Publish portable Telegram MCP with bundled Teleproto CLI

This commit is contained in:
Vickenty Zherebov 2026-11-05 14:26:28 +03:00
commit 30795b7316
255 changed files with 44073 additions and 0 deletions

16
.gitignore vendored Normal file
View file

@ -0,0 +1,16 @@
.env
.env.*
*.session
*.session.*
*.log
*.sock
*.pid
*.tgz
__pycache__/
*.py[cod]
.venv/
node_modules/
dist/
coverage/
.private/
.DS_Store

25
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,25 @@
# Разработка
Клонируйте https://git.flowmasters.ru/vik/telegram-mcp.git, перейдите в его корень и выполните:
```sh
python3 scripts/manage.py setup
python3 scripts/manage.py test
python3 scripts/export_source.py /tmp/telegram-mcp-source.tar.gz
```
Проверки выполняются без реальных Telegram-отправок. TypeScript: strict, ESM, tsup, vitest. MCP: Python 3.11+, unittest и настоящий stdio smoke на закреплённом SDK. Не добавляйте live Telegram-вызовы в тесты по умолчанию.
Сохраните stdout как структурированные данные. Не меняйте форму CLI envelope, daemon wire protocol, destroy()/блокировки сессий и правило отсутствия повторной отправки после таймаута. Новые операции MCP должны быть типизированы; изменения начинать с предпросмотра. Файлы `dist` не редактируются и не публикуются как исходники.
Для изменения Python-зависимостей редактируйте requirements.in и пересобирайте requirements.lock через `uv pip compile requirements.in --generate-hashes -o requirements.lock --python-version 3.11`. npm-зависимости фиксируются cli/package-lock.json. Сохраняйте Teleproto pin и локальные дополнения при обновлении upstream.
Каждое изменение — отдельная ветка и review перед merge; исходники и данные аккаунтов не смешиваются. Публичная публикация этого подготовительного комплекта требует решения владельца.
Экспорт работает по allowlist, не включает Git history, node_modules, .venv, runtime state или произвольные файлы. Проверки экспорта не заменяют review: перед релизом просмотрите весь manifest и назначьте приватный security contact.
## Related
- [README](README.md)
- [Подключение](docs/setup-development.md)
- [Происхождение](UPSTREAM.md)

23
LICENSE Normal file
View file

@ -0,0 +1,23 @@
MIT License
Copyright (c) 2026 Telegram MCP contributors
Bundled CLI: Copyright (c) 2026 miolamio; see cli/LICENSE.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

40
README.md Normal file
View file

@ -0,0 +1,40 @@
# Telegram MCP
61 инструмент для работы с Telegram из ИИ-помощника: новости, переписки, папки, черновики, файлы и планы поездок. Пользовательский клиент, работающий от вашего аккаунта.
Открытый репозиторий: [vik/telegram-mcp](https://git.flowmasters.ru/vik/telegram-mcp). В комплект входят MCP и исходники нашей сборки CLI. Готовые бинарные релизы пока не выпускаются.
## Быстрый старт
1. **Выберите окружение:** macOS или Linux, Python 3.11+, Node.js 20+. Windows — через WSL; нативная Windows не поддерживается этим комплектом.
2. **Скачайте исходники:** [ZIP ветки main](https://git.flowmasters.ru/vik/telegram-mcp/archive/main.zip), распакуйте и откройте терминал в папке проекта. **Установите:** `python3 scripts/manage.py setup`. Зависимости и сборка останутся внутри папки проекта; глобальный CLI не заменяется.
3. **Войдите в Telegram:** `python3 scripts/manage.py login`. Команду запускает человек в своём терминале; код и пароль вводятся интерактивно. Для WSS: `python3 scripts/manage.py login --transport wss`.
4. **Подключите MCP и попробуйте:** ручная настройка описана в [инструкции подключения](docs/setup-development.md). Первый запрос: «Прочитай выбранный мной канал и составь краткую сводку со ссылками. Пока ничего не отправляй».
Установка не входит в аккаунт и не редактирует настройки вашего ИИ-приложения. `python3 scripts/manage.py check` проверяет 61 схему и пробный предпросмотр без Telegram.
## Возможности
| Задача | Что даёт связка |
|---|---|
| Новости без повторов | История и поиск → сводка ИИ с источниками |
| Где нужен мой ответ | Контекст обсуждений → вопросы и договорённости |
| Черновики | Подготовка ответа → сохранение в нужном чате |
| Поездка | Даты и варианты → план, опрос, папка |
| Порядок | Папки, пересечения, архив, закрепления, уведомления |
| Медиа | Поиск, скачивание, отправка файлов и доступные истории |
ИИ анализирует полученные данные; MCP сам не генерирует картинки, не распознаёт речь и не запускает регулярные дайджесты. Для этих задач нужны отдельные инструменты или расписание.
## Документация
- [Четыре сценария](examples/scenarios.md)
- [Каталог 61 инструмента](docs/tools.md)
- [Документация и архитектура](docs/README.md)
- [Конфиденциальность и управление действиями](SECURITY.md)
- [Разработка и тестирование](CONTRIBUTING.md)
- [Происхождение и лицензия](UPSTREAM.md)
## Related
- [Подключение и обслуживание](docs/setup-development.md)

22
SECURITY.md Normal file
View file

@ -0,0 +1,22 @@
# Конфиденциальность и действия
MCP предоставляет ИИ доступ к вашему пользовательскому аккаунту Telegram в пределах его прав. Тексты, возвращённые инструментами, попадают в выбранное вами ИИ-приложение: локальный транспорт не означает, что модель работает локально.
Сессия даёт доступ к аккаунту. Не публикуйте каталог состояния, config, `.env`, session strings, коды входа или пароли. Вход выполняйте вручную в терминале. Не отдавайте эти данные в запросах ИИ. Стандартный каталог состояния находится вне checkout.
Новые 49 методов требуют явного account. Команды изменения из этого набора по умолчанию возвращают предпросмотр (`dry_run=true`). Это не система авторизации: поручение человека всё равно требуется. Старые `send_message`, `send_html`, `send_file`, `schedule_message` выполняют отправку непосредственно — вызывайте их только после явного поручения. Каталог описывает эту разницу.
Перед применением изменений папок требуется revision свежего чтения/предпросмотра. Общие папки не изменяются. Проверка optimistic, не атомарная транзакция Telegram. Аудит ограничен заданным количеством диалогов: `complete=false` обозначает частичный результат.
Не повторяйте отправку после неизвестного исхода. MCP повторяет вызов только при доказанном отсутствии отправки в daemon (`DAEMON_NOT_RUNNING`). Таймаут, разрыв связи и ошибки API не повторяются автоматически.
В MCP нет generic eval/raw invoke, экспорта авторизации или массового удаления участников. Сам CLI имеет более широкие команды, включая управление сессиями: наличие CLI не означает разрешения агенту их использовать. Не используйте комплект для спама.
Скачанные файлы — данные из внешнего источника; не исполняйте их автоматически. Часть инструментов пишет локальные файлы, хотя для Telegram это чтение. Истории с запретом сохранения не скачиваются; скачивание ограничено 30 МиБ. OCR и транскрибация требуют отдельных инструментов.
Не публикуйте потенциальные секреты и exploit-данные в общедоступных issues. Для получения приватного канала связи создайте [issue](https://git.flowmasters.ru/vik/telegram-mcp/issues) с темой «Нужен приватный канал для security report», без технических деталей, вложений или секретов. Передайте подробности только после согласования приватного канала с владельцем.
## Related
- [Подключение](docs/setup-development.md)
- [README](README.md)

17
UPSTREAM.md Normal file
View file

@ -0,0 +1,17 @@
# Upstream attribution
CLI: [miolamio/tg-cli](https://github.com/miolamio/tg-cli), MIT, original notice retained in [cli/LICENSE](cli/LICENSE).
Snapshot base commit: `d8dd9a4cbbddfe38e77d8e226cbb8e89d72de297`. This is a source snapshot with local modifications, not a claim that upstream released this version. CLI version: `0.6.1-teleproto.1`; Teleproto: `1.232.1`.
Local additions include Teleproto migration, daemon bridge, folder organization/audit, notification settings, drafts and scheduled queue operations. MCP is packaged separately here, with portable isolated state and no dependency on a personal workspace.
The original npm name is retained to preserve source/package provenance; `private: true` prevents accidental npm publication. This bundle does not report issues to the upstream project automatically.
Dependency licenses belong to their respective authors; see the generated [license inventory](docs/dependency-licenses.json). The Python dependency inventory is in [python-dependency-licenses.json](docs/python-dependency-licenses.json). The CLI test-only `gramjs-reference` dependency brings `@cryptography/aes` (GPL-3.0-or-later); it is not the runtime SDK and is not vendored in the source archive. Inventories cover installed packages on the verification platform; lockfiles also contain optional packages for other platforms.
No upstream Git history, private operational documents, credentials or sessions are included.
## Related
- [README](README.md)

21
cli/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 miolamio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

4084
cli/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

67
cli/package.json Normal file
View file

@ -0,0 +1,67 @@
{
"name": "@miolamio/tg-cli",
"version": "0.6.1-teleproto.1",
"type": "module",
"description": "Telegram CLI client for Claude Code agents and power users",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"bin": {
"tg": "./dist/bin/tg.js",
"telegram-cli": "./dist/bin/tg.js"
},
"engines": {
"node": ">=20"
},
"scripts": {
"build": "tsup",
"prepack": "npm run build",
"dev": "tsup --watch",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"typecheck": "tsc --noEmit"
},
"files": [
"dist",
"CHANGELOG.md"
],
"keywords": [
"telegram",
"cli",
"mtproto",
"teleproto"
],
"license": "MIT",
"dependencies": {
"@toon-format/toon": "^2.3.1",
"commander": "^14.0.3",
"conf": "^15.1.0",
"picocolors": "^1.1.1",
"proper-lockfile": "^4.1.2",
"teleproto": "1.232.1",
"ws": "8.22.1",
"zod": "^4.3.6"
},
"overrides": {
"esbuild": "^0.28.2",
"vite": "^6.4.3"
},
"devDependencies": {
"@types/node": "^25.4.0",
"@types/proper-lockfile": "^4.1.4",
"@types/ws": "8.18.1",
"@vitest/coverage-v8": "^3.2.7",
"gpt-tokenizer": "^3.4.0",
"gramjs-reference": "npm:telegram@2.26.22",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^3.2.7"
},
"private": true
}

180
cli/src/bin/tg.ts Normal file
View file

@ -0,0 +1,180 @@
import { createBridgeCommand } from '../commands/bridge/index.js';
import { Command, CommanderError } from 'commander';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { createAuthCommand } from '../commands/auth/index.js';
import { createSessionCommand } from '../commands/session/index.js';
import { createChatCommand } from '../commands/chat/index.js';
import { createMessageCommand } from '../commands/message/index.js';
import { createMediaCommand } from '../commands/media/index.js';
import { createUserCommand } from '../commands/user/index.js';
import { createContactCommand } from '../commands/contact/index.js';
import { createDaemonCommand } from '../commands/daemon/index.js';
import { createCompletionCommand } from '../commands/completion/index.js';
import { setOutputMode, setJsonlMode, setToonMode, setFieldSelection, outputError } from '../lib/output.js';
import { setQuietMode, setVerboseMode } from '../lib/cli-mode.js';
import { ErrorCode } from '../lib/error-codes.js';
import { validateProfile } from '../lib/validate.js';
import { validateTransport } from '../lib/transport.js';
import { formatError, TgError } from '../lib/errors.js';
import { installCliConsoleGuard } from '../lib/cli-console.js';
import { DaemonCommandHandled, routeThroughDaemon } from '../lib/daemon/route.js';
import { formatHelpBanner } from '../lib/branding.js';
installCliConsoleGuard();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Read package version and gramjs version for --version output
let pkgVersion = '0.0.0';
let gramjsVersion = 'unknown';
try {
const pkg = JSON.parse(
readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8'),
);
pkgVersion = pkg.version;
} catch {}
try {
const gramjsPkg = JSON.parse(
readFileSync(
createRequire(import.meta.url).resolve('teleproto/package.json'),
'utf-8',
),
);
gramjsVersion = gramjsPkg.version;
} catch {}
const versionString = `${pkgVersion} (teleproto ${gramjsVersion})`;
// Create root program
const program = new Command()
.name('tg')
.description('Telegram CLI - Agent-first Telegram client')
.version(versionString, '-V, --version');
// Global options available on all commands via optsWithGlobals()
program
.option('--json', 'JSON output (default)', true)
.option('--no-json', 'Human-readable output (alias for --human)')
.option('--human', 'Human-readable output')
.option('-v, --verbose', 'Show extra info')
.option('-q, --quiet', 'Suppress stderr output')
.option('--profile <name>', 'Named profile', 'default')
.option('--config <path>', 'Config file path')
.option('--transport <mode>', 'Telegram transport: tcp or wss (default: saved profile or tcp)')
.option('--fields <fields>', 'Select output fields (comma-separated, dot notation for nested)')
.option('--jsonl', 'Output one JSON object per line (list commands only)')
.option('--toon', 'Token-efficient TOON output (LLM-optimized)')
.option('--daemon', 'Route command through persistent daemon connection');
program.addHelpText('before', ({ error }) => error ? '' : formatHelpBanner(!!program.opts().quiet));
// Global options are parsed at any position in the command line
// Set output mode before any action runs based on --human or --no-json flags
function configureOutput(): void {
const opts = program.optsWithGlobals();
const isHuman = opts.human === true || opts.json === false;
setOutputMode(isHuman);
setQuietMode(!!opts.quiet);
setVerboseMode(!!opts.verbose);
// Invalid combinations use a deterministic error format.
setToonMode(!!opts.toon && !isHuman && !opts.jsonl);
setJsonlMode(!!opts.jsonl && !isHuman && !opts.toon);
if (opts.fields) setFieldSelection(opts.fields.split(',').map((f: string) => f.trim()));
}
program.hook('preAction', async (thisCommand, actionCommand) => {
configureOutput();
const opts = thisCommand.optsWithGlobals();
validateProfile(opts.profile);
if (opts.transport !== undefined) {
validateTransport(opts.transport);
if (opts.daemon || (actionCommand.name() === 'watch' && actionCommand.parent?.name() === 'message')) {
throw new TgError('Choose --transport when starting the daemon; commands use its existing connection', ErrorCode.INVALID_OPTIONS);
}
}
const isHuman = opts.human === true || opts.json === false;
// --toon mutual exclusion checks
if (opts.toon && isHuman) {
throw new TgError('--toon and --human are mutually exclusive', ErrorCode.INVALID_OPTIONS);
}
if (opts.toon && opts.jsonl) {
throw new TgError('--toon and --jsonl are mutually exclusive', ErrorCode.INVALID_OPTIONS);
}
// --jsonl and --human are mutually exclusive
if (opts.jsonl && isHuman) {
throw new TgError('--jsonl and --human are mutually exclusive', ErrorCode.INVALID_OPTIONS);
}
if (await routeThroughDaemon(actionCommand)) throw new DaemonCommandHandled();
});
// Wire command groups with help group headings
const authCmd = createAuthCommand();
authCmd.helpGroup('Auth');
program.addCommand(authCmd);
const sessionCmd = createSessionCommand();
sessionCmd.helpGroup('Session');
program.addCommand(sessionCmd);
const chatCmd = createChatCommand();
chatCmd.helpGroup('Chat');
program.addCommand(chatCmd);
const messageCmd = createMessageCommand();
messageCmd.helpGroup('Message');
program.addCommand(messageCmd);
const mediaCmd = createMediaCommand();
mediaCmd.helpGroup('Media');
program.addCommand(mediaCmd);
const userCmd = createUserCommand();
userCmd.helpGroup('User');
program.addCommand(userCmd);
const contactCmd = createContactCommand();
contactCmd.helpGroup('Contact');
program.addCommand(contactCmd);
const bridgeCmd = createBridgeCommand();
bridgeCmd.helpGroup('Utility');
program.addCommand(bridgeCmd);
const daemonCmd = createDaemonCommand();
daemonCmd.helpGroup('Daemon');
program.addCommand(daemonCmd);
const completionCmd = createCompletionCommand();
completionCmd.helpGroup('Utility');
program.addCommand(completionCmd);
// Groups are constructed separately, so install the exit hook on every level.
// Commander parse errors must use the same output contract as async actions.
function configureCommandErrors(command: Command): void {
command.exitOverride();
command.configureOutput({ outputError: () => {} });
for (const child of command.commands) configureCommandErrors(child);
}
configureCommandErrors(program);
try {
await program.parseAsync();
} catch (err: unknown) {
if (err instanceof DaemonCommandHandled) {
// The daemon result has already been rendered, including its exit status.
} else if (err instanceof CommanderError && err.exitCode === 0) {
// Explicit --help and --version have already rendered their normal output.
process.exitCode = 0;
} else {
configureOutput();
const { message, code } = formatError(err);
outputError(message, err instanceof CommanderError ? ErrorCode.INVALID_OPTIONS : code ?? ErrorCode.UNKNOWN_ERROR);
}
}

View file

@ -0,0 +1,36 @@
import { Command } from 'commander';
import { loginAction } from './login.js';
import { statusAction } from './status.js';
import { logoutAction } from './logout.js';
/**
* Create the `auth` command group with login, status, and logout subcommands.
*
* Usage:
* tg auth login - Log in with phone number + code + optional 2FA
* tg auth status - Check current authentication status
* tg auth logout - Log out and destroy session
*/
export function createAuthCommand(): Command {
const auth = new Command('auth')
.description('Authentication commands');
auth
.command('login')
.description('Log in with phone number + code + optional 2FA')
.option('--client <name>', 'Use official client preset (desktop, android, ios, macos, web-z)')
.option('--phone <number>', 'Phone number in international format (skips the phone prompt)')
.action(loginAction);
auth
.command('status')
.description('Check current authentication status')
.action(statusAction);
auth
.command('logout')
.description('Log out and destroy session')
.action(logoutAction);
return auth;
}

View file

@ -0,0 +1,124 @@
import type { Command } from 'commander';
import { LogLevel } from 'teleproto/extensions/Logger.js';
import { createConfig, getCredentialsOrThrow } from '../../lib/config.js';
import { resolveTransport } from '../../lib/transport.js';
import { createPrompt } from '../../lib/prompt.js';
import { createClientForAuth } from '../../lib/client.js';
import { connectOrThrow } from '../../lib/connect.js';
import { SessionStore } from '../../lib/session-store.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { formatError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js';
import { showLoginBanner } from '../../lib/branding.js';
import { validatePhone } from '../../lib/validate.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Login action handler for `tg auth login`.
*
* Requires an interactive terminal (TTY). Fails fast with a structured
* error when stdin is not a TTY (CI, piped input, agent automation).
*
* Invokes gramjs client.start() with interactive prompts for
* phone number, verification code, and optional 2FA password.
* Saves the resulting session string to disk on success.
*/
export async function loginAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { client?: string; phone?: string };
const { profile, quiet } = opts;
if (await refuseDirectConnectIfDaemon(opts)) return;
// Fail fast when not running in an interactive terminal
if (!process.stdin.isTTY) {
outputError(
'Interactive login requires a terminal (TTY). Use `tg session import` for non-interactive auth.',
ErrorCode.NOT_INTERACTIVE,
);
return;
}
const config = createConfig(opts.config);
const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, ''));
try {
await store.withLock(profile, async () => {
const prompt = createPrompt();
let client: Awaited<ReturnType<typeof createClientForAuth>> | undefined;
let phone = '';
const ask = async (question: string, secret = false): Promise<string> => {
// Only this client's SDK logger is paused; restore it even on rejection.
const logger = client?.logger;
const previousLevel = logger?.logLevel;
logger?.setLevel(LogLevel.NONE);
try { return await (secret ? prompt.askSecret(question) : prompt.ask(question)); }
finally { if (logger && previousLevel !== undefined) logger.setLevel(previousLevel); }
};
try {
showLoginBanner(quiet);
// Collect the phone before credential fetching, connect(), or the SDK's
// authorization check can block or fill the terminal with diagnostics.
phone = validatePhone(opts.phone ?? await ask('Phone number (international format): '));
const { apiId, apiHash } = await getCredentialsOrThrow(config, opts.client, profile);
const transport = resolveTransport(config, profile, opts.transport);
client = await createClientForAuth(apiId, apiHash, transport);
logStatus('Starting authentication...', quiet);
await connectOrThrow(client);
logStatus('Connected. Starting sign-in...', quiet);
let phoneRequests = 0;
await client.start({
// A literal --phone makes gramjs propagate sendCode failures instead
// of repeatedly submitting the same invalid phone via a callback.
phoneNumber: opts.phone !== undefined ? phone : async () => {
if (phoneRequests++ > 0) phone = validatePhone(await ask('Phone number (international format): '));
logStatus('Requesting login code...', quiet);
return phone;
},
phoneCode: async (isCodeViaApp?: boolean) => {
const msg = isCodeViaApp
? 'Code (from Telegram app): '
: 'Code (from SMS): ';
return ask(msg);
},
password: async (hint?: string) => {
const msg = hint
? `2FA password (hint: ${hint}): `
: '2FA password: ';
return ask(msg, true);
},
onError: (err: Error) => {
logStatus(`Auth error: ${err.message}`, quiet);
},
});
// Save session string
const sessionString = client.session.save() as unknown as string;
store.saveUnlocked(profile, sessionString);
// Update profile in config
const clientName = opts.client ?? config.get(`profiles.${profile}.client`);
config.set(`profiles.${profile}`, {
...(clientName ? { client: clientName } : {}),
transport,
phone,
created: new Date().toISOString(),
});
logStatus('Login successful!', quiet);
outputSuccess({
loggedIn: true,
profile,
phone,
});
} finally {
if (client) await client.destroy().catch(() => {});
prompt.close();
}
});
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code ?? ErrorCode.UNKNOWN_ERROR);
}
}

View file

@ -0,0 +1,52 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { createConfig, getCredentialsOrThrow } from '../../lib/config.js';
import { resolveTransport } from '../../lib/transport.js';
import { withClient } from '../../lib/client.js';
import { SessionStore } from '../../lib/session-store.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { formatError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Logout action handler for `tg auth logout`.
*
* Connects with the existing session, invokes auth.LogOut on the server,
* then deletes the local session file and removes the profile from config.
*/
export async function logoutAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const { profile, quiet } = opts;
if (await refuseDirectConnectIfDaemon(opts)) return;
const config = createConfig(opts.config);
const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, ''));
try {
await store.withLock(profile, async (sessionString, holdUntil) => {
if (!sessionString) {
outputError('Not logged in', ErrorCode.NOT_LOGGED_IN);
return;
}
const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile);
await withClient({ apiId, apiHash, sessionString, transport: resolveTransport(config, opts.profile, opts.transport) }, async (client) => {
logStatus('Logging out...', quiet);
await client.invoke(new Api.auth.LogOut());
}, { holdUntil });
// Delete file without re-acquiring lock (we're already inside withLock)
store.deleteUnlocked(profile);
config.delete(`profiles.${profile}` as never);
logStatus('Logged out successfully.', quiet);
outputSuccess({ loggedOut: true });
});
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code ?? ErrorCode.UNKNOWN_ERROR);
}
}

View file

@ -0,0 +1,65 @@
import type { Command } from 'commander';
import { createConfig, getCredentialsOrThrow } from '../../lib/config.js';
import { resolveTransport } from '../../lib/transport.js';
import { withClient } from '../../lib/client.js';
import { SessionStore } from '../../lib/session-store.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { formatError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { bigIntToString } from '../../lib/serialize.js';
import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Status action handler for `tg auth status`.
*
* Checks whether the current session is authorized.
* If no session file exists, outputs { authorized: false } without connecting.
* If session exists, connects and checks authorization state.
*/
export async function statusAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const { profile, quiet } = opts;
if (await refuseDirectConnectIfDaemon(opts)) return;
const config = createConfig(opts.config);
const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, ''));
try {
await store.withLock(profile, async (sessionString, holdUntil) => {
if (!sessionString) {
outputSuccess({ authorized: false, reason: 'No session found' });
return;
}
const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile);
await withClient({ apiId, apiHash, sessionString, transport: resolveTransport(config, opts.profile, opts.transport) }, async (client, signal) => {
const authorized = await client.checkAuthorization();
signal.throwIfAborted();
if (authorized) {
const me = await client.getMe();
signal.throwIfAborted();
outputSuccess({
authorized: true,
user: {
id: bigIntToString((me as any)?.id),
phone: (me as any)?.phone,
username: (me as any)?.username,
firstName: (me as any)?.firstName,
},
});
} else {
outputSuccess({
authorized: false,
reason: 'Session expired or invalid',
});
}
}, { holdUntil });
});
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code ?? ErrorCode.UNKNOWN_ERROR);
}
}

View file

@ -0,0 +1,121 @@
import { Api, type TelegramClient } from 'teleproto';
import { getPeerId, getInputPeer, getDisplayName } from 'teleproto/Utils.js';
import bigInt from 'big-integer';
import { randomUUID } from 'node:crypto';
import { TgError } from '../../lib/errors.js';
// In-memory state on the existing daemon/session. Never serialize input peers,
// access hashes, message bodies or session data into a continuation token.
interface Scan {
token: string; created: number; touched: number; rows: any[]; seen: Set<string>;
offsetId: number; offsetDate: number; offsetPeer: Api.TypeInputPeer;
excludePinned: boolean; complete: boolean; busy: boolean;
pages: number; skipped: number; lastOffset?: string;
}
interface Owner { scans: Map<string, Scan>; current?: string; retryAt: number }
const owners = new WeakMap<object, Map<string, Owner>>();
const TTL = 30 * 60_000;
function owner(client: TelegramClient, account: string): Owner {
const key = client.session ?? client;
let accounts = owners.get(key);
if (!accounts) owners.set(key, accounts = new Map());
let value = accounts.get(account);
if (!value) accounts.set(account, value = { scans: new Map(), retryAt: 0 });
return value;
}
export function floodSeconds(error: unknown): number | undefined {
const e = error as any;
const name = `${e?.errorMessage ?? ''} ${e?.message ?? ''} ${e?.code ?? ''}`;
if (!/FLOOD(?:_PREMIUM)?_WAIT/i.test(name)) return;
const seconds = Number(e?.seconds ?? name.match(/FLOOD(?:_PREMIUM)?_WAIT_?(\d+)/i)?.[1]);
return Number.isFinite(seconds) && seconds >= 0 ? Math.max(1, Math.ceil(seconds)) : undefined;
}
export function recordReadFlood(client: TelegramClient, account: string, error: unknown) {
const seconds = floodSeconds(error);
if (seconds === undefined) throw error;
const o = owner(client, account);
o.retryAt = Math.max(o.retryAt, Date.now() + seconds * 1000);
return { retry_after_seconds: Math.ceil((o.retryAt - Date.now()) / 1000), retry_at: new Date(o.retryAt).toISOString() };
}
/** At most five server pages per call. FloodWait preserves the last committed
* cursor and returns a deadline; the caller resumes, never replays a write. */
export async function scanDialogs(client: TelegramClient, account: string, target: number,
cursor?: string, refresh = false) {
if (cursor && refresh) throw new TgError('Use cursor to resume OR refresh to restart', 'INVALID_OPTIONS');
const o = owner(client, account), now = Date.now();
for (const [key, s] of o.scans) if (!s.busy && now - s.touched > TTL) o.scans.delete(key);
let s = o.scans.get(cursor ?? (refresh ? '' : o.current ?? ''));
if (cursor && !s) throw new TgError('Dialog cursor expired or belongs to another session/account; restart explicitly', 'CURSOR_EXPIRED');
if (!s) {
if (o.scans.size >= 4) throw new TgError('Too many active dialog snapshots; reuse a cursor or wait for expiry', 'SCAN_LIMIT');
s = { token: randomUUID(), created: now, touched: now, rows: [], seen: new Set(),
offsetId: 0, offsetDate: 0, offsetPeer: new Api.InputPeerEmpty(), excludePinned: false,
complete: false, busy: false, pages: 0, skipped: 0 };
o.scans.set(s.token, s); o.current = s.token;
}
if (s.busy) throw new TgError('Dialog snapshot is in use; resume sequentially', 'SCAN_BUSY');
s.busy = true; s.touched = now;
try {
for (let page = 0; page < 5 && !s.complete && s.rows.length < target; page++) {
if (Date.now() < o.retryAt) break;
let r: any;
try {
r = await client.invoke(new Api.messages.GetDialogs({ offsetId: s.offsetId,
offsetDate: s.offsetDate, offsetPeer: s.offsetPeer, excludePinned: s.excludePinned,
limit: 100, hash: bigInt.zero }));
} catch (e) {
const seconds = floodSeconds(e);
if (seconds === undefined) throw e;
o.retryAt = Date.now() + seconds * 1000;
break;
}
if (!(r instanceof Api.messages.Dialogs || r instanceof Api.messages.DialogsSlice))
throw new TgError('Unexpected dialog response; cursor preserved', 'DIALOG_RESPONSE');
const entities = new Map<string, any>();
for (const e of [...r.users, ...r.chats]) entities.set(getPeerId(e), e);
const messages = new Map<string, any>();
for (const m of r.messages) if (m.peerId) messages.set(`${getPeerId(m.peerId)}:${m.id}`, m);
const unsupported = r.dialogs.filter((d: any) => !(d instanceof Api.Dialog) && !(d instanceof Api.DialogFolder)).length;
const dialogs = r.dialogs.filter((d: any) => d instanceof Api.Dialog);
const last = dialogs.at(-1);
let next: { id: number; date: number; peer: Api.TypeInputPeer; key: string } | undefined;
const end = r instanceof Api.messages.Dialogs || r.dialogs.length < 100;
if (!end && last) {
const id = getPeerId(last.peer), entity = entities.get(id);
if (!entity) throw new TgError('Missing cursor entity; snapshot incomplete', 'DIALOG_ENTITY');
next = { id: last.topMessage, date: messages.get(`${id}:${last.topMessage}`)?.date ?? 0,
peer: getInputPeer(entity), key: `${id}:${last.topMessage}` };
if (next.key === s.lastOffset) throw new TgError('Dialog cursor did not advance; snapshot incomplete', 'CURSOR_STALLED');
} else if (!end && !last) throw new TgError('No usable dialog cursor; snapshot incomplete', 'CURSOR_STALLED');
// Commit only after cursor validation. Discard all message bodies here.
for (const d of dialogs) {
const id = getPeerId(d.peer), e = entities.get(id);
if (s.seen.has(id)) continue;
if (!e || e instanceof Api.UserEmpty || e instanceof Api.ChatEmpty) { s.skipped++; continue; }
const m = messages.get(`${id}:${d.topMessage}`), mute = d.notifySettings?.muteUntil;
s.rows.push({ id, title: getDisplayName(e), username: e.username ?? null,
type: e.bot ? 'bot' : e instanceof Api.User ? 'user' : e.broadcast ? 'channel' : 'group',
contact: !!e.contact, self: !!e.self, archived: d.folderId === 1, pinned: !!d.pinned,
unread_count: d.unreadCount, unread_mentions: d.unreadMentionsCount, unread_mark: !!d.unreadMark,
mute_until: mute ?? null, muted: mute == null ? null : mute > Date.now() / 1000,
notifications_inherited: mute == null, last_message_id: d.topMessage,
last_message_at: m?.date ? new Date(m.date * 1000).toISOString() : null,
has_draft: !!(d.draft instanceof Api.DraftMessage && d.draft.message) });
s.seen.add(id);
}
s.skipped += unsupported; s.pages++; s.complete = end;
if (next) { s.offsetId = next.id; s.offsetDate = next.date; s.offsetPeer = next.peer;
s.lastOffset = next.key; s.excludePinned = true; }
}
s.touched = Date.now();
return { rows: s.rows, cursor: s.token, complete: s.complete && s.skipped === 0,
exhausted: s.complete, scanned: s.rows.length, skipped: s.skipped, pages_fetched: s.pages,
snapshot_started_at: new Date(s.created).toISOString(),
retry_after_seconds: Math.max(0, Math.ceil((o.retryAt - Date.now()) / 1000)),
retry_at: o.retryAt > Date.now() ? new Date(o.retryAt).toISOString() : null };
} finally { s.busy = false; }
}

View file

@ -0,0 +1,151 @@
import { Command } from 'commander';
import { Api, type TelegramClient } from 'teleproto';
import bigInt from 'big-integer';
import { CustomFile } from 'teleproto/client/uploads.js';
import { readFile, writeFile, mkdtemp } from 'node:fs/promises';
import { basename, isAbsolute, join } from 'node:path';
import { tmpdir } from 'node:os';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess } from '../../lib/output.js';
import { TgError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
import { runOrganize } from './organize.js';
export const BRIDGE_OPERATIONS = ['html', 'schedule', 'send-dialog', 'delete', 'download-media', 'download-photo', 'download-photo-at', 'contact-photo', 'recent-dms', 'stories', 'organize'] as const;
function invalid(message: string): never { throw new TgError(message, ErrorCode.INVALID_OPTIONS); }
function storyFailure(code: string): never { throw new TgError(code, code); }
function text(value: unknown): string { if (typeof value !== 'string' || !value) invalid('Expected nonempty string'); return value as string; }
function integer(value: unknown, min = 0, max = 2147483647): number {
if (!/^\d+$/.test(String(value))) invalid('Expected integer');
const n = Number(value); if (!Number.isSafeInteger(n) || n < min || n > max) invalid('Integer out of range'); return n;
}
function file(value: unknown): string { const s = text(value); if (!isAbsolute(s)) invalid('File path must be absolute'); return s; }
async function target(client: TelegramClient, value: string, bare = false): Promise<any> {
// Bare positive IDs can refer to channels as well as users. Require an
// unambiguous cached dialog, never silently send to a different peer kind.
if (bare || /^\d+$/.test(value)) {
const dialogs = await client.getDialogs({ limit: 500 });
const id = value.startsWith('-100') ? value.slice(4) : value.replace(/^-/, '');
const matches = dialogs.filter(d => String(d.entity?.id) === id);
if (matches.length !== 1 || !matches[0].entity) invalid('Dialog ID is missing or ambiguous');
return matches[0].entity;
}
return client.getEntity(value);
}
function storyDescription(story: any, chat: string) {
const media = story.media;
const type = media instanceof Api.MessageMediaPhoto ? 'photo' : media instanceof Api.MessageMediaDocument ? media.document instanceof Api.Document && media.document.mimeType.startsWith('video/') ? 'video' : 'document' : 'unknown';
const date = (n: number) => n ? new Date(n * 1000).toISOString() : null;
return { id: story.id, state: story.className, date: date(story.date), expires_at: date(story.expireDate), caption: story.caption ?? null,
pinned: Boolean(story.pinned), noforwards: Boolean(story.noforwards), media_type: type,
mime_type: media?.document?.mimeType ?? (type === 'photo' ? 'image/jpeg' : null), link: `https://t.me/${chat}/s/${story.id}` };
}
/** Fixed operations for the existing local wrappers; no arbitrary invoke/eval. */
export async function runBridge(client: TelegramClient, operation: string, payload: unknown): Promise<unknown> {
if (operation === 'organize') return runOrganize(client, payload);
if (!BRIDGE_OPERATIONS.includes(operation as any)) invalid('Unsupported bridge operation');
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) invalid('Expected payload object');
const p = payload as Record<string, any>;
if (!['main', 'reserve'].includes(p.account)) invalid('Account must be main or reserve');
const account = p.account;
if (operation === 'stories') {
const chat = text(p.chat);
if (!['list', 'get', 'download'].includes(p.action)) invalid('Invalid story action');
const peer = await client.getInputEntity(chat);
if (p.action === 'list') {
if (!['pinned', 'active'].includes(p.kind)) invalid('Invalid story kind');
const limit = integer(p.limit, 1, 100), offsetId = integer(p.offset_id ?? 0);
const result: any = p.kind === 'pinned' ? await client.invoke(new Api.stories.GetPinnedStories({ peer, offsetId, limit })) : await client.invoke(new Api.stories.GetPeerStories({ peer }));
const all = p.kind === 'pinned' ? result.stories : result.stories.stories;
const items = all.slice(0, limit).map((s: any) => storyDescription(s, chat));
return { kind: p.kind, total: p.kind === 'pinned' ? result.count : all.length, stories: items,
next_offset_id: p.kind === 'pinned' && items.length ? items.at(-1).id : null, truncated: p.kind === 'active' && all.length > items.length };
}
const storyId = integer(p.story_id, 1);
const result = await client.invoke(new Api.stories.GetStoriesByID({ peer, id: [storyId] }));
const story = result.stories.find(s => s.id === storyId);
if (!(story instanceof Api.StoryItem)) storyFailure('STORY_UNAVAILABLE');
const meta = storyDescription(story, chat);
if (p.action === 'get') return meta;
if (story.noforwards) storyFailure('MEDIA_PROTECTED');
if (!['photo', 'video'].includes(meta.media_type)) storyFailure('UNSUPPORTED_MEDIA');
const max = 30 * 1024 * 1024;
if (Number((story.media as any)?.document?.size ?? 0) > max) storyFailure('MEDIA_TOO_LARGE');
const bytes = await client.downloadMedia(story.media, {});
if (!Buffer.isBuffer(bytes) || !bytes.length) storyFailure('EMPTY_MEDIA');
if (bytes.length > max) storyFailure('MEDIA_TOO_LARGE');
const dir = await mkdtemp(join(tmpdir(), 'telegram-story-'));
const path = join(dir, `story-${story.id}.${meta.media_type === 'photo' ? 'jpg' : 'mp4'}`);
await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
return { ...meta, path, size: bytes.length };
}
if (operation === 'recent-dms') {
const since = integer(p.since ?? 0, 0, Number.MAX_SAFE_INTEGER), limit = integer(p.limit ?? 100, 1, 1000);
const dialogs = await client.getDialogs({ limit });
return dialogs.filter(d => d.entity instanceof Api.User && !d.entity.bot && (d.message?.date ?? 0) > since).map(d => {
const e = d.entity as Api.User;
return { user_id: String(e.id), username: e.username ?? null, first_name: e.firstName ?? null, last_name: e.lastName ?? null,
last_msg_date: d.message?.date ?? 0, last_msg_preview: (d.message?.message ?? '').slice(0, 200), unread_count: d.unreadCount ?? 0, is_self: !!e.self };
});
}
const chat = text(p.chat);
// Validate all write inputs before resolving peers or uploading anything.
let message: string | undefined, schedule: Date | undefined;
if (['html', 'schedule', 'send-dialog'].includes(operation)) {
message = text(p.text); if (message.length > 4096) invalid('Message too long');
if (operation === 'schedule') {
schedule = new Date(text(p.when));
if (!Number.isFinite(schedule.getTime()) || schedule.getTime() <= Date.now() + 10000) invalid('schedule must be at least 10s in the future');
}
}
if (operation === 'delete' && typeof p.revoke !== 'boolean') invalid('Explicit revoke boolean required');
const ids = operation === 'delete' ? text(p.ids).split(',').map(id => integer(id, 1)) : [];
const output = ['download-media', 'download-photo', 'download-photo-at'].includes(operation) ? file(p.path) : undefined;
const input = operation === 'contact-photo' ? file(p.path) : undefined;
const messageId = operation === 'download-media' ? integer(p.id, 1) : undefined;
const index = operation === 'download-photo-at' ? integer(p.index, 0, 49) : undefined;
const entity = await target(client, chat, operation === 'send-dialog');
if (message !== undefined) {
const sent = await client.sendMessage(entity, { message, parseMode: operation === 'html' ? 'html' : undefined, schedule: schedule ? Math.floor(schedule.getTime() / 1000) : undefined });
if (!sent) throw new TgError('Send outcome unknown; verify before retrying', ErrorCode.MESSAGE_RESULT_UNAVAILABLE);
if (operation === 'html') return { message_id: sent.id, format: 'html', entities: (sent.entities ?? []).map(e => e.className) };
if (operation === 'schedule') return { id: sent.id, scheduled_for: schedule!.toISOString(), chat, account, preview: message.length > 80 ? message.slice(0, 80) + '…' : message };
return { sent_to: String(entity.id), title: entity.title || entity.username, message_id: sent.id };
}
if (operation === 'delete') return { chat, ids, account, result: String(await client.deleteMessages(entity, ids, { revoke: p.revoke })) };
if (operation === 'contact-photo') {
const bytes = await readFile(input!);
const uploaded = await client.uploadFile({ file: new CustomFile(basename(input!), bytes.length, input!, bytes), workers: 1 });
const result = await client.invoke(new Api.photos.UploadContactProfilePhoto({ userId: entity, file: uploaded, suggest: false, save: true }));
return { user: chat, entity_id: String(entity.id), photo_id: String(result.photo.id), bytes: bytes.length, account };
}
let bytes: string | Buffer | undefined, count: number | undefined;
if (operation === 'download-media') {
const messages = await client.getMessages(entity, { ids: [messageId!] });
if (!messages[0]?.media) invalid('Message has no media');
bytes = await client.downloadMedia(messages[0], {});
} else if (operation === 'download-photo') bytes = await client.downloadProfilePhoto(entity, { isBig: true });
else if (operation === 'download-photo-at') {
const result = await client.invoke(new Api.photos.GetUserPhotos({ userId: entity, offset: 0, maxId: bigInt.zero, limit: 50 }));
count = result.photos.length;
const photo = result.photos[index!];
if (!(photo instanceof Api.Photo)) invalid('Photo index unavailable');
bytes = await client.downloadFile(new Api.InputPhotoFileLocation({ id: photo.id, accessHash: photo.accessHash, fileReference: photo.fileReference, thumbSize: 'x' }), { dcId: photo.dcId });
}
if (!Buffer.isBuffer(bytes) || !bytes.length) invalid('Empty media');
await writeFile(output!, bytes, { mode: 0o600 });
if (operation === 'download-photo') return { user: chat, entity_id: String(entity.id), path: output, bytes: bytes.length, account };
if (operation === 'download-photo-at') return { count, used_index: index, size: bytes.length, path: output };
return { id: messageId, size: bytes.length, path: output };
}
export function createBridgeCommand(): Command {
const group = new Command('bridge').description('Compatibility operations for local Telegram wrappers');
group.command('call <operation> <payload>').description('Run a named wrapper operation with JSON payload').action(async function (this: Command, operation: string, payload: string) {
let parsed: unknown;
try { parsed = JSON.parse(payload); } catch { invalid('Invalid JSON payload'); }
await withAuth(this.optsWithGlobals() as GlobalOptions, async client => { outputSuccess(await runBridge(client, operation, parsed)); });
});
return group;
}

View file

@ -0,0 +1,186 @@
import { Api, type TelegramClient } from 'teleproto';
import { z } from 'zod';
import { createHash } from 'node:crypto';
import bigInt from 'big-integer';
import { scanDialogs, recordReadFlood } from './dialog-scan.js';
import { TgError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { serializeMessage } from '../../lib/serialize.js';
const peer = z.string().min(1).max(256).refine(s => !s.includes('\0') && !s.startsWith('--'));
const ids = z.array(z.number().int().positive()).min(1).max(100);
const peers = z.array(peer).max(200);
const rules = z.object({ contacts: z.boolean().optional(), nonContacts: z.boolean().optional(),
groups: z.boolean().optional(), broadcasts: z.boolean().optional(), bots: z.boolean().optional(),
excludeMuted: z.boolean().optional(), excludeRead: z.boolean().optional(), excludeArchived: z.boolean().optional() }).strict();
const patchSchema = z.object({ title: z.string().min(1).max(12).optional(), emoticon: z.string().max(32).optional(),
color: z.number().int().min(0).max(6).optional(), include: peers.optional(), exclude: peers.optional(),
pinned: peers.optional(), rules: rules.optional() }).strict();
const common = { account: z.enum(['main', 'reserve']) };
const mutation = { dry_run: z.boolean().default(true) };
const folderId = z.number().int().min(2).max(255);
const revision = z.string().regex(/^[a-f0-9]{64}$/).optional();
const schema = z.discriminatedUnion('action', [
z.object({ ...common, action: z.literal('folders') }).strict(),
z.object({ ...common, action: z.literal('audit'), scan_limit: z.number().int().min(1).max(50000).default(1000), folder_id: folderId.optional(), cursor: z.string().uuid().optional(), refresh: z.boolean().default(false) }).strict(),
z.object({ ...common, action: z.literal('dialogs'), limit: z.number().int().min(1).max(500).default(100), offset: z.number().int().min(0).max(50000).default(0), cursor: z.string().uuid().optional(), refresh: z.boolean().default(false) }).strict(),
z.object({ ...common, action: z.literal('folder-put'), id: folderId, create: z.boolean().default(false), patch: patchSchema, revision, ...mutation }).strict(),
z.object({ ...common, action: z.literal('folder-delete'), id: folderId, revision, ...mutation }).strict(),
z.object({ ...common, action: z.literal('folder-order'), order: z.array(z.number().int().min(0).max(255)).min(1).max(30), revision, ...mutation }).strict(),
z.object({ ...common, action: z.literal('archive'), chat: peer, archived: z.boolean(), ...mutation }).strict(),
z.object({ ...common, action: z.literal('dialog-pin'), chat: peer, pinned: z.boolean(), ...mutation }).strict(),
z.object({ ...common, action: z.literal('unread'), chat: peer, unread: z.boolean(), ...mutation }).strict(),
z.object({ ...common, action: z.literal('read'), chat: peer, max_id: z.number().int().positive(), ...mutation }).strict(),
z.object({ ...common, action: z.literal('notify-get'), chat: peer }).strict(),
z.object({ ...common, action: z.literal('notify-set'), chat: peer, mute_until: z.number().int().min(0).max(2147483647), ...mutation }).strict(),
z.object({ ...common, action: z.literal('scheduled-list'), chat: peer }).strict(),
z.object({ ...common, action: z.enum(['scheduled-delete', 'scheduled-send']), chat: peer, ids, ...mutation }).strict(),
z.object({ ...common, action: z.literal('draft-save'), chat: peer, text: z.string().max(4096), ...mutation }).strict(),
]);
function fail(message: string): never { throw new TgError(message, ErrorCode.INVALID_OPTIONS); }
function inputPeer(client: TelegramClient, value: string) {
// Numeric strings can otherwise enter username/phone resolution in the SDK.
return client.getInputEntity(/^-?\d+$/.test(value) ? bigInt(value) : value);
}
/** Stable marked peer IDs only: never expose access hashes or file references. */
export function peerId(p: any): string {
if (p.userId != null) return String(p.userId);
if (p.channelId != null) return `-100${p.channelId}`;
if (p.chatId != null) return `-${p.chatId}`;
if (p instanceof Api.InputPeerSelf) return 'me';
return fail('Unsupported folder peer');
}
export function folderDto(f: any) {
if (f instanceof Api.DialogFilterDefault) return { id: 0, kind: 'default' };
return { id: f.id, kind: f.className, title: f.title?.text ?? '', emoticon: f.emoticon ?? null,
color: f.color ?? null, title_noanimate: !!f.titleNoanimate,
include: (f.includePeers ?? []).map(peerId), exclude: (f.excludePeers ?? []).map(peerId),
pinned: (f.pinnedPeers ?? []).map(peerId),
rules: Object.fromEntries(Object.keys(rules.shape).map(k => [k, !!f[k]])) };
}
async function folders(client: TelegramClient) {
const raw = await client.getDialogFilters();
const dto = { tags_enabled: !!raw.tagsEnabled, folders: raw.filters.map(folderDto) };
return { raw, dto: { ...dto, revision: createHash('sha256').update(JSON.stringify(dto)).digest('hex') } };
}
/** Named account-management operations, with previews and optimistic folder revisions. */
export async function runOrganize(client: TelegramClient, payload: unknown): Promise<unknown> {
const parsed = schema.safeParse(payload);
if (!parsed.success) fail(parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; '));
const p = parsed.data;
if (p.action === 'folders') return (await folders(client)).dto;
if (p.action === 'audit') {
const scan = await scanDialogs(client, p.account, p.scan_limit + 1, p.cursor, p.refresh);
const { rows: all, ...progress } = scan;
if (scan.retry_after_seconds) return { ...progress, complete: false, audit_pending: true, chats: [], note: 'Wait until retry_at, then resume with cursor; collected metadata retained in daemon.' };
let state: Awaited<ReturnType<typeof folders>>;
const defaults: Record<string, number> = {};
try {
state = await folders(client);
for (const [key, scope] of [['user', new Api.InputNotifyUsers()], ['group', new Api.InputNotifyChats()], ['channel', new Api.InputNotifyBroadcasts()]] as const)
defaults[key] = (await client.getNotifySettings(scope)).muteUntil ?? 0;
} catch (error) {
return { ...progress, ...recordReadFlood(client, p.account, error), complete: false, audit_pending: true, chats: [],
note: 'Audit settings rate limited; resume with cursor after retry_at. Dialog metadata retained.' };
}
const ordinary = state.dto.folders.filter(f => f.kind !== 'default');
if (p.folder_id !== undefined && !ordinary.some(f => f.id === p.folder_id)) fail('Folder not found');
const complete = scan.complete && all.length <= p.scan_limit;
const rows = all.slice(0, p.scan_limit);
const chats = rows.map(d => {
const id = d.id;
const category = d.type === 'bot' ? 'user' : d.type;
const muted = (d.mute_until ?? defaults[category]) > Date.now() / 1000;
const unread = d.unread_count > 0 || d.unread_mark || d.unread_mentions > 0;
const memberships = ordinary.filter((f: any) => {
const match = (items: string[]) => items.includes(id) || (d.self && items.includes('me'));
if (match(f.exclude)) return false;
if (match(f.include) || match(f.pinned)) return true;
const r = f.rules;
if (r.excludeArchived && d.archived || r.excludeRead && !unread || r.excludeMuted && muted && d.unread_mentions === 0) return false;
return d.type === 'bot' ? r.bots : d.type === 'user' ? d.contact ? r.contacts : r.nonContacts : category === 'channel' ? r.broadcasts : r.groups;
}).map(f => f.id);
return { ...d, muted, folders: memberships };
});
return { ...state.dto, ...progress, complete, scanned: rows.length, scan_limit: p.scan_limit, notification_defaults: defaults,
folders_summary: ordinary.map((f: any) => ({ id: f.id, title: f.title,
matched_in_scan: chats.filter(c => c.folders.includes(f.id)).length })),
outside_folders: chats.filter(c => c.folders.length === 0).map(c => c.id),
overlaps: chats.filter(c => c.folders.length > 1).map(c => ({ id: c.id, folders: c.folders })),
chats: p.folder_id === undefined ? chats : chats.filter(c => c.folders.includes(p.folder_id!)),
note: 'Computed membership from a bounded snapshot, not atomic. Counts are lower bounds when complete=false. Muted mentions may render differently across Telegram clients. Overlap is informational, not an error.' };
}
if (p.action === 'dialogs') {
const scan = await scanDialogs(client, p.account, p.offset + p.limit + 1, p.cursor, p.refresh);
if (p.offset > scan.rows.length) throw new TgError('Offset not yet collected; resume sequentially with the returned cursor', 'OFFSET_NOT_READY');
const rows = scan.rows.slice(p.offset, p.offset + p.limit);
const { rows: _all, ...progress } = scan;
const more = !scan.exhausted || scan.rows.length > p.offset + rows.length;
return { ...progress, chats: rows, next_offset: more ? p.offset + rows.length : null, has_more: more,
note: 'Daemon snapshot; resume with cursor and next_offset. Wait retry_after_seconds before resuming. No message bodies/read receipts. Not atomic; muted=null inherits defaults.' };
}
if (p.action === 'folder-put' || p.action === 'folder-delete' || p.action === 'folder-order') {
const state = await folders(client);
if (p.revision && p.revision !== state.dto.revision) fail('FOLDER_CONFLICT: read current folders and preview again');
if (!p.dry_run && !p.revision) fail('Applying folder changes requires the revision returned by a fresh preview');
if (p.action === 'folder-order') {
const current = state.raw.filters.map(f => f instanceof Api.DialogFilterDefault ? 0 : f.id);
if (new Set(p.order).size !== p.order.length || [...current].sort().join() !== [...p.order].sort().join()) fail('Order must contain every current folder exactly once');
if (p.dry_run) return { dry_run: true, revision: state.dto.revision, before: current, after: p.order };
const accepted = await client.updateDialogFiltersOrder(p.order);
return { accepted, state: (await folders(client)).dto };
}
const old = state.raw.filters.find(f => !(f instanceof Api.DialogFilterDefault) && f.id === p.id);
if (p.action === 'folder-delete') {
if (!(old instanceof Api.DialogFilter)) fail('Only existing ordinary folders can be deleted; shared folders require a separate workflow');
if (p.dry_run) return { dry_run: true, revision: state.dto.revision, before: folderDto(old), after: null };
const accepted = await client.updateDialogFilter(p.id);
return { accepted, state: (await folders(client)).dto };
}
if (p.create ? !!old : !old) fail(p.create ? 'Folder ID already exists' : 'Folder not found');
if (old && !(old instanceof Api.DialogFilter)) fail('Shared folder editing is not supported');
if (p.create && !p.patch.title) fail('New folder requires title');
const original = old as Api.DialogFilter | undefined;
const args: any = original ? { ...original } : { id: p.id, title: new Api.TextWithEntities({ text: p.patch.title!, entities: [] }), includePeers: [], excludePeers: [], pinnedPeers: [] };
if (p.patch.title !== undefined) args.title = new Api.TextWithEntities({ text: p.patch.title, entities: [] });
if (p.patch.emoticon !== undefined) args.emoticon = p.patch.emoticon || undefined;
if (p.patch.color !== undefined) args.color = p.patch.color;
Object.assign(args, p.patch.rules ?? {});
for (const [key, field] of [['include', 'includePeers'], ['exclude', 'excludePeers'], ['pinned', 'pinnedPeers']] as const) {
if (p.patch[key] !== undefined) {
args[field] = [];
for (const name of p.patch[key]!) args[field].push(await inputPeer(client, name));
if (new Set(args[field].map(peerId)).size !== args[field].length) fail(`Duplicate ${key} peers`);
}
}
const included = new Set([...args.includePeers, ...args.pinnedPeers].map(peerId));
if (args.excludePeers.some((e: any) => included.has(peerId(e)))) fail('Peer cannot be both included/pinned and excluded');
const next = new Api.DialogFilter(args);
if (p.dry_run) return { dry_run: true, revision: state.dto.revision, before: old ? folderDto(old) : null, after: folderDto(next) };
const accepted = await client.updateDialogFilter(p.id, next);
return { accepted, state: (await folders(client)).dto };
}
const entity = await inputPeer(client, p.chat);
if (p.action === 'notify-get') {
const n = await client.getNotifySettings(entity);
return { mute_until: n.muteUntil ?? null, silent: n.silent ?? null, show_previews: n.showPreviews ?? null,
inherited: n.muteUntil == null };
}
if (p.action === 'scheduled-list') return { messages: (await client.getScheduledMessages(entity)).map(m => serializeMessage(m)) };
if (p.dry_run) return { dry_run: true, operation: p.action, target: p.chat, parameters: p };
if (p.action === 'archive') await client.editPeerFolders(entity, p.archived ? 1 : 0);
else if (p.action === 'dialog-pin') await client.invoke(new Api.messages.ToggleDialogPin({ peer: entity, pinned: p.pinned }));
else if (p.action === 'unread') await client.invoke(new Api.messages.MarkDialogUnread({ peer: entity, unread: p.unread }));
else if (p.action === 'read') await client.markAsRead(entity, p.max_id);
else if (p.action === 'notify-set') {
const accepted = await client.updateNotifySettings(entity, { muteUntil: p.mute_until });
const n = await client.getNotifySettings(entity);
return { accepted, mute_until: n.muteUntil ?? null };
} else if (p.action === 'scheduled-delete') await client.deleteScheduledMessages(entity, p.ids);
else if (p.action === 'scheduled-send') return { messages: (await client.sendScheduledMessages(entity, p.ids)).map(m => serializeMessage(m)) };
else if (p.action === 'draft-save') return { accepted: await client.saveDraft(entity, { message: p.text, formattingEntities: [] }) };
return { submitted: true, operation: p.action, chat: p.chat };
}

View file

@ -0,0 +1,93 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { markedPeerId } from '../../lib/serialize.js';
import { resolveEntity } from '../../lib/peer.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
const CHAT_TYPES = new Set(['group', 'supergroup', 'channel']);
/**
* Action handler for `tg chat create <title>`.
*
* Creates a new group, supergroup, or channel.
* Options: --type (group|supergroup|channel, default supergroup), --description, --members
*/
export async function chatCreateAction(this: Command, title: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & {
type?: string;
description?: string;
members?: string;
};
if (!title) {
outputError('Chat title is required', ErrorCode.INVALID_INPUT);
return;
}
const chatType = opts.type ?? 'supergroup';
if (!CHAT_TYPES.has(chatType)) {
outputError(
`Invalid chat type '${chatType}'. Use: group, supergroup, channel`,
ErrorCode.INVALID_CHAT_TYPE,
);
return;
}
const members = (opts.members ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (chatType === 'group' && members.length === 0) {
outputError(
'Basic groups require at least one other member. Pass --members or use --type supergroup.',
ErrorCode.INVALID_OPTIONS,
);
return;
}
await withAuth(opts, async (client) => {
let result: any;
if (chatType === 'channel' || chatType === 'supergroup') {
result = await client.invoke(
new Api.channels.CreateChannel({
title,
about: opts.description ?? '',
broadcast: chatType === 'channel',
megagroup: chatType === 'supergroup',
}),
);
} else {
const users = [];
for (const member of members) {
users.push(await resolveEntity(client, member));
}
result = await client.invoke(
new Api.messages.CreateChat({
title,
users,
}),
);
}
// messages.CreateChat returns messages.InvitedUsers; channels.CreateChannel
// returns Updates directly.
const updates = chatType === 'group' ? (result.updates ?? result) : result;
const chat = updates.chats?.[0];
outputSuccess({
id: chat
? markedPeerId({
...chat,
className: chat.className ?? (chatType === 'group' ? 'Chat' : 'Channel'),
megagroup: chat.megagroup ?? chatType === 'supergroup',
})
: null,
title,
type: chatType,
});
});
}

View file

@ -0,0 +1,53 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Action handler for `tg chat edit <chat>`.
*
* Edits a chat's title and/or description.
* At least one of --title or --description is required.
*/
export async function chatEditAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { title?: string; description?: string };
if (!opts.title && !opts.description) {
outputError('At least one of --title or --description is required', ErrorCode.INVALID_INPUT);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
if (entity instanceof Api.Channel) {
if (opts.title) {
await client.invoke(new Api.channels.EditTitle({ channel: entity, title: opts.title }));
}
if (opts.description) {
await client.invoke(new Api.messages.EditChatAbout({ peer: entity, about: opts.description }));
}
} else if (entity instanceof Api.Chat) {
if (opts.title) {
await client.invoke(new Api.messages.EditChatTitle({ chatId: entity.id, title: opts.title }));
}
if (opts.description) {
await client.invoke(new Api.messages.EditChatAbout({ peer: entity, about: opts.description }));
}
} else {
outputError('Cannot edit a user chat', ErrorCode.INVALID_CHAT_TYPE);
return;
}
outputSuccess({
chatId: markedPeerId(entity),
updated: true,
title: opts.title ?? null,
description: opts.description ?? null,
});
});
}

View file

@ -0,0 +1,123 @@
import { Command } from 'commander';
import { chatListAction } from './list.js';
import { chatInfoAction } from './info.js';
import { chatJoinAction } from './join.js';
import { chatLeaveAction } from './leave.js';
import { chatResolveAction } from './resolve.js';
import { chatInviteInfoAction } from './invite-info.js';
import { chatMembersAction } from './members.js';
import { chatTopicsAction } from './topics.js';
import { chatSearchAction } from './search.js';
import { chatCreateAction } from './create.js';
import { chatEditAction } from './edit.js';
import { chatKickAction } from './kick.js';
/**
* Create the `chat` command group (12 subcommands).
*
* Usage:
* tg chat list - List all chats/dialogs
* tg chat info <chat> - Get detailed chat info
* tg chat join <target> - Join a group or channel
* tg chat leave <chat> - Leave a group or channel
* tg chat resolve <input> - Resolve a peer to entity info
* tg chat invite-info <link> - Check invite link info without joining
* tg chat members <chat> - List members of a group/channel
* tg chat topics <chat> - List forum topics in a supergroup
* tg chat search <query> - Search public channels and groups
* tg chat create <title> - Create a group, supergroup, or channel
* tg chat edit <chat> - Edit chat title or description
* tg chat kick <chat> <user> - Kick a user from a group or channel
*/
export function createChatCommand(): Command {
const chat = new Command('chat')
.description('Chat discovery and management');
chat
.command('list')
.description('List all chats/dialogs')
.option('--type <type>', 'Filter by type: user, group, channel, supergroup')
.option('--limit <n>', 'Max results', '50')
.option('--offset <n>', 'Skip results', '0')
.action(chatListAction);
chat
.command('info')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Get detailed chat info')
.action(chatInfoAction);
chat
.command('join')
.argument('<target>', 'Username, @username, or invite link')
.description('Join a group or channel')
.action(chatJoinAction);
chat
.command('leave')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Leave a group or channel')
.action(chatLeaveAction);
chat
.command('resolve')
.argument('<input>', 'Username, ID, or phone number')
.description('Resolve a peer to entity info')
.action(chatResolveAction);
chat
.command('invite-info')
.argument('<link>', 'Invite link (t.me/+HASH)')
.description('Check invite link info without joining')
.action(chatInviteInfoAction);
chat
.command('members')
.argument('<chat>', 'Chat ID, username, or @username')
.description('List members of a group/channel')
.option('--limit <n>', 'Max results', '50')
.option('--offset <n>', 'Skip results', '0')
.option('--search <query>', 'Filter members by name')
.action(chatMembersAction);
chat
.command('topics')
.argument('<chat>', 'Chat ID, username, or @username')
.description('List forum topics in a supergroup')
.option('--limit <n>', 'Max topics', '50')
.option('--offset <n>', 'Skip topics', '0')
.action(chatTopicsAction);
chat
.command('search')
.argument('<query>', 'Search query')
.description('Search for public channels and groups globally')
.option('--limit <n>', 'Max results', '20')
.action(chatSearchAction);
chat
.command('create')
.argument('<title>', 'Chat title')
.description('Create a new group, supergroup, or channel')
.option('--type <type>', 'Chat type: group, supergroup, channel', 'supergroup')
.option('--description <text>', 'Chat description')
.option('--members <users>', 'Comma-separated users (required for --type group)')
.action(chatCreateAction);
chat
.command('edit')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Edit chat title or description')
.option('--title <text>', 'New title')
.option('--description <text>', 'New description')
.action(chatEditAction);
chat
.command('kick')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<user>', 'User ID, username, or @username')
.description('Kick a user from a group or channel')
.action(chatKickAction);
return chat;
}

View file

@ -0,0 +1,98 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId, serializeChatPhoto, serializeBannedRights } from '../../lib/serialize.js';
import type { GlobalOptions, ChatInfo } from '../../lib/types.js';
/**
* Action handler for `tg chat info <chat>`.
*
* Gets detailed information for a chat by username, ID, or @username.
* Returns kitchen-sink fields: description, member count, permissions, etc.
*/
export async function chatInfoAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
let chatInfo: ChatInfo;
if (entity instanceof Api.Channel) {
// Channel or Supergroup
const full = await client.invoke(
new Api.channels.GetFullChannel({ channel: entity }),
);
const fc = full.fullChat as any;
const type = entity.megagroup ? 'supergroup' : 'channel';
chatInfo = {
id: markedPeerId(entity),
title: entity.title ?? '',
type,
username: (entity as any).username ?? null,
description: fc.about ?? null,
memberCount: fc.participantsCount ?? null,
creationDate: entity.date ? new Date(entity.date * 1000).toISOString() : null,
photo: serializeChatPhoto((entity as any).photo),
linkedChatId: fc.linkedChatId
? markedPeerId({ id: fc.linkedChatId, className: 'Channel' })
: null,
slowmodeSeconds: fc.slowmodeSeconds ?? null,
permissions: serializeBannedRights((entity as any).defaultBannedRights),
inviteLink: fc.exportedInvite?.link ?? null,
migratedFrom: fc.migratedFromChatId
? markedPeerId({ id: fc.migratedFromChatId, className: 'Chat' })
: null,
};
} else if (entity instanceof Api.Chat) {
// Basic group
const full = await client.invoke(
new Api.messages.GetFullChat({ chatId: entity.id }),
);
const fc = full.fullChat as any;
chatInfo = {
id: markedPeerId(entity),
title: entity.title ?? '',
type: 'group',
username: null,
description: fc.about ?? null,
memberCount: fc.participants?.participants?.length ?? null,
creationDate: entity.date ? new Date(entity.date * 1000).toISOString() : null,
photo: serializeChatPhoto((entity as any).photo),
linkedChatId: null,
slowmodeSeconds: null,
permissions: serializeBannedRights((entity as any).defaultBannedRights),
inviteLink: fc.exportedInvite?.link ?? null,
migratedFrom: null,
};
} else {
// User - basic info only
const user = entity as Api.User;
const firstName = (user as any).firstName ?? '';
const lastName = (user as any).lastName ?? '';
const title = lastName ? `${firstName} ${lastName}` : firstName;
chatInfo = {
id: markedPeerId(user),
title,
type: 'user',
username: (user as any).username ?? null,
description: null,
memberCount: null,
creationDate: null,
photo: serializeChatPhoto((user as any).photo),
linkedChatId: null,
slowmodeSeconds: null,
permissions: null,
inviteLink: null,
migratedFrom: null,
};
}
outputSuccess(chatInfo);
});
}

View file

@ -0,0 +1,61 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { extractInviteHash } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import type { GlobalOptions } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg chat invite-info <link>`.
*
* Checks invite link info without joining.
* Handles three result types:
* - ChatInviteAlready: already a member
* - ChatInvite: preview info (title, about, member count)
* - ChatInvitePeek: temporary peek with expiry
*/
export async function chatInviteInfoAction(this: Command, link: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const hash = extractInviteHash(link);
const result = await client.invoke(
new Api.messages.CheckChatInvite({ hash }),
);
if (result instanceof Api.ChatInviteAlready) {
const chat = (result as any).chat;
outputSuccess({
alreadyMember: true,
chat: {
id: markedPeerId(chat),
title: chat?.title ?? '',
},
});
} else if (result instanceof Api.ChatInvitePeek) {
const chat = (result as any).chat;
outputSuccess({
alreadyMember: false,
chat: {
id: markedPeerId(chat),
title: chat?.title ?? '',
},
expires: new Date((result as any).expires * 1000).toISOString(),
});
} else if (result instanceof Api.ChatInvite) {
outputSuccess({
alreadyMember: false,
title: (result as any).title,
about: (result as any).about ?? null,
participantsCount: (result as any).participantsCount ?? 0,
channel: !!(result as any).channel,
broadcast: !!(result as any).broadcast,
});
} else {
outputError('Unknown invite result type', ErrorCode.UNKNOWN_INVITE_TYPE);
return;
}
});
}

View file

@ -0,0 +1,80 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity, extractInviteHash } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import type { GlobalOptions } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Detect if a target string looks like an invite link (contains /+ or /joinchat/).
*/
function isInviteLink(target: string): boolean {
return /(?:t\.me|telegram\.me)\/(?:joinchat\/|\+)/.test(target);
}
/**
* Action handler for `tg chat join <target>`.
*
* Joins a group or channel by username or invite link.
* - Username/ID: resolves entity, calls JoinChannel
* - Invite link: extracts hash, calls ImportChatInvite
*/
export async function chatJoinAction(this: Command, target: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
if (isInviteLink(target)) {
// Join via invite link
const hash = extractInviteHash(target);
try {
const result = await client.invoke(
new Api.messages.ImportChatInvite({ hash }),
);
const chat = (result as any)?.chats?.[0];
outputSuccess({
joined: true,
chat: chat ? {
id: markedPeerId(chat),
title: chat.title ?? '',
} : { id: '', title: '' },
});
} catch (err: unknown) {
const errMsg = err instanceof Error ? err.message : String(err);
if (errMsg.includes('USER_ALREADY_PARTICIPANT')) {
outputError('You are already a member of this chat', ErrorCode.USER_ALREADY_PARTICIPANT);
return;
}
throw err;
}
} else {
// Join by username/ID
const entity = await resolveEntity(client, target);
try {
const inputEntity = await client.getInputEntity(entity);
await client.invoke(
new Api.channels.JoinChannel({ channel: inputEntity as any }),
);
outputSuccess({
joined: true,
chat: {
id: markedPeerId(entity),
title: (entity as any).title ?? '',
},
});
} catch (err: unknown) {
const errMsg = err instanceof Error ? err.message : String(err);
if (errMsg.includes('USER_ALREADY_PARTICIPANT')) {
outputError('You are already a member of this chat', ErrorCode.USER_ALREADY_PARTICIPANT);
return;
}
if (errMsg.includes('CHANNELS_TOO_MUCH')) {
outputError('Cannot join: you have reached the channel/supergroup limit', ErrorCode.CHANNELS_TOO_MUCH);
return;
}
throw err;
}
}
});
}

View file

@ -0,0 +1,56 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { bigIntToString, markedPeerId } from '../../lib/serialize.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Action handler for `tg chat kick <chat> <user>`.
*
* Kicks a user from a group or supergroup.
*/
export async function chatKickAction(this: Command, chatInput: string, userInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const chatEntity = await resolveEntity(client, chatInput);
const userEntity = await resolveEntity(client, userInput);
if (!(userEntity instanceof Api.User)) {
outputError('Target must be a user', ErrorCode.NOT_A_USER);
return;
}
if (chatEntity instanceof Api.Channel) {
await client.invoke(
new Api.channels.EditBanned({
channel: chatEntity,
participant: userEntity,
bannedRights: new Api.ChatBannedRights({
untilDate: 0,
viewMessages: true,
}),
}),
);
} else if (chatEntity instanceof Api.Chat) {
await client.invoke(
new Api.messages.DeleteChatUser({
chatId: chatEntity.id,
userId: userEntity,
}),
);
} else {
outputError('Cannot kick from a user chat', ErrorCode.INVALID_CHAT_TYPE);
return;
}
outputSuccess({
chatId: markedPeerId(chatEntity),
userId: bigIntToString(userEntity.id),
kicked: true,
});
});
}

View file

@ -0,0 +1,50 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import type { GlobalOptions } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg chat leave <chat>`.
*
* Leaves a group or channel.
* - Channel/Supergroup: uses LeaveChannel
* - Basic group: uses DeleteChatUser with self as user
*/
export async function chatLeaveAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
if (entity instanceof Api.Channel) {
// Channel or supergroup
await client.invoke(
new Api.channels.LeaveChannel({ channel: entity }),
);
} else if (entity instanceof Api.Chat) {
// Basic group: remove self
const me = await client.getMe();
await client.invoke(
new Api.messages.DeleteChatUser({
chatId: entity.id,
userId: (me as any).id,
}),
);
} else {
outputError('Cannot leave a user chat', ErrorCode.INVALID_CHAT_TYPE);
return;
}
outputSuccess({
left: true,
chat: {
id: markedPeerId(entity),
title: (entity as any).title ?? '',
},
});
});
}

View file

@ -0,0 +1,103 @@
import type { Command } from 'commander';
import type { TelegramClient } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { bigIntToString, serializeDialog } from '../../lib/serialize.js';
import { validatePagination } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { ChatListItem, GlobalOptions } from '../../lib/types.js';
const DIALOG_BATCH = 100;
const MAX_DIALOGS = 5000;
/**
* Keep fetching dialogs until we have `offset + limit` matches of `type`,
* or the dialog list is exhausted.
*/
async function fetchTypedPage(
client: TelegramClient,
type: string,
offset: number,
limit: number,
): Promise<{ chats: ChatListItem[]; total: number; hasMore: boolean }> {
const needed = offset + limit;
const matching: ChatListItem[] = [];
const seen = new Set<string>();
let last: any;
let fetched = 0;
let exhausted = false;
while (matching.length < needed && fetched < MAX_DIALOGS) {
const params: Record<string, unknown> = { limit: DIALOG_BATCH };
if (last) {
params.offsetDate = last.date ?? last.message?.date;
params.offsetId = last.message?.id ?? last.topMessage ?? 0;
params.offsetPeer = last.inputEntity ?? last.entity;
}
const batch = await client.getDialogs(params as any);
if (!batch.length) {
exhausted = true;
break;
}
fetched += batch.length;
for (const dialog of batch) {
const key = bigIntToString((dialog as any).id) || String((dialog as any).id);
if (seen.has(key)) continue;
seen.add(key);
last = dialog;
const chat = serializeDialog(dialog);
if (chat.type === type) matching.push(chat);
}
if (batch.length < DIALOG_BATCH) {
exhausted = true;
break;
}
}
return {
chats: matching.slice(offset, offset + limit),
total: matching.length,
hasMore:
matching.length > offset + limit
|| (matching.length >= needed && !exhausted && fetched < MAX_DIALOGS),
};
}
/**
* Action handler for `tg chat list`.
*
* Lists all chats/dialogs with optional type filtering and pagination.
* Options: --type (user|group|channel|supergroup), --limit (default 50), --offset (default 0)
*/
export async function chatListAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { type?: string; limit: string; offset: string };
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
if (opts.type) {
const { chats, total, hasMore } = await fetchTypedPage(client, opts.type, offset, limit);
outputSuccess({ chats, total, hasMore });
return;
}
const dialogs = await client.getDialogs({
limit: offset + limit,
});
const chats = dialogs.map(serializeDialog).slice(offset, offset + limit);
outputSuccess({
chats,
total: (dialogs as any).total ?? 0,
});
});
}

View file

@ -0,0 +1,46 @@
import type { Command } from 'commander';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeMember } from '../../lib/serialize.js';
import { validatePagination } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions } from '../../lib/types.js';
import type { Api } from 'teleproto';
/**
* Action handler for `tg chat members <chat>`.
*
* Lists members of a group or channel with pagination and search.
* Options: --limit (default 50), --offset (default 0), --search <query>
*/
export async function chatMembersAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { limit: string; offset: string; search?: string };
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
const participants = await client.getParticipants(entity, {
limit,
offset,
search: opts.search,
});
const members = participants.map((p: any) => serializeMember(p as Api.User));
outputSuccess({
members,
total: (participants as any).total ?? 0,
});
});
}

View file

@ -0,0 +1,51 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Determine the entity type string from a resolved entity.
*/
function entityType(entity: Api.User | Api.Chat | Api.Channel): string {
if (entity instanceof Api.Channel) {
return (entity as any).megagroup ? 'supergroup' : 'channel';
}
if (entity instanceof Api.Chat) return 'group';
return 'user';
}
/**
* Get a display title from a resolved entity.
*/
function entityTitle(entity: Api.User | Api.Chat | Api.Channel): string {
if (entity instanceof Api.User) {
const first = (entity as any).firstName ?? '';
const last = (entity as any).lastName ?? '';
return last ? `${first} ${last}` : first;
}
return (entity as any).title ?? '';
}
/**
* Action handler for `tg chat resolve <input>`.
*
* Resolves a peer by username, numeric ID, or phone number.
* Outputs the entity's id, type, title, and username.
*/
export async function chatResolveAction(this: Command, input: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, input);
outputSuccess({
id: markedPeerId(entity),
type: entityType(entity),
title: entityTitle(entity),
username: (entity as any).username ?? null,
});
});
}

View file

@ -0,0 +1,57 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { markedPeerId } from '../../lib/serialize.js';
import { validatePagination } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Determine chat type from a gramjs Chat or Channel entity.
*/
function chatType(entity: any): string {
if (entity.className === 'Channel') {
return entity.megagroup ? 'supergroup' : 'channel';
}
if (entity.className === 'Chat') return 'group';
return 'unknown';
}
/**
* Action handler for `tg chat search <query>`.
*
* Searches for public channels and groups globally via contacts.Search.
* Returns the chats array from the API response (channels, supergroups, groups).
* Options: --limit (default 20)
*/
export async function chatSearchAction(this: Command, query: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { limit?: string };
let limit: number;
try {
({ limit } = validatePagination({ limit: opts.limit }, 20));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const found = await client.invoke(
new Api.contacts.Search({ q: query, limit }),
);
const chats = ((found as any).chats ?? [])
.filter((c: any) => c.className === 'Channel' || c.className === 'Chat')
.map((c: any) => ({
id: markedPeerId(c),
title: c.title ?? '',
type: chatType(c),
username: c.username ?? null,
membersCount: c.participantsCount ?? null,
}));
outputSuccess({ chats, total: chats.length });
});
}

View file

@ -0,0 +1,87 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { withAuth } from '../../lib/with-auth.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { TgError, formatError } from '../../lib/errors.js';
import { validatePagination } from '../../lib/validate.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeTopic } from '../../lib/serialize.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Action handler for `tg chat topics <chat>`.
*
* Lists forum topics in a supergroup with pagination.
* Options: --limit (default 50), --offset (default 0)
*
* Forum guard: rejects non-forum chats with NOT_A_FORUM error code.
* Filters out ForumTopicDeleted items from API results.
* Applies client-side offset slicing for simple pagination.
*/
export async function chatTopicsAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { limit: string; offset: string };
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
// Forum guard: entity must be a Channel with forum enabled
if ((entity as any).className !== 'Channel') {
throw new TgError('Chat is not a forum-enabled supergroup', ErrorCode.NOT_A_FORUM);
}
if ((entity as any).forum !== true) {
throw new TgError('Chat is not a forum-enabled supergroup', ErrorCode.NOT_A_FORUM);
}
const TOPIC_BATCH = 100;
const needed = offset + limit;
const collected: any[] = [];
let offsetDate = 0;
let offsetId = 0;
let offsetTopic = 0;
let total = 0;
while (collected.length < needed) {
const result = await client.invoke(
new Api.messages.GetForumTopics({
peer: entity as Api.Channel,
offsetDate,
offsetId,
offsetTopic,
limit: TOPIC_BATCH,
}),
);
total = (result as any).count ?? total;
const raw = ((result as any).topics ?? []) as any[];
// ForumTopicDeleted items count toward the API limit and are the
// pagination placeholders. Filter them only from the user-facing list.
if (!raw.length) break;
for (const t of raw) {
if (t.className !== 'ForumTopicDeleted') collected.push(t);
}
const last = raw[raw.length - 1];
offsetTopic = last.id ?? offsetTopic;
offsetId = last.topMessage ?? 0;
offsetDate = last.date ?? 0;
if (raw.length < TOPIC_BATCH) break;
}
const serialized = collected.map(serializeTopic);
const sliced = serialized.slice(offset, offset + limit);
outputSuccess({
topics: sliced,
total,
});
});
}

View file

@ -0,0 +1,121 @@
import { Command } from 'commander';
import { outputError } from '../../lib/output.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Generate shell completion scripts for bash, zsh, or fish.
* Install via: eval "$(tg completion bash)"
*/
export function createCompletionCommand(): Command {
const completion = new Command('completion')
.argument('<shell>', 'Shell type: bash, zsh, or fish')
.description('Generate shell completion script')
.action((shell: string) => {
const scripts: Record<string, string> = {
bash: generateBashCompletion(),
zsh: generateZshCompletion(),
fish: generateFishCompletion(),
};
const script = scripts[shell];
if (!script) {
outputError(`Unknown shell: ${shell}. Use: bash, zsh, or fish`, ErrorCode.INVALID_INPUT);
return;
}
process.stdout.write(script);
});
return completion;
}
function generateBashCompletion(): string {
return `# tg bash completion
_tg_completions() {
local cur prev commands
cur="\${COMP_WORDS[COMP_CWORD]}"
prev="\${COMP_WORDS[COMP_CWORD-1]}"
commands="auth session chat message media user contact daemon completion"
case "\${COMP_WORDS[1]}" in
auth) COMPREPLY=( $(compgen -W "login status logout" -- "$cur") ) ;;
session) COMPREPLY=( $(compgen -W "export import" -- "$cur") ) ;;
chat) COMPREPLY=( $(compgen -W "list info join leave resolve invite-info members topics search create edit kick" -- "$cur") ) ;;
message) COMPREPLY=( $(compgen -W "history search get pinned send forward react replies edit delete pin unpin poll watch" -- "$cur") ) ;;
media) COMPREPLY=( $(compgen -W "download send" -- "$cur") ) ;;
user) COMPREPLY=( $(compgen -W "profile block unblock blocked" -- "$cur") ) ;;
contact) COMPREPLY=( $(compgen -W "list add delete search" -- "$cur") ) ;;
daemon) COMPREPLY=( $(compgen -W "start stop status" -- "$cur") ) ;;
*) COMPREPLY=( $(compgen -W "$commands" -- "$cur") ) ;;
esac
}
complete -F _tg_completions tg
`;
}
function generateZshCompletion(): string {
return `#compdef tg
_tg() {
local -a commands
local state
_arguments -C \\
'1: :->command' \\
'*:: :->args'
case $state in
command)
commands=(
'auth:Authentication management'
'session:Session import/export'
'chat:Chat discovery and management'
'message:Message reading and sending'
'media:Media upload/download'
'user:User profiles and blocking'
'contact:Contact management'
'daemon:Persistent connection daemon'
'completion:Generate shell completions'
)
_describe 'command' commands
;;
args)
case $words[1] in
auth) _describe 'subcommand' '(login:Log in status:Auth status logout:Log out)' ;;
session) _describe 'subcommand' '(export:Export session import:Import session)' ;;
chat) _describe 'subcommand' '(list:List chats info:Chat info join:Join leave:Leave resolve:Resolve invite-info:Invite info members:Members topics:Topics search:Search create:Create edit:Edit kick:Kick)' ;;
message) _describe 'subcommand' '(history:History search:Search get:Get pinned:Pinned send:Send forward:Forward react:React replies:Replies edit:Edit delete:Delete pin:Pin unpin:Unpin poll:Poll watch:Watch)' ;;
media) _describe 'subcommand' '(download:Download send:Send)' ;;
user) _describe 'subcommand' '(profile:Profile block:Block unblock:Unblock blocked:Blocked)' ;;
contact) _describe 'subcommand' '(list:List add:Add delete:Delete search:Search)' ;;
daemon) _describe 'subcommand' '(start:Start stop:Stop status:Status)' ;;
esac
;;
esac
}
_tg "$@"
`;
}
function generateFishCompletion(): string {
return `# tg fish completion
complete -c tg -n '__fish_use_subcommand' -a auth -d 'Authentication management'
complete -c tg -n '__fish_use_subcommand' -a session -d 'Session import/export'
complete -c tg -n '__fish_use_subcommand' -a chat -d 'Chat discovery and management'
complete -c tg -n '__fish_use_subcommand' -a message -d 'Message reading and sending'
complete -c tg -n '__fish_use_subcommand' -a media -d 'Media upload/download'
complete -c tg -n '__fish_use_subcommand' -a user -d 'User profiles and blocking'
complete -c tg -n '__fish_use_subcommand' -a contact -d 'Contact management'
complete -c tg -n '__fish_use_subcommand' -a daemon -d 'Persistent connection daemon'
complete -c tg -n '__fish_use_subcommand' -a completion -d 'Generate shell completions'
complete -c tg -n '__fish_seen_subcommand_from auth' -a 'login status logout'
complete -c tg -n '__fish_seen_subcommand_from session' -a 'export import'
complete -c tg -n '__fish_seen_subcommand_from chat' -a 'list info join leave resolve invite-info members topics search create edit kick'
complete -c tg -n '__fish_seen_subcommand_from message' -a 'history search get pinned send forward react replies edit delete pin unpin poll watch'
complete -c tg -n '__fish_seen_subcommand_from media' -a 'download send'
complete -c tg -n '__fish_seen_subcommand_from user' -a 'profile block unblock blocked'
complete -c tg -n '__fish_seen_subcommand_from contact' -a 'list add delete search'
complete -c tg -n '__fish_seen_subcommand_from daemon' -a 'start stop status'
complete -c tg -n '__fish_seen_subcommand_from completion' -a 'bash zsh fish'
`;
}

View file

@ -0,0 +1,120 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity, isPhoneNumber } from '../../lib/peer.js';
import { buildUserProfile } from '../../lib/user-profile.js';
import { withAuth } from '../../lib/with-auth.js';
import { batchError, outputBatchResult } from '../../lib/batch-results.js';
import { bigIntToString } from '../../lib/serialize.js';
import type { BatchItemError, GlobalOptions } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Detect whether input is a phone number.
* Phone numbers start with '+' or are all digits.
*/
function isPhoneInput(input: string): boolean {
return isPhoneNumber(input);
}
/**
* Action handler for `tg contact add <input>`.
*
* Adds a contact with dual routing:
* - Phone number (starts with '+' or all digits): uses ImportContacts API
* - Username/ID: uses resolveEntity + AddContact API
*
* Both routes fetch full profile via GetFullUser after adding.
* Returns UserProfile on success.
*
* Phone-based add requires --first-name flag.
* Idempotent: adding an existing contact returns success with profile.
*/
export async function contactAddAction(this: Command, input: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { firstName?: string; lastName?: string };
const { firstName, lastName } = opts;
await withAuth(opts, async (client) => {
let targetUser: Api.User;
try {
if (isPhoneInput(input)) {
// Phone route: ImportContacts
if (!firstName) {
outputError('--first-name is required when adding by phone number', ErrorCode.MISSING_FIRST_NAME);
return;
}
const phoneNumber = input.startsWith('+') ? input : `+${input}`;
const importResult = await client.invoke(
new Api.contacts.ImportContacts({
contacts: [
new Api.InputPhoneContact({
clientId: BigInt(Math.floor(Math.random() * 2 ** 32)) as any,
phone: phoneNumber,
firstName,
lastName: lastName ?? '',
}),
],
}),
);
if (importResult.users.length === 0) {
outputError('Phone number not found on Telegram', ErrorCode.PHONE_NOT_FOUND);
return;
}
targetUser = importResult.users[0] as Api.User;
} else {
// Username/ID route: resolveEntity + AddContact
const entity = await resolveEntity(client, input);
if (!(entity instanceof Api.User)) {
outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER);
return;
}
targetUser = entity;
await client.invoke(
new Api.contacts.AddContact({
id: entity,
firstName: entity.firstName ?? '',
lastName: entity.lastName ?? '',
phone: '',
}),
);
}
// The contact has already been added. Keep that fact in the response even
// when the subsequent read fails, so callers need not repeat the mutation.
let fullResult;
try {
fullResult = await client.invoke(new Api.users.GetFullUser({ id: targetUser }));
} catch (err: unknown) {
outputBatchResult({
added: true,
id: bigIntToString(targetUser.id),
firstName: targetUser.firstName ?? null,
lastName: targetUser.lastName ?? null,
username: targetUser.username ?? null,
}, [batchError(input, err, 'Could not fetch added contact profile')]);
return;
}
const fullUser = fullResult.fullUser;
const userFromResult = (fullResult.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(targetUser.id)) ?? targetUser) as Api.User;
const errors: BatchItemError[] = [];
const profileData = await buildUserProfile(client, targetUser, fullUser, userFromResult, err => {
errors.push(batchError(input, err, 'Could not fetch profile photos'));
});
outputBatchResult({ ...profileData, added: true }, errors);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}

View file

@ -0,0 +1,53 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { bigIntToString } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import type { GlobalOptions, ContactDeleteResult } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg contact delete <user>`.
*
* Deletes a single contact. Validates that the resolved entity is a User
* (not a Channel or Chat). Idempotent: deleting a non-contact returns
* success silently.
*
* Returns ContactDeleteResult with userId, username, firstName, action: 'deleted'.
*/
export async function contactDeleteAction(this: Command, userInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, userInput);
// Validate entity is a User (not Channel/Chat)
if (!(entity instanceof Api.User)) {
outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER);
return;
}
const user = entity;
try {
await client.invoke(
new Api.contacts.DeleteContacts({ id: [user] }),
);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
return;
}
const result: ContactDeleteResult = {
userId: bigIntToString(user.id),
username: user.username ?? null,
firstName: user.firstName ?? null,
action: 'deleted',
};
outputSuccess(result);
});
}

View file

@ -0,0 +1,53 @@
import { Command } from 'commander';
import { contactSetPhotoAction } from './set-photo.js';
import { contactListAction } from './list.js';
import { contactAddAction } from './add.js';
import { contactDeleteAction } from './delete.js';
import { contactSearchAction } from './search.js';
/**
* Create the `contact` command group with list, add, delete, search subcommands.
*
* Usage:
* tg contact list - List all contacts (--limit, --offset)
* tg contact add <input> - Add a contact by username/ID or phone (--first-name, --last-name)
* tg contact delete <user> - Delete a contact
* tg contact search <query> - Search contacts (--global, --limit)
*/
export function createContactCommand(): Command {
const contact = new Command('contact')
.description('Contact management: list, add, delete, search');
contact.command('list')
.description('List all contacts')
.option('--limit <n>', 'Max results', '50')
.option('--offset <n>', 'Skip results', '0')
.action(contactListAction);
contact.command('add')
.argument('<input>', 'Username, user ID, or phone number')
.description('Add a contact')
.option('--first-name <name>', 'First name (required for phone)')
.option('--last-name <name>', 'Last name')
.action(contactAddAction);
contact.command('delete')
.argument('<user>', 'Username or user ID')
.description('Delete a contact')
.action(contactDeleteAction);
contact.command('search')
.argument('<query>', 'Search query')
.description('Search contacts')
.option('--global', 'Include non-contact Telegram users')
.option('--limit <n>', 'Max results', '20')
.action(contactSearchAction);
contact.command('set-photo')
.argument('<user>', 'Contact username or user ID')
.argument('<file>', 'JPEG or PNG file')
.description('Set a personal contact photo visible only to you (no suggestion sent)')
.action(contactSetPhotoAction);
return contact;
}

View file

@ -0,0 +1,109 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputError } from '../../lib/output.js';
import { bigIntToString } from '../../lib/serialize.js';
import { buildUserProfile } from '../../lib/user-profile.js';
import { withAuth } from '../../lib/with-auth.js';
import { validatePagination } from '../../lib/validate.js';
import { formatError, TgError } from '../../lib/errors.js';
import { batchError, outputBatchResult } from '../../lib/batch-results.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { BatchItemError, GlobalOptions, UserProfile } from '../../lib/types.js';
/**
* Action handler for `tg contact list`.
*
* Lists all contacts with full UserProfile enrichment.
* Supports pagination via --limit (default 50) and --offset (default 0).
* Results are sorted alphabetically by firstName + lastName.
*
* Returns ContactListResult { contacts: UserProfile[], total: number }
* where total is the full count before pagination.
*/
export async function contactListAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { limit?: string; offset?: string };
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const result = await client.invoke(
new Api.contacts.GetContacts({ hash: BigInt(0) as any }),
);
// Handle ContactsNotModified
if ((result as any).className === 'contacts.ContactsNotModified') {
outputBatchResult({ contacts: [], total: 0 }, []);
return;
}
// Build userMap from result.users keyed by bigIntToString(user.id)
const userMap = new Map<string, Api.User>();
for (const user of (result as any).users ?? []) {
userMap.set(bigIntToString(user.id), user);
}
// Get contact user IDs from result.contacts
const contactUserIds: string[] = [];
for (const contact of (result as any).contacts ?? []) {
contactUserIds.push(bigIntToString(contact.userId));
}
// Sort alphabetically by firstName + lastName
contactUserIds.sort((a, b) => {
const userA = userMap.get(a);
const userB = userMap.get(b);
const nameA = [userA?.firstName ?? '', userA?.lastName ?? ''].join(' ').trim().toLowerCase();
const nameB = [userB?.firstName ?? '', userB?.lastName ?? ''].join(' ').trim().toLowerCase();
return nameA.localeCompare(nameB);
});
const total = contactUserIds.length;
// Apply pagination
const page = contactUserIds.slice(offset, offset + limit);
// Enrich with GetFullUser in batches of 5
const profiles: UserProfile[] = [];
const errors: BatchItemError[] = [];
const BATCH_SIZE = 5;
for (let i = 0; i < page.length; i += BATCH_SIZE) {
const batch = page.slice(i, i + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(async (userId) => {
const user = userMap.get(userId);
if (!user) throw new TgError('Contact user was absent from the Telegram response', ErrorCode.PEER_NOT_FOUND);
const fullResult = await client.invoke(
new Api.users.GetFullUser({ id: user }),
);
const fullUser = fullResult.fullUser;
const userFromResult = (fullResult.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(user.id)) ?? user) as Api.User;
return buildUserProfile(client, user, fullUser, userFromResult, err => {
errors.push(batchError(userId, err, 'Could not fetch profile photos'));
});
}),
);
for (const [index, r] of results.entries()) {
if (r.status === 'fulfilled' && r.value != null) {
profiles.push(r.value);
} else if (r.status === 'rejected') {
errors.push(batchError(batch[index], r.reason));
}
}
}
outputBatchResult({ contacts: profiles, total }, errors);
});
}

View file

@ -0,0 +1,146 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import bigInt from 'big-integer';
import { outputError } from '../../lib/output.js';
import { bigIntToString } from '../../lib/serialize.js';
import { validatePagination } from '../../lib/validate.js';
import { formatError, TgError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { buildUserProfile } from '../../lib/user-profile.js';
import { withAuth } from '../../lib/with-auth.js';
import { batchError, outputBatchResult } from '../../lib/batch-results.js';
import type { BatchItemError, GlobalOptions, ContactSearchItem } from '../../lib/types.js';
function normalizeSearchText(value: string): string {
return value.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim();
}
/**
* Action handler for `tg contact search <query>`.
*
* Searches the address book locally by name/username. With --global, appends
* remote username matches after local contacts, within the same result limit.
*
* Returns ContactSearchResult { results: ContactSearchItem[], total: number }
* Contact membership comes from the address book, not contacts.Search.myResults.
*/
export async function contactSearchAction(this: Command, query: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { global?: boolean; limit?: string };
const globalMode = !!opts.global;
const normalizedQuery = normalizeSearchText(query);
const usernameQuery = normalizedQuery.replace(/^@/, '');
if (!usernameQuery) {
outputError('Search query cannot be empty', ErrorCode.INVALID_INPUT);
return;
}
let limit: number;
try {
({ limit } = validatePagination({ limit: opts.limit }, 20));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const errors: BatchItemError[] = [];
const userMap = new Map<string, Api.User>();
const myContactIds = new Set<string>();
const peerUserIds: string[] = [];
const seenIds = new Set<string>();
const addCandidate = (id: string) => {
if (!seenIds.has(id)) {
peerUserIds.push(id);
seenIds.add(id);
}
};
// contacts.Search excludes the address book. Fetch it without a cache hash
// and match names/usernames locally, including queries shorter than 3 chars.
try {
const contacts = await client.invoke(new Api.contacts.GetContacts({ hash: bigInt.zero }));
if (!('contacts' in contacts)) {
throw new TgError('Telegram returned unchanged contacts without a cached contact list', ErrorCode.UNKNOWN_ERROR);
}
for (const u of contacts.users) userMap.set(bigIntToString(u.id), u as Api.User);
for (const contact of contacts.contacts) {
const id = bigIntToString(contact.userId);
if (myContactIds.has(id)) continue;
myContactIds.add(id);
const user = userMap.get(id);
if (!user) {
errors.push(batchError(id, new TgError('Contact user was absent from the Telegram response', ErrorCode.PEER_NOT_FOUND)));
continue;
}
const fullName = normalizeSearchText([user.firstName, user.lastName].filter(Boolean).join(' '));
const username = normalizeSearchText(user.username ?? '');
if ((!normalizedQuery.startsWith('@') && fullName.includes(normalizedQuery))
|| username.includes(usernameQuery)) {
addCandidate(id);
}
}
} catch (err: unknown) {
errors.push(batchError('contacts', err, 'Could not read contacts'));
}
// Local contacts take precedence. Avoid a remote lookup when they already
// fill the page, so remote query limits do not hide usable local matches.
if (globalMode && peerUserIds.length < limit) {
try {
const found = await client.invoke(new Api.contacts.Search({ q: query.trim().replace(/^@/, ''), limit }));
for (const u of found.users) {
const id = bigIntToString(u.id);
if (!userMap.has(id)) userMap.set(id, u as Api.User);
}
for (const peer of [...found.myResults, ...found.results]) {
if ('userId' in peer) addCandidate(bigIntToString(peer.userId));
}
} catch (err: unknown) {
errors.push(batchError(query, err, 'Global username search failed'));
}
}
// Apply the CLI limit after deduplication, before expensive enrichment RPCs.
const selectedUserIds = peerUserIds.slice(0, limit);
// Enrich with GetFullUser in batches of 5
const results: ContactSearchItem[] = [];
const BATCH_SIZE = 5;
for (let i = 0; i < selectedUserIds.length; i += BATCH_SIZE) {
const batch = selectedUserIds.slice(i, i + BATCH_SIZE);
const enriched = await Promise.allSettled(
batch.map(async (userId) => {
const user = userMap.get(userId);
if (!user) throw new TgError('Contact user was absent from the Telegram response', ErrorCode.PEER_NOT_FOUND);
const fullResult = await client.invoke(
new Api.users.GetFullUser({ id: user }),
);
const fullUser = fullResult.fullUser;
const userFromResult = (fullResult.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(user.id)) ?? user) as Api.User;
const profile = await buildUserProfile(client, user, fullUser, userFromResult, err => {
errors.push(batchError(userId, err, 'Could not fetch profile photos'));
});
return {
...profile,
isContact: myContactIds.has(userId) || userFromResult.contact === true,
} as ContactSearchItem;
}),
);
for (const [index, r] of enriched.entries()) {
if (r.status === 'fulfilled' && r.value != null) {
results.push(r.value);
} else if (r.status === 'rejected') {
errors.push(batchError(batch[index], r.reason));
}
}
}
outputBatchResult({ results, total: results.length }, errors);
});
}

View file

@ -0,0 +1,55 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { CustomFile } from 'teleproto/client/uploads.js';
import { readFileSync, statSync } from 'node:fs';
import { resolve, basename, isAbsolute } from 'node:path';
import { withAuth } from '../../lib/with-auth.js';
import { resolveEntity } from '../../lib/peer.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { bigIntToString } from '../../lib/serialize.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { getDaemonContext } from '../../lib/daemon/execution-context.js';
import type { GlobalOptions, ContactPhotoResult } from '../../lib/types.js';
/** Set a personal contact photo visible only to the current account. */
export async function contactSetPhotoAction(this: Command, user: string, file: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const context = getDaemonContext();
if (context && (!context.cwd || !isAbsolute(context.cwd))) {
outputError('Contact photo commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS);
return;
}
const filePath = resolve(context?.cwd ?? process.cwd(), file);
let bytes: Buffer;
try {
if (!statSync(filePath).isFile()) throw new Error('Not a regular file');
bytes = readFileSync(filePath);
} catch {
outputError('Photo must be a readable regular file', ErrorCode.FILE_NOT_FOUND);
return;
}
const jpeg = bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
const png = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
if (!jpeg && !png) {
outputError('Photo must contain a JPEG or PNG image', ErrorCode.INVALID_PHOTO);
return;
}
await withAuth(opts, async client => {
const entity = await resolveEntity(client, user);
if (!(entity instanceof Api.User)) {
outputError('Personal photos require a user contact', ErrorCode.NOT_A_USER);
return;
}
const uploaded = await client.uploadFile({ file: new CustomFile(basename(filePath), bytes.length, filePath, bytes), workers: 1 });
const result = await client.invoke(new Api.photos.UploadContactProfilePhoto({
userId: entity, file: uploaded, save: true, suggest: false,
}));
const photoId = bigIntToString(result.photo?.id);
if (!photoId) {
outputError('Telegram did not return the personal photo result; verify before retrying', ErrorCode.PHOTO_RESULT_UNAVAILABLE);
return;
}
const data: ContactPhotoResult = { userId: bigIntToString(entity.id)!, photoId, personal: true, size: bytes.length };
outputSuccess(data);
});
}

View file

@ -0,0 +1,28 @@
import { Command } from 'commander';
import { daemonStartAction } from './start.js';
import { daemonStopAction } from './stop.js';
import { daemonStatusAction } from './status.js';
export function createDaemonCommand(): Command {
const daemon = new Command('daemon')
.description('Manage persistent Telegram connection daemon');
daemon
.command('start')
.description('Start the daemon for persistent connection')
.option('--idle-timeout <seconds>', 'Auto-stop after N seconds of inactivity (0 = keep running)', '300')
.option('--foreground', 'Run in foreground (do not fork)')
.action(daemonStartAction);
daemon
.command('stop')
.description('Stop the running daemon')
.action(daemonStopAction);
daemon
.command('status')
.description('Check daemon status')
.action(daemonStatusAction);
return daemon;
}

View file

@ -0,0 +1,158 @@
import type { Command } from 'commander';
import { fork } from 'node:child_process';
import { createConfig, getCredentialsOrThrow } from '../../lib/config.js';
import { resolveTransport } from '../../lib/transport.js';
import { SessionStore } from '../../lib/session-store.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { DaemonPaths } from '../../lib/daemon/pid.js';
import { DaemonClient } from '../../lib/daemon/client.js';
import { DaemonServer } from '../../lib/daemon/server.js';
import { resolveDaemonEntry } from '../../lib/daemon/entry-path.js';
import { daemonChildEnv, installDaemonSignals, isProcessAlive, waitWhile } from '../../lib/daemon/lifecycle.js';
import { cleanupStaleDaemon, daemonPidAlive } from '../../lib/daemon/guard.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
import { parseIntegerOption, validateProfile } from '../../lib/validate.js';
export async function daemonStartAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { idleTimeout?: string; foreground?: boolean };
const { profile, quiet } = opts;
validateProfile(profile);
const idleTimeout = parseIntegerOption(opts.idleTimeout ?? '300', '--idle-timeout', {
max: 2_147_483,
}) * 1000;
const config = createConfig(opts.config);
const configDir = config.path.replace(/[/\\][^/\\]+$/, '');
const paths = new DaemonPaths(configDir, profile);
// Check if already running
if (paths.socketExists()) {
try {
const client = new DaemonClient(paths.socketPath);
const status = await client.call('ping', {});
client.close();
if (status === 'pong') {
outputError('Daemon is already running', ErrorCode.DAEMON_ALREADY_RUNNING);
return;
}
if (!cleanupStaleDaemon(paths)) {
outputError(
'Daemon is not responding. Try: tg daemon stop && tg daemon start',
ErrorCode.DAEMON_CONNECTION_FAILED,
);
return;
}
} catch {
if (!cleanupStaleDaemon(paths)) {
outputError(
'Daemon is not responding. Try: tg daemon stop && tg daemon start',
ErrorCode.DAEMON_CONNECTION_FAILED,
);
return;
}
}
}
if (daemonPidAlive(paths)) {
outputError('Daemon is already running', ErrorCode.DAEMON_ALREADY_RUNNING);
return;
}
// Load session
const store = new SessionStore(configDir);
const sessionString = await store.load(profile);
if (!sessionString) {
outputError('Not logged in. Run: tg auth login', ErrorCode.NOT_AUTHENTICATED);
return;
}
const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile);
const transport = resolveTransport(config, profile, opts.transport);
if (opts.foreground) {
logStatus('Starting daemon in foreground...', quiet);
const server = new DaemonServer(
paths,
{ apiId, apiHash, transport },
{ idleTimeout, onIdle: () => process.exit(0) },
);
const uninstallSignals = installDaemonSignals(() => server.stop());
try {
await server.start();
} catch (err: unknown) {
uninstallSignals();
outputError(
`Daemon failed to start: ${(err as Error).message}`,
ErrorCode.DAEMON_START_FAILED,
);
return;
}
logStatus(`Daemon running on ${paths.socketPath} (PID ${process.pid})`, quiet);
outputSuccess({ pid: process.pid, socket: paths.socketPath, profile });
await new Promise(() => {});
} else {
const daemonEntry = resolveDaemonEntry(import.meta.url);
const child = fork(daemonEntry, [], {
detached: true,
stdio: 'ignore',
env: daemonChildEnv({
configDir,
profile,
idleTimeout,
configPath: opts.config,
transport,
}),
});
// fork() creates an IPC channel even with ignored stdio. Readiness uses the
// Unix socket, so close unused IPC before unref or it keeps this CLI alive.
if (child.connected) child.disconnect();
child.unref();
const childPid = child.pid;
if (childPid == null) {
outputError('Daemon failed to start (fork returned no pid)', ErrorCode.DAEMON_START_FAILED);
return;
}
if (!paths.writePidExclusive(childPid)) {
try { process.kill(childPid, 'SIGTERM'); } catch { /* already gone */ }
outputError('Daemon is already running', ErrorCode.DAEMON_ALREADY_RUNNING);
return;
}
const maxWait = 10_000;
const started = Date.now();
while (Date.now() - started < maxWait) {
if (paths.socketExists()) {
try {
const ready = new DaemonClient(paths.socketPath);
const pong = await ready.call('ping', {}, { timeoutMs: 1000 });
ready.close();
if (pong === 'pong') {
outputSuccess({
pid: paths.readPid() ?? childPid,
socket: paths.socketPath,
profile,
});
return;
}
} catch {
// Socket exists but not accepting yet
}
}
await new Promise(r => setTimeout(r, 100));
}
try { process.kill(childPid, 'SIGTERM'); } catch { /* already gone */ }
await waitWhile(() => isProcessAlive(childPid), 5_000);
if (isProcessAlive(childPid)) {
try { process.kill(childPid, 'SIGKILL'); } catch { /* already gone */ }
}
paths.cleanupOwned(childPid);
outputError('Daemon failed to start within 10 seconds', ErrorCode.DAEMON_START_FAILED);
}
}

View file

@ -0,0 +1,29 @@
import type { Command } from 'commander';
import { createConfig } from '../../lib/config.js';
import { outputSuccess } from '../../lib/output.js';
import { DaemonPaths } from '../../lib/daemon/pid.js';
import { DaemonClient } from '../../lib/daemon/client.js';
import type { GlobalOptions } from '../../lib/types.js';
export async function daemonStatusAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const { profile } = opts;
const config = createConfig(opts.config);
const configDir = config.path.replace(/[/\\][^/\\]+$/, '');
const paths = new DaemonPaths(configDir, profile);
if (!paths.socketExists()) {
outputSuccess({ running: false, profile });
return;
}
try {
const client = new DaemonClient(paths.socketPath);
const status = await client.call('status', {}) as Record<string, unknown>;
client.close();
outputSuccess({ ...status, profile });
} catch {
outputSuccess({ running: false, profile, stale: true });
}
}

View file

@ -0,0 +1,75 @@
import type { Command } from 'commander';
import { createConfig } from '../../lib/config.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { DaemonPaths } from '../../lib/daemon/pid.js';
import { DaemonClient } from '../../lib/daemon/client.js';
import { isProcessAlive, waitWhile } from '../../lib/daemon/lifecycle.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
export async function daemonStopAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const { profile, quiet } = opts;
const config = createConfig(opts.config);
const configDir = config.path.replace(/[/\\][^/\\]+$/, '');
const paths = new DaemonPaths(configDir, profile);
const pid = paths.readPid();
if (!pid && !paths.socketExists()) {
outputError('Daemon is not running', ErrorCode.DAEMON_NOT_RUNNING);
return;
}
if (paths.socketExists()) {
try {
const client = new DaemonClient(paths.socketPath);
await client.call('shutdown', {});
client.close();
} catch {
// Socket unresponsive
}
await waitWhile(() => paths.socketExists(), 5_000);
}
if (pid && isProcessAlive(pid)) {
try {
process.kill(pid, 'SIGTERM');
} catch {
// Process already dead
}
await waitWhile(() => isProcessAlive(pid), 5_000);
}
if (pid && isProcessAlive(pid)) {
outputError('Daemon did not stop (process still running)', ErrorCode.DAEMON_STOP_FAILED);
return;
}
const now = paths.readPid();
if (now !== null && now !== pid) {
// Successor already claimed the pid file. Do not unlink its files.
logStatus('Daemon stopped.', quiet);
outputSuccess({ stopped: true, profile });
return;
}
if (paths.socketExists()) {
try {
const client = new DaemonClient(paths.socketPath);
const pong = await client.call('ping', {});
client.close();
if (pong === 'pong') {
outputError('Daemon did not stop (socket still accepting connections)', ErrorCode.DAEMON_STOP_FAILED);
return;
}
} catch {
// Unresponsive and no live pid: stale socket
}
}
paths.cleanup();
logStatus('Daemon stopped.', quiet);
outputSuccess({ stopped: true, profile });
}

View file

@ -0,0 +1,162 @@
import type { Command } from 'commander';
import { existsSync } from 'node:fs';
import { resolve, basename, sep, isAbsolute } from 'node:path';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { TgError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { extractMediaInfo, detectMedia } from '../../lib/serialize.js';
import { generateFilename, formatBytes } from '../../lib/media-utils.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageIds } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions, DownloadResult } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { getDaemonContext } from '../../lib/daemon/execution-context.js';
const DOWNLOADABLE = new Set(['photo', 'video', 'voice', 'document', 'audio']);
/**
* Action handler for `tg media download <chat> <msg-ids>`.
*
* Downloads media from one or more messages. Supports:
* - Single download: `tg media download @chat 123`
* - Batch download: `tg media download @chat 123,456,789`
* - Output override: `-o <path>` (file for single, directory for batch)
* - Auto-naming from Telegram metadata or generateFilename fallback
* - Progress output on stderr (suppressed with --quiet)
*
* Returns DownloadResult for single, { files, downloaded, failed } for batch.
*/
export async function mediaDownloadAction(this: Command): Promise<void> {
const chat = this.args[0];
const rawIds = this.args[1];
const opts = this.optsWithGlobals() as GlobalOptions & { output?: string; force?: boolean };
const { quiet } = opts;
const context = getDaemonContext();
if (context && (!context.cwd || !isAbsolute(context.cwd))) {
outputError('Media commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS);
return;
}
const cwd = context?.cwd ?? process.cwd();
let messageIds: number[];
try {
messageIds = parseMessageIds(rawIds);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
const isBatch = messageIds.length > 1;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
const results: DownloadResult[] = [];
const failed: { messageId: number; error: string; code: string }[] = [];
const downloadOne = async (msgId: number): Promise<DownloadResult> => {
const messages = await client.getMessages(entity, { ids: [msgId] });
const msg = messages[0];
if (!msg || !msg.media) {
throw new TgError(
`Message ${msgId} has no downloadable media`,
ErrorCode.NO_MEDIA,
);
}
const { mediaType } = detectMedia((msg as any).media);
if (!mediaType || !DOWNLOADABLE.has(mediaType)) {
throw new TgError(
`Message ${msgId} has no downloadable media`,
ErrorCode.NO_MEDIA,
);
}
const mediaInfo = extractMediaInfo((msg as any).media);
const rawFilename = mediaInfo?.filename;
const filename = rawFilename
? basename(rawFilename)
: generateFilename(mediaType, msgId, mediaInfo?.mimeType ?? null);
let targetPath: string;
if (opts.output) {
if (isBatch) {
targetPath = resolve(cwd, opts.output, filename);
} else {
targetPath = resolve(cwd, opts.output);
}
} else {
targetPath = resolve(cwd, filename);
}
const allowedDir = opts.output ? resolve(cwd, opts.output) : cwd;
const baseDir = isBatch || !opts.output ? allowedDir : resolve(allowedDir, '..');
if (targetPath !== baseDir && !targetPath.startsWith(baseDir + sep)) {
throw new TgError(
`Path traversal detected: ${targetPath} is outside ${baseDir}`,
ErrorCode.PATH_TRAVERSAL,
);
}
if (existsSync(targetPath) && !opts.force) {
throw new TgError(
`File exists: ${targetPath} (use --force to overwrite)`,
ErrorCode.FILE_EXISTS,
);
}
let lastProgressTime = 0;
await client.downloadMedia(msg as any, {
outputFile: targetPath,
progressCallback: (downloaded: any, total: any) => {
const now = Date.now();
if (now - lastProgressTime < 1000) return;
lastProgressTime = now;
const dl = typeof downloaded?.toJSNumber === 'function'
? downloaded.toJSNumber() : Number(downloaded);
const tot = typeof total?.toJSNumber === 'function'
? total.toJSNumber() : Number(total);
const pct = tot > 0 ? Math.round((dl / tot) * 100) : 0;
logStatus(
`Downloading ${filename}: ${pct}% (${formatBytes(dl)}/${formatBytes(tot)})`,
quiet,
);
},
});
const savedFilename = (!isBatch && opts.output)
? basename(targetPath)
: filename;
return {
path: targetPath,
filename: savedFilename,
size: mediaInfo?.fileSize ?? 0,
mediaType,
messageId: msgId,
};
};
for (const msgId of messageIds) {
try {
results.push(await downloadOne(msgId));
} catch (err: unknown) {
if (!isBatch) throw err;
const { message, code } = formatError(err);
failed.push({
messageId: msgId,
error: message,
code: code ?? ErrorCode.UNKNOWN_ERROR,
});
}
}
if (isBatch) {
outputSuccess({ files: results, downloaded: results.length, failed });
} else {
outputSuccess(results[0]);
}
});
}

View file

@ -0,0 +1,36 @@
import { Command } from 'commander';
import { mediaDownloadAction } from './download.js';
import { mediaSendAction } from './send.js';
/**
* Create the `media` command group with download and send subcommands.
*
* Usage:
* tg media download <chat> <msg-ids> - Download media from messages
* tg media send <chat> <files...> - Upload and send files to a chat
*/
export function createMediaCommand(): Command {
const media = new Command('media')
.description('Download and upload media files');
media
.command('download')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<msg-ids>', 'Message ID(s), comma-separated for batch')
.description('Download media from messages')
.option('-o, --output <path>', 'Output path (file for single, directory for batch)')
.option('--force', 'Overwrite existing files')
.action(mediaDownloadAction);
media
.command('send')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<files...>', 'File path(s) to send (multiple = album)')
.description('Upload and send files to a chat')
.option('--caption <text>', 'Caption for the media')
.option('--reply-to <msgId>', 'Reply to message ID')
.option('--topic <topicId>', 'Forum topic ID')
.action(mediaSendAction);
return media;
}

View file

@ -0,0 +1,158 @@
import type { Command } from 'commander';
import { resolve, extname, isAbsolute } from 'node:path';
import { access } from 'node:fs/promises';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { resolveEntity, assertForum } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { detectFileType } from '../../lib/media-utils.js';
import { withAuth } from '../../lib/with-auth.js';
import type { GlobalOptions } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { parseMessageId, parseTopicId } from '../../lib/validate.js';
import { outputBatchResult } from '../../lib/batch-results.js';
import type { BatchItemError } from '../../lib/types.js';
import { getDaemonContext } from '../../lib/daemon/execution-context.js';
/**
* Action handler for `tg media send <chat> <files...>`.
*
* Uploads and sends files to a chat. Supports:
* - Single file send: `tg media send @chat photo.jpg`
* - Album send (multiple files, max 10): `tg media send @chat a.jpg b.jpg c.jpg`
* - Caption: `--caption "My caption"`
* - Reply: `--reply-to 42`
* - Voice note auto-detection for .ogg/.opus files
* - Force document mode for non-photo/video/voice files
* - Progress output on stderr (suppressed with --quiet)
*
* Returns MessageItem for single, { messages, sent } for album.
*/
export async function mediaSendAction(this: Command): Promise<void> {
const chat = this.args[0];
const files = this.args.slice(1);
const opts = this.optsWithGlobals() as GlobalOptions & {
caption?: string;
replyTo?: string;
topic?: string;
};
const { quiet } = opts;
const context = getDaemonContext();
if (context && (!context.cwd || !isAbsolute(context.cwd))) {
outputError('Media commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS);
return;
}
const cwd = context?.cwd ?? process.cwd();
// Validate file count for albums
if (files.length > 10) {
outputError('Albums support a maximum of 10 files', ErrorCode.ALBUM_TOO_LARGE);
return;
}
// Validate all files exist before attempting upload
for (const fp of files) {
try {
await access(resolve(cwd, fp));
} catch {
outputError(`File not found: ${fp}`, ErrorCode.FILE_NOT_FOUND);
return;
}
}
let topicId: number | undefined;
if (opts.topic !== undefined) {
try {
topicId = parseTopicId(opts.topic);
} catch (err: unknown) {
outputError(
err instanceof Error ? err.message : 'Invalid topic ID: must be a number',
ErrorCode.INVALID_TOPIC_ID,
);
return;
}
}
let replyTo: number | undefined;
if (opts.replyTo !== undefined) {
try {
replyTo = parseMessageId(opts.replyTo);
} catch {
outputError('Invalid reply-to message ID: must be a positive message ID', ErrorCode.INVALID_REPLY_TO);
return;
}
}
if (topicId !== undefined && replyTo !== undefined) {
outputError(
'--topic and --reply-to cannot be combined yet. Use --reply-to to reply in-topic, or --topic to post to the topic root.',
ErrorCode.INVALID_OPTIONS,
);
return;
}
const effectiveReplyTo = topicId !== undefined ? topicId : replyTo;
const isAlbum = files.length > 1;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
// Forum guard: reject --topic on non-forum chats
await assertForum(entity, topicId);
// Build send params
const sendParams: any = {
file: isAlbum
? files.map(f => resolve(cwd, f))
: resolve(cwd, files[0]),
caption: opts.caption ?? '',
replyTo: effectiveReplyTo,
progressCallback: (progress: number) => {
logStatus(
`Uploading: ${Math.round(progress * 100)}%`,
quiet,
);
},
};
// Single file type detection
if (!isAlbum) {
const ext = extname(files[0]);
const fileType = detectFileType(ext);
if (fileType === 'voice') {
sendParams.voiceNote = true;
} else if (fileType === 'document') {
sendParams.forceDocument = true;
}
}
const result = await client.sendFile(entity, sendParams);
if (!isAlbum && result == null) {
outputError('Telegram did not return the sent message ID; the file may have been sent and retrying may create a duplicate', ErrorCode.MESSAGE_RESULT_UNAVAILABLE);
return;
}
if (isAlbum) {
// gramjs returns each sent message; their IDs need not be consecutive.
const returnedMessages = Array.isArray(result) ? result : [result];
const sentMessages = returnedMessages.filter(message => message != null);
const serialized = sentMessages.map(message => serializeMessage(message));
const output: Record<string, unknown> = { messages: serialized, sent: serialized.length };
const errors: BatchItemError[] = [];
for (let index = 0; index < files.length; index++) {
if (returnedMessages[index] == null) {
errors.push({ input: files[index], error: `Message ID for album item ${index + 1} is unavailable after sending; retrying may create a duplicate`, code: ErrorCode.MESSAGE_RESULT_UNAVAILABLE });
}
}
if (sentMessages.length !== files.length) {
output.warning = `Telegram returned ${sentMessages.length} messages for ${files.length} files; missing message IDs are unknown`;
}
outputBatchResult(output, errors);
} else {
// Single file: serialize and return
const serialized = serializeMessage(result as any);
outputSuccess(serialized);
}
});
}

View file

@ -0,0 +1,69 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageIds } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions, DeleteResult } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg message delete <chat> <ids>`.
*
* Deletes messages in a chat. Requires explicit --revoke (delete for everyone)
* or --for-me (delete for self only) flag for safety.
*
* Accepts comma-separated IDs (max 100). Returns DeleteResult shape.
* Uses translateTelegramError for Telegram-specific permission errors.
*/
export async function messageDeleteAction(this: Command, chat: string, idsInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { revoke?: boolean; forMe?: boolean };
// Safety: require explicit mode selection, mutually exclusive
if (!opts.revoke && !opts.forMe) {
outputError('Specify --revoke (delete for everyone) or --for-me (delete for self)', ErrorCode.DELETE_MODE_REQUIRED);
return;
}
if (opts.revoke && opts.forMe) {
outputError('--revoke and --for-me are mutually exclusive', ErrorCode.INVALID_OPTIONS);
return;
}
let numericIds: number[];
try {
numericIds = parseMessageIds(idsInput);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
const mode: 'revoke' | 'for-me' = opts.revoke ? 'revoke' : 'for-me';
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
// Telegram only supports deleting for everyone in channels and supergroups.
// gramjs silently ignores revoke:false for these peers, so reject before RPC.
if (mode === 'for-me' && ['Channel', 'ChannelForbidden', 'InputPeerChannel', 'PeerChannel'].includes(entity.className)) {
outputError('--for-me is not supported in channels or supergroups. Use --revoke to delete for everyone.', ErrorCode.INVALID_OPTIONS);
return;
}
try {
await client.deleteMessages(entity, numericIds, { revoke: mode === 'revoke' });
// If no error thrown, all deletions succeeded
const result: DeleteResult = {
deleted: numericIds,
failed: [],
mode,
};
outputSuccess(result);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}

View file

@ -0,0 +1,85 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError, formatError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageId } from '../../lib/validate.js';
import type { GlobalOptions } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { getDaemonContext } from '../../lib/daemon/execution-context.js';
/**
* Read all data from stdin as a UTF-8 string.
* Used when the text argument is "-" (dash placeholder) to support piped input.
*/
async function readStdin(): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
return Buffer.concat(chunks).toString('utf-8').trimEnd();
}
/**
* Action handler for `tg message edit <chat> <id> <text>`.
*
* Edits a text message in any chat. Supports:
* - Piped stdin input via dash placeholder: echo "new text" | tg message edit <chat> <id> -
* - gramjs built-in markdown parsing for **bold**, __italic__, `code`, [links](url)
*
* Returns the edited message as a serialized MessageItem (includes editDate).
* Uses translateTelegramError for Telegram-specific permission errors.
*/
export async function messageEditAction(this: Command, chat: string, msgId: string, text: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
let messageId: number;
try {
messageId = parseMessageId(msgId);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
// Handle stdin pipe via dash placeholder
if (text === '-') {
const context = getDaemonContext();
if (context ? context.stdin === undefined : process.stdin.isTTY) {
outputError('"-" requires piped input. Example: echo "new text" | tg message edit @user 42 -', ErrorCode.STDIN_REQUIRED);
return;
}
text = context ? context.stdin!.trimEnd() : await readStdin();
}
// Validate non-empty text
if (!text) {
outputError('Message text is required', ErrorCode.EMPTY_MESSAGE);
return;
}
// Telegram message length limit
if (text.length > 4096) {
outputError('Message too long (max 4096 chars)', ErrorCode.MESSAGE_TOO_LONG);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
try {
// gramjs built-in MarkdownParser handles **bold**, __italic__, `code`, [links](url) automatically
const editedMsg = await client.editMessage(entity, {
message: messageId,
text,
});
const serialized = serializeMessage(editedMsg as any, (editedMsg as any)._sender);
outputSuccess(serialized);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}

View file

@ -0,0 +1,50 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageIds } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Action handler for `tg message forward <from-chat> <msg-ids> <to-chat>`.
*
* Forwards one or more messages from a source chat to a destination chat.
* Message IDs are comma-separated: `tg message forward @source 123,456,789 @dest`
*
* Uses Telegram's native batch forward API via gramjs forwardMessages.
* Always passes fromPeer to avoid PEER_ID_INVALID when using integer IDs.
*
* Returns: { forwarded: N, messages: MessageItem[] }
*/
export async function messageForwardAction(this: Command, fromChat: string, msgIds: string, toChat: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
let ids: number[];
try {
ids = parseMessageIds(msgIds);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const fromEntity = await resolveEntity(client, fromChat);
const toEntity = await resolveEntity(client, toChat);
// MUST pass fromPeer when using integer IDs (pitfall #2 from research)
const forwarded = await client.forwardMessages(toEntity, {
messages: ids,
fromPeer: fromEntity,
});
const messages = forwarded.map((msg: any) => serializeMessage(msg));
outputSuccess({
forwarded: messages.length,
messages,
});
});
}

View file

@ -0,0 +1,67 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { messagePeerMarkedId, serializeMessage } from '../../lib/serialize.js';
import { buildEntityMap } from '../../lib/entity-map.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageIds } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions, MessageItem } from '../../lib/types.js';
/**
* Action handler for `tg message get <chat> <ids>`.
*
* Fetches specific messages by ID from a chat. Accepts comma-separated IDs (max 100).
* Returns found messages and a list of IDs that were not found.
*
* Output shape: { messages: MessageItem[], notFound: number[] }
*/
export async function messageGetAction(
this: Command,
chatInput: string,
idsInput: string,
): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
let numericIds: number[];
try {
numericIds = parseMessageIds(idsInput);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
// getMessages returns array where missing entries are undefined
const result = await client.getMessages(entity, { ids: numericIds });
const found: MessageItem[] = [];
const notFound: number[] = [];
// Build entity map as fallback for sender resolution
const entityMap = buildEntityMap(result);
// Iterate by index to preserve input order
for (let i = 0; i < numericIds.length; i++) {
const msg = result[i];
if (msg) {
// Prefer _sender from gramjs _finishInit, fall back to entity map
let senderEntity = (msg as any)._sender;
if (!senderEntity) {
const senderId = messagePeerMarkedId({ peerId: (msg as any).fromId });
if (senderId) {
senderEntity = entityMap.get(senderId);
}
}
found.push(serializeMessage(msg, senderEntity));
} else {
notFound.push(numericIds[i]);
}
}
outputSuccess({ messages: found, notFound });
});
}

View file

@ -0,0 +1,98 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity, assertForum } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { validatePagination, parseIsoDate, parseTopicId } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions, MessageItem } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg message history <chat>`.
*
* Reads message history from a chat with pagination and date filtering.
* Options: --limit (default 50), --offset (default 0), --since <date>, --until <date>
*
* Date options use ISO 8601 format (e.g., 2026-03-01T00:00:00Z).
* --until uses server-side offsetDate for efficiency.
* --since uses post-filtering (newest-first ordering ensures early stop).
*/
export async function messageHistoryAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & {
limit: string;
offset: string;
since?: string;
until?: string;
topic?: string;
};
let limit: number;
let offset: number;
let untilDate: Date | undefined;
let sinceDate: Date | undefined;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
if (opts.until) untilDate = parseIsoDate(opts.until, '--until');
if (opts.since) sinceDate = parseIsoDate(opts.since, '--since');
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
let topicId: number | undefined;
if (opts.topic !== undefined) {
try {
topicId = parseTopicId(opts.topic);
} catch (err: unknown) {
outputError(
err instanceof Error ? err.message : 'Invalid topic ID: must be a number',
ErrorCode.INVALID_TOPIC_ID,
);
return;
}
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
// Forum guard: reject --topic on non-forum chats
await assertForum(entity, topicId);
// Build getMessages parameters
const params: Record<string, any> = {
limit,
addOffset: offset,
};
// --topic: scope messages to a specific forum topic
if (topicId !== undefined) {
params.replyTo = topicId;
}
// --until: server-side date filter via offsetDate
if (untilDate) {
params.offsetDate = Math.floor(untilDate.getTime() / 1000);
}
const messages = await client.getMessages(entity, params);
// Serialize messages
let serialized: MessageItem[] = messages.map((msg: any) =>
serializeMessage(msg),
);
// --since: post-filter messages after the given date
if (sinceDate) {
const sinceMs = sinceDate.getTime();
serialized = serialized.filter(
(m) => new Date(m.date).getTime() >= sinceMs,
);
}
outputSuccess({
messages: serialized,
total: (messages as any).total ?? 0,
});
});
}

View file

@ -0,0 +1,185 @@
import { Command } from 'commander';
import { messageHistoryAction } from './history.js';
import { messageSearchAction } from './search.js';
import { messageSendAction } from './send.js';
import { messageForwardAction } from './forward.js';
import { messageReactAction } from './react.js';
import { messageRepliesAction } from './replies.js';
import { messageGetAction } from './get.js';
import { messagePinnedAction } from './pinned.js';
import { messageEditAction } from './edit.js';
import { messageDeleteAction } from './delete.js';
import { messagePinAction } from './pin.js';
import { messageUnpinAction } from './unpin.js';
import { messagePollAction } from './poll.js';
import { messageWatchAction } from './watch.js';
/**
* Create the `message` command group with history, search, get, pinned, send, forward, react, replies,
* edit, delete, pin, unpin, poll, and watch subcommands.
*
* Usage:
* tg message history <chat> - Read message history from a chat
* tg message search - Search messages by keyword
* tg message get <chat> <ids> - Get specific messages by ID (comma-separated, max 100)
* tg message pinned <chat> - Get pinned messages from a chat
* tg message send <chat> <text> - Send a text message
* tg message forward <from> <ids> <to> - Forward messages between chats
* tg message react <chat> <id> <emoji> - React to a message
* tg message replies <channel> <msg-ids> - Read replies/comments on channel posts (comma-separated)
* tg message edit <chat> <id> <text> - Edit a sent message
* tg message delete <chat> <ids> - Delete messages (--revoke or --for-me required)
* tg message pin <chat> <id> - Pin a message (silent by default)
* tg message unpin <chat> <id> - Unpin a message
* tg message poll <chat> - Send a poll to a chat
*/
export function createMessageCommand(): Command {
const message = new Command('message')
.description('Message reading, sending, and interaction');
message
.command('history')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Read message history from a chat')
.option('--limit <n>', 'Max messages', '50')
.option('--offset <n>', 'Skip messages', '0')
.option('--since <date>', 'Messages after this date (ISO 8601)')
.option('--until <date>', 'Messages before this date (ISO 8601)')
.option('--topic <topicId>', 'Forum topic ID')
.action(messageHistoryAction);
message
.command('search')
.description('Search messages by keyword or media type')
.option('--chat <chat>', 'Search in specific chat or comma-separated chats (omit for global search)')
.option('--query <text>', 'Search query')
.option('--filter <type>', 'Filter by type (photos|videos|documents|urls|voice|music|gifs|round|photo_video|round_voice|chat_photos|phone_calls|mentions|geo|contacts|pinned)')
.option('--limit <n>', 'Max results', '50')
.option('--offset <n>', 'Skip results', '0')
.option('--topic <topicId>', 'Forum topic ID (single --chat only)')
.option('--public', 'Search public channel posts by hashtag (including channels you have not joined)')
.option('--peer <chat>', 'Public-search pagination peer (nextOffsetPeer from the previous page)')
.option('--after <msgId>', 'Public-search pagination message id (nextOffsetId)')
.addHelpText('after', `
Valid filters: photos, videos, photo_video, documents, urls, gifs, voice, music, round, round_voice, chat_photos, phone_calls, mentions, geo, contacts, pinned
Public hashtag search (CLI contract remains hashtag-only):
tg message search --public --query bitcoin
tg message search --public --query bitcoin --offset <nextRate> --peer <nextOffsetPeer> --after <nextOffsetId>`)
.action(messageSearchAction);
message
.command('get')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<ids>', 'Message IDs (comma-separated, max 100)')
.description('Get specific messages by ID')
.action(messageGetAction);
message
.command('pinned')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Get pinned messages from a chat')
.option('--limit <n>', 'Max messages', '50')
.option('--offset <n>', 'Skip messages', '0')
.action(messagePinnedAction);
message
.command('send')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<text>', 'Message text (use - for stdin)')
.description('Send a text message to a chat')
.option('--reply-to <msgId>', 'Reply to message ID')
.option('--topic <topicId>', 'Forum topic ID')
.option('--comment-to <postId>', 'Comment on a channel post')
.option('--schedule <iso>', 'Schedule on Telegram (ISO timestamp with timezone)')
.action(messageSendAction);
message
.command('forward')
.argument('<from-chat>', 'Source chat')
.argument('<msg-ids>', 'Message IDs (comma-separated)')
.argument('<to-chat>', 'Destination chat')
.description('Forward messages between chats')
.action(messageForwardAction);
message
.command('react')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<msg-id>', 'Message ID')
.argument('<emoji>', 'Emoji to react with')
.description('React to a message with an emoji')
.option('--remove', 'Remove reaction')
.action(messageReactAction);
message
.command('replies')
.argument('<channel>', 'Channel ID, username, or @username')
.argument('<msg-ids>', 'Post message IDs (comma-separated for batch)')
.description('Read replies/comments on channel posts')
.option('--limit <n>', 'Max replies per post', '50')
.option('--offset <n>', 'Skip replies', '0')
.action(messageRepliesAction);
message
.command('edit')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<msg-id>', 'Message ID')
.argument('<text>', 'New message text (use - for stdin)')
.description('Edit a sent message')
.action(messageEditAction);
message
.command('delete')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<ids>', 'Message IDs (comma-separated, max 100)')
.description('Delete messages')
.option('--revoke', 'Delete for everyone')
.option('--for-me', 'Delete only for self')
.action(messageDeleteAction);
message
.command('pin')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<msg-id>', 'Message ID')
.description('Pin a message in a chat')
.option('--notify', 'Notify members (silent by default)')
.action(messagePinAction);
message
.command('unpin')
.argument('<chat>', 'Chat ID, username, or @username')
.argument('<msg-id>', 'Message ID')
.description('Unpin a message from a chat')
.action(messageUnpinAction);
message
.command('poll')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Send a poll to a chat')
.requiredOption('--question <text>', 'Poll question (max 300 chars)')
.option('--option <text>', 'Poll option (repeat 2-10 times)', collect, [])
.option('--quiz', 'Quiz mode (one correct answer)')
.option('--correct <index>', 'Correct answer index, 1-based (requires --quiz)')
.option('--solution <text>', 'Solution explanation (requires --quiz)')
.option('--multiple', 'Allow multiple choices')
.option('--public', 'Show voter names (non-anonymous)')
.option('--close-in <seconds>', 'Auto-close after N seconds')
.action(messagePollAction);
message
.command('watch')
.argument('<chat>', 'Chat ID, username, or @username')
.description('Watch for new messages in real-time (requires daemon)')
.option('--topic <topicId>', 'Forum topic ID')
.action(messageWatchAction);
return message;
}
/**
* Commander repeatable option accumulator.
* Used for --option flags that can be specified multiple times.
*/
function collect(value: string, previous: string[]): string[] {
return [...previous, value];
}

View file

@ -0,0 +1,51 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError, formatError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageId } from '../../lib/validate.js';
import type { GlobalOptions, PinResult } from '../../lib/types.js';
/**
* Action handler for `tg message pin <chat> <msg-id>`.
*
* Pins a message in a chat. Silent by default (no notification).
* Use --notify to send a notification to chat members.
*
* Returns PinResult with messageId, chatId, action, and silent indicator.
* Uses translateTelegramError for Telegram-specific permission errors.
*/
export async function messagePinAction(this: Command, chat: string, msgId: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { notify?: boolean };
let messageId: number;
try {
messageId = parseMessageId(msgId);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
const notify = opts.notify ?? false;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
try {
await client.pinMessage(entity, messageId, { notify });
const result: PinResult = {
messageId,
chatId: markedPeerId(entity),
action: 'pinned',
silent: !notify,
};
outputSuccess(result);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}

View file

@ -0,0 +1,60 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { validatePagination } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions, MessageItem } from '../../lib/types.js';
/**
* Action handler for `tg message pinned <chat>`.
*
* Fetches pinned messages from a chat using the pinned filter.
* Returns serialized messages with total count for pagination.
*
* Output shape: { messages: MessageItem[], total: number }
*/
export async function messagePinnedAction(
this: Command,
chatInput: string,
): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & {
limit: string;
offset: string;
};
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chatInput);
// CRITICAL: Pass search: '' alongside the pinned filter to ensure gramjs
// creates a messages.Search request. Without this, gramjs falls through
// to GetHistory which ignores filters.
const messages = await client.getMessages(entity, {
search: '',
filter: new Api.InputMessagesFilterPinned(),
limit,
addOffset: offset,
});
const serialized: MessageItem[] = messages.map(msg =>
serializeMessage(msg, (msg as any)._sender),
);
outputSuccess({
messages: serialized,
total: (messages as any).total ?? 0,
});
});
}

View file

@ -0,0 +1,165 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import bigInt from 'big-integer';
import { generateRandomLong } from 'teleproto/Helpers.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
import { parseIntegerOption } from '../../lib/validate.js';
/**
* Options for the poll subcommand.
*/
interface PollOpts {
question: string;
option: string[];
quiz?: boolean;
correct?: string;
solution?: string;
multiple?: boolean;
public?: boolean;
closeIn?: string;
}
/**
* Validate poll options before sending to Telegram API.
* Returns null if valid, or { error, code } describing the first validation failure.
*
* Fail-fast: reports first error found.
*/
export function validatePollOpts(opts: Pick<PollOpts, 'question' | 'option' | 'quiz' | 'correct' | 'solution' | 'multiple' | 'closeIn'>): { error: string; code: string } | null {
// Question validation
if (!opts.question || opts.question.trim().length === 0) {
return { error: 'Poll question cannot be empty', code: ErrorCode.EMPTY_QUESTION };
}
if (opts.question.length > 300) {
return { error: 'Question too long (max 300 chars)', code: ErrorCode.QUESTION_TOO_LONG };
}
// Options count validation
if (opts.option.length < 2) {
return { error: 'Poll requires 2-10 options', code: ErrorCode.TOO_FEW_OPTIONS };
}
if (opts.option.length > 10) {
return { error: 'Poll requires 2-10 options', code: ErrorCode.TOO_MANY_OPTIONS };
}
// Individual option validation
for (const opt of opts.option) {
if (!opt || opt.trim().length === 0) {
return { error: 'Poll option cannot be empty', code: ErrorCode.EMPTY_OPTION };
}
if (opt.length > 100) {
return { error: 'Option too long (max 100 chars)', code: ErrorCode.OPTION_TOO_LONG };
}
}
// Duplicate detection
const seen = new Set<string>();
for (const opt of opts.option) {
if (seen.has(opt)) {
return { error: `Duplicate option text: '${opt}'`, code: ErrorCode.DUPLICATE_OPTION };
}
seen.add(opt);
}
// Quiz constraints
if (opts.quiz && !opts.correct) {
return { error: 'Quiz mode requires --correct <index>', code: ErrorCode.QUIZ_MISSING_CORRECT };
}
if (opts.solution && !opts.quiz) {
return { error: '--solution requires --quiz mode', code: ErrorCode.SOLUTION_WITHOUT_QUIZ };
}
if (opts.quiz && opts.multiple) {
return { error: 'Quiz mode cannot use --multiple', code: ErrorCode.QUIZ_MULTIPLE_CONFLICT };
}
// --correct range validation
if (opts.correct !== undefined) {
try {
parseIntegerOption(opts.correct, 'Correct index', { min: 1, max: opts.option.length });
} catch {
return { error: `Correct index must be 1-${opts.option.length}`, code: ErrorCode.INVALID_CORRECT_INDEX };
}
}
// --close-in validation
if (opts.closeIn !== undefined) {
try {
parseIntegerOption(opts.closeIn, 'Close-in seconds', { min: 1 });
} catch {
return { error: 'Close-in seconds must be > 0', code: ErrorCode.INVALID_CLOSE_IN };
}
}
return null;
}
/**
* Action handler for `tg message poll <chat>`.
*
* Sends a poll to a chat with full configuration support:
* basic polls, quiz mode, multiple choice, anonymous/public, auto-close timer.
*
* Validates all options client-side before making the API call.
* Returns serialized MessageItem via outputSuccess on success.
*/
export async function messagePollAction(this: Command, chat: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & PollOpts;
// Client-side validation
const validation = validatePollOpts(opts);
if (validation) {
outputError(validation.error, validation.code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
try {
// Build poll answers
const answers = opts.option.map((text) => new Api.InputPollAnswer({
text: new Api.TextWithEntities({ text, entities: [] }),
}));
const closeInSeconds = opts.closeIn !== undefined ? Number(opts.closeIn.trim()) : undefined;
const poll = new Api.Poll({
id: generateRandomLong(),
hash: bigInt.zero,
question: new Api.TextWithEntities({ text: opts.question, entities: [] }),
answers,
quiz: opts.quiz || undefined,
publicVoters: opts.public || undefined,
multipleChoice: opts.multiple || undefined,
closePeriod: closeInSeconds || undefined,
});
const correctIdx = opts.correct !== undefined ? Number(opts.correct.trim()) - 1 : undefined;
const inputMedia = new Api.InputMediaPoll({
poll,
correctAnswers: opts.quiz && correctIdx !== undefined
? [correctIdx]
: undefined,
solution: opts.solution || undefined,
solutionEntities: opts.solution ? [] : undefined,
});
const sentMsg = await client.sendFile(entity, { file: inputMedia });
if (!sentMsg) {
outputError('Telegram did not return the sent poll result; retrying may create a duplicate.', ErrorCode.MESSAGE_RESULT_UNAVAILABLE);
return;
}
const serialized = serializeMessage(sentMsg as any);
outputSuccess(serialized);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}

View file

@ -0,0 +1,56 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageId } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Action handler for `tg message react <chat> <msg-id> <emoji>`.
*
* Adds or removes an emoji reaction on a message.
* Uses Api.messages.SendReaction with Api.ReactionEmoji wrapper (NOT plain string).
* Remove with --remove flag sends empty reaction array.
*
* Returns: { messageId, chatId, emoji, action: 'added'|'removed' }
*/
export async function messageReactAction(this: Command, chat: string, msgId: string, emoji: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { remove?: boolean };
const remove = opts.remove ?? false;
let messageId: number;
try {
messageId = parseMessageId(msgId);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
// CRITICAL: reaction MUST be Api.ReactionEmoji[], NOT plain string (pitfall #1)
const reaction = remove
? []
: [new Api.ReactionEmoji({ emoticon: emoji })];
await client.invoke(
new Api.messages.SendReaction({
peer: entity,
msgId: messageId,
reaction,
}),
);
outputSuccess({
messageId,
chatId: markedPeerId(entity),
emoji,
action: remove ? 'removed' : 'added',
});
});
}

View file

@ -0,0 +1,107 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { messagePeerMarkedId, serializeMessage } from '../../lib/serialize.js';
import { buildEntityMap } from '../../lib/entity-map.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageIds, validatePagination } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import { batchError, outputBatchResult } from '../../lib/batch-results.js';
import type { BatchItemError, GlobalOptions, MessageItem } from '../../lib/types.js';
/**
* Serialize messages from a GetReplies result, resolving sender names.
*/
function serializeReplies(result: any): MessageItem[] {
const entityMap = buildEntityMap(result);
return result.messages.map((msg: any) => {
const senderId = messagePeerMarkedId({ peerId: msg.fromId });
const senderEntity = entityMap.get(senderId);
return serializeMessage(msg, senderEntity);
});
}
/**
* Action handler for `tg message replies <channel> <msg-ids>`.
*
* Reads replies/comments on channel posts using messages.GetReplies.
* Accepts comma-separated msg IDs for batch fetching in a single connection.
* Options: --limit (default 50), --offset (default 0)
*/
export async function messageRepliesAction(
this: Command,
channelInput: string,
msgIdsInput: string,
): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & {
limit: string;
offset: string;
};
let limit: number;
let offset: number;
let msgIds: number[];
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
msgIds = parseMessageIds(msgIdsInput);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, channelInput);
// Single post — original simple output
if (msgIds.length === 1) {
const result = await client.invoke(
new Api.messages.GetReplies({
peer: entity,
msgId: msgIds[0],
limit,
addOffset: offset,
}),
);
outputSuccess({
messages: serializeReplies(result),
total: (result as any).count ?? 0,
postId: msgIds[0],
});
return;
}
// Batch mode — iterate over post IDs within one connection
const posts: Array<{
postId: number;
messages: MessageItem[];
total: number;
}> = [];
const errors: BatchItemError[] = [];
for (const msgId of msgIds) {
try {
const result = await client.invoke(
new Api.messages.GetReplies({
peer: entity,
msgId,
limit,
addOffset: offset,
}),
);
posts.push({
postId: msgId,
messages: serializeReplies(result),
total: (result as any).count ?? 0,
});
} catch (err: unknown) {
errors.push(batchError(String(msgId), err));
}
}
outputBatchResult({ posts }, errors);
});
}

View file

@ -0,0 +1,362 @@
import type { Command } from 'commander';
import type { TelegramClient } from 'teleproto';
import { Api } from 'teleproto';
import bigInt from 'big-integer';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { resolveEntity, assertForum } from '../../lib/peer.js';
import {
serializeMessage,
serializeSearchResult,
bigIntToString,
markedPeerId,
messagePeerMarkedId,
} from '../../lib/serialize.js';
import { FILTER_MAP, VALID_FILTERS } from '../../lib/media-utils.js';
import { withAuth } from '../../lib/with-auth.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { validatePagination, parseTopicId, parseMessageId } from '../../lib/validate.js';
import { formatError } from '../../lib/errors.js';
import { buildEntityMap } from '../../lib/entity-map.js';
import { batchError, outputBatchResult } from '../../lib/batch-results.js';
import type { BatchItemError, GlobalOptions, PublicPostSearchResult, SearchResultItem } from '../../lib/types.js';
/**
* Action handler for `tg message search`.
*
* Searches messages by keyword within a specific chat (--chat), across multiple
* chats (comma-separated --chat), or globally (no --chat).
*
* Options: --query, --filter, --chat <chat>, --topic <topicId>, --limit (default 50), --offset (default 0)
*
* Single-chat search (--chat with one value): resolves entity, passes search param to getMessages.
* Multi-chat search (--chat with comma-separated values): resolves each, searches sequentially, merges results.
* Global search (no --chat): iterates cross-chat search and skips --offset results;
* results include marked chatId/chatTitle. Multi-chat failures include partial/errors.
*/
export async function messageSearchAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & {
query?: string;
filter?: string;
chat?: string;
topic?: string;
public?: boolean;
peer?: string;
after?: string;
limit: string;
offset: string;
};
const { quiet } = opts;
if (opts.public) {
if (opts.chat) {
outputError('--public cannot be combined with --chat', ErrorCode.INVALID_OPTIONS);
return;
}
if (opts.filter) {
outputError('--public cannot be combined with --filter', ErrorCode.INVALID_OPTIONS);
return;
}
if (opts.topic !== undefined) {
outputError('--public cannot be combined with --topic', ErrorCode.INVALID_OPTIONS);
return;
}
if (!opts.query) {
outputError(
'--public requires --query (a public-channel hashtag, with or without #)',
ErrorCode.MISSING_QUERY,
);
return;
}
} else if (opts.peer !== undefined || opts.after !== undefined) {
outputError('--peer and --after require --public', ErrorCode.INVALID_OPTIONS);
return;
}
// Validate: either --query or --filter (or both) must be provided
if (!opts.query && !opts.filter) {
outputError(
'Either --query or --filter is required. Use --filter to browse by media type.',
ErrorCode.MISSING_QUERY,
);
return;
}
// Validate filter name if provided
if (opts.filter && !FILTER_MAP[opts.filter]) {
outputError(
`Unknown filter: ${opts.filter}. Valid: ${VALID_FILTERS.join(', ')}`,
ErrorCode.INVALID_FILTER,
);
return;
}
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
let topicId: number | undefined;
if (opts.topic !== undefined) {
try {
topicId = parseTopicId(opts.topic);
} catch (err: unknown) {
outputError(
err instanceof Error ? err.message : 'Invalid topic ID: must be a number',
ErrorCode.INVALID_TOPIC_ID,
);
return;
}
}
if (topicId !== undefined && !opts.chat) {
outputError('--topic requires a single --chat', ErrorCode.INVALID_OPTIONS);
return;
}
let afterId = 0;
if (opts.after !== undefined) {
try {
afterId = parseMessageId(opts.after);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
}
await withAuth(opts, async (client) => {
if (opts.public) {
await searchPublicPosts(client, {
query: opts.query!,
limit,
offsetRate: offset,
afterId,
peer: opts.peer,
});
return;
}
const baseSearchParams: Record<string, any> = {
search: opts.query || '',
};
if (opts.filter) {
baseSearchParams.filter = FILTER_MAP[opts.filter]();
}
if (opts.chat) {
const chatIds = opts.chat.split(',').map(c => c.trim()).filter(Boolean);
if (chatIds.length === 1) {
// Single-chat search (READ-03) with optional topic scoping
const entity = await resolveEntity(client, chatIds[0]);
if (topicId !== undefined) {
await assertForum(entity, topicId);
const peer = await client.getInputEntity(entity);
const messages = [];
let total = 0;
let offsetId = 0;
while (messages.length < limit) {
const pageLimit = Math.min(100, limit - messages.length);
const result = await client.invoke(new Api.messages.Search({
peer,
q: opts.query ?? '',
filter: opts.filter ? FILTER_MAP[opts.filter]() : new Api.InputMessagesFilterEmpty(),
topMsgId: topicId,
offsetId,
addOffset: offsetId === 0 ? offset : 0,
limit: pageLimit,
minDate: 0,
maxDate: 0,
maxId: 0,
minId: 0,
hash: bigInt.zero,
}));
if (!('messages' in result)) break;
total = 'count' in result ? result.count : result.messages.length;
const nextOffsetId = result.messages.at(-1)?.id;
if (!nextOffsetId || (offsetId !== 0 && nextOffsetId >= offsetId)) break;
const entities = buildEntityMap(result);
for (const message of result.messages) {
if (offsetId !== 0 && message.id >= offsetId) continue;
const senderId = messagePeerMarkedId({ peerId: (message as any).fromId });
messages.push(serializeMessage(message as any, entities.get(senderId)));
}
if (result.messages.length < pageLimit) break;
offsetId = nextOffsetId;
}
outputSuccess({ messages: messages.slice(0, limit), total });
return;
}
const messages = await client.getMessages(entity, { ...baseSearchParams, limit, addOffset: offset });
const serialized = messages.map((msg: any) =>
serializeMessage(msg),
);
outputSuccess({
messages: serialized,
total: (messages as any).total ?? 0,
});
} else {
// Multi-chat search (READ-06)
// Topic flag not supported on multi-chat search (ambiguous which chat)
if (topicId !== undefined) {
outputError('--topic cannot be used with multi-chat search', ErrorCode.INVALID_OPTIONS);
return;
}
const allResults: SearchResultItem[] = [];
const errors: BatchItemError[] = [];
// Fetch enough results from each chat to satisfy offset + limit after merge
const perChatLimit = offset + limit;
for (const chatId of chatIds) {
try {
const entity = await resolveEntity(client, chatId);
const messages = await client.getMessages(entity, { ...baseSearchParams, addOffset: 0, limit: perChatLimit });
for (const msg of messages) {
const msgChatId = messagePeerMarkedId(msg);
const chat = (msg as any).chat || (msg as any)._chat;
let chatTitle: string;
if (chat?.firstName) {
const last = chat.lastName ? ` ${chat.lastName}` : '';
chatTitle = `${chat.firstName}${last}`;
} else {
chatTitle = chat?.title || msgChatId;
}
allResults.push(serializeSearchResult(msg as any, msgChatId, chatTitle));
}
} catch (err) {
const error = batchError(chatId, err);
errors.push(error);
logStatus(`Warning: failed to search ${chatId}: ${error.error}`, quiet);
}
}
// Sort newest first, apply offset, truncate to limit
allResults.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
const paged = allResults.slice(offset, offset + limit);
outputBatchResult({ messages: paged, total: paged.length }, errors);
}
} else {
// Global search (READ-04)
// SearchGlobal has no addOffset. Let gramjs advance its full cursor
// (offsetRate, offsetPeer, offsetId), then skip the requested result count.
const iterator = client.iterMessages(undefined, { ...baseSearchParams, limit: offset + limit });
const messages: Api.Message[] = [];
let skipped = 0;
for await (const message of iterator) {
if (skipped < offset) {
skipped++;
continue;
}
messages.push(message);
if (messages.length >= limit) break;
}
const serialized = messages.map((msg: any) => {
const chatId = messagePeerMarkedId(msg);
const chat = msg.chat || (msg as any)._chat;
let chatTitle: string;
if (chat?.firstName) {
// User entity (DM): use firstName + lastName
const last = chat.lastName ? ` ${chat.lastName}` : '';
chatTitle = `${chat.firstName}${last}`;
} else {
chatTitle = chat?.title || chatId;
}
return serializeSearchResult(msg, chatId, chatTitle);
});
outputSuccess({
messages: serialized,
total: (iterator as any).total ?? 0,
});
}
});
}
/**
* Global hashtag search over public channel posts (`channels.searchPosts`).
* The CLI preserves its hashtag-only public search contract on Teleproto.
*/
async function searchPublicPosts(
client: TelegramClient,
opts: { query: string; limit: number; offsetRate: number; afterId: number; peer?: string },
): Promise<void> {
const hashtag = opts.query.trim().replace(/^#/, '');
if (!hashtag) {
outputError('Search query cannot be empty', ErrorCode.MISSING_QUERY);
return;
}
if (/\s/.test(hashtag)) {
outputError(
'Public post search looks up hashtags in public channels (including those you have not joined). Use a single token, with or without #.',
ErrorCode.INVALID_OPTIONS,
);
return;
}
let offsetPeer: any = new Api.InputPeerEmpty();
if (opts.peer) {
const entity = await resolveEntity(client, opts.peer);
offsetPeer = await client.getInputEntity(entity);
}
const result = await client.invoke(
new Api.channels.SearchPosts({
hashtag,
offsetRate: opts.offsetRate,
offsetPeer,
offsetId: opts.afterId,
limit: opts.limit,
}),
);
const chats = ((result as any).chats ?? []) as any[];
const rawMessages = ((result as any).messages ?? []) as any[];
const messages = rawMessages.map((msg: any) => {
const chatId = messagePeerMarkedId(msg);
const chat = chats.find((c) => markedPeerId(c) === chatId)
?? chats.find((c) => bigIntToString(c.id) === bigIntToString(msg.peerId?.channelId));
const title = chat?.title || chat?.username || chatId;
return serializeSearchResult(msg, chatId, title);
});
const lastRaw = rawMessages[rawMessages.length - 1];
const last = messages[messages.length - 1];
const hasMore = messages.length > 0
&& ((result as any).nextRate != null || messages.length >= opts.limit);
const nextRate = hasMore
? ((result as any).nextRate ?? lastRaw?.date ?? null)
: null;
const floodRaw = (result as any).searchFlood;
const data: PublicPostSearchResult = {
messages,
total: (result as any).count ?? messages.length,
hasMore,
nextRate,
nextOffsetId: hasMore ? (last?.id ?? null) : null,
nextOffsetPeer: hasMore ? (last?.chatId ?? null) : null,
};
if (floodRaw) {
data.flood = {
remains: floodRaw.remains ?? null,
totalDaily: floodRaw.totalDaily ?? null,
waitTill: floodRaw.waitTill ?? null,
starsAmount: floodRaw.starsAmount != null ? String(floodRaw.starsAmount) : null,
queryIsFree: floodRaw.queryIsFree === true,
};
}
outputSuccess(data);
}

View file

@ -0,0 +1,141 @@
import type { Command } from 'commander';
import { parseSchedule } from '../../lib/schedule.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { resolveEntity, assertForum } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import type { GlobalOptions, ScheduledMessageResult } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { getDaemonContext } from '../../lib/daemon/execution-context.js';
import { parseTopicId, parseMessageId } from '../../lib/validate.js';
/**
* Read all data from stdin as a UTF-8 string.
* Used when the text argument is "-" (dash placeholder) to support piped input.
*/
async function readStdin(): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
return Buffer.concat(chunks).toString('utf-8').trimEnd();
}
/**
* Action handler for `tg message send <chat> <text>`.
*
* Sends a text message to any chat. Supports:
* - Server-side scheduled delivery via --schedule <zoned ISO timestamp>
* - Reply to a specific message via --reply-to <msgId>
* - Piped stdin input via dash placeholder: echo "msg" | tg message send <chat> -
* - gramjs built-in markdown parsing for **bold**, __italic__, `code`, [links](url)
*
* Returns the sent message as a serialized MessageItem.
*/
export async function messageSendAction(this: Command, chat: string, text: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { replyTo?: string; topic?: string; commentTo?: string; schedule?: string };
let schedule: number | undefined;
if (opts.schedule !== undefined) {
try { schedule = parseSchedule(opts.schedule); }
catch (err) {
outputError((err as Error).message, ErrorCode.INVALID_SCHEDULE);
return;
}
}
// Handle stdin pipe via dash placeholder
if (text === '-') {
const context = getDaemonContext();
if (context ? context.stdin === undefined : process.stdin.isTTY) {
outputError('"-" requires piped input. Example: echo "msg" | tg message send @user -', ErrorCode.STDIN_REQUIRED);
return;
}
text = context ? context.stdin!.trimEnd() : await readStdin();
}
// Validate non-empty text
if (!text) {
outputError('Message text is required', ErrorCode.EMPTY_MESSAGE);
return;
}
// Telegram message length limit
if (text.length > 4096) {
outputError('Message too long (max 4096 chars)', ErrorCode.MESSAGE_TOO_LONG);
return;
}
let topicId: number | undefined;
if (opts.topic !== undefined) {
try {
topicId = parseTopicId(opts.topic);
} catch (err: unknown) {
outputError(
err instanceof Error ? err.message : 'Invalid topic ID: must be a number',
ErrorCode.INVALID_TOPIC_ID,
);
return;
}
}
// Parse replyTo as integer
let replyTo: number | undefined;
try {
if (opts.replyTo !== undefined) replyTo = parseMessageId(opts.replyTo);
} catch {
outputError('Invalid reply-to message ID: must be a positive integer', ErrorCode.INVALID_REPLY_TO);
return;
}
// Parse commentTo as integer (for channel post comments)
let commentTo: number | undefined;
try {
if (opts.commentTo !== undefined) commentTo = parseMessageId(opts.commentTo);
} catch {
outputError('Invalid comment-to message ID: must be a positive integer', ErrorCode.INVALID_COMMENT_TO);
return;
}
if (topicId !== undefined && replyTo !== undefined) {
outputError(
'--topic and --reply-to cannot be combined yet. Use --reply-to to reply in-topic, or --topic to post to the topic root.',
ErrorCode.INVALID_OPTIONS,
);
return;
}
if (commentTo !== undefined && (topicId !== undefined || replyTo !== undefined)) {
outputError('--comment-to cannot be combined with --topic or --reply-to', ErrorCode.INVALID_OPTIONS);
return;
}
const effectiveReplyTo = topicId !== undefined ? topicId : replyTo;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
// Forum guard: reject --topic on non-forum chats
await assertForum(entity, topicId);
// Auth/peer resolution may have taken long enough to expire the requested time.
if (opts.schedule !== undefined) schedule = parseSchedule(opts.schedule);
// gramjs built-in MarkdownParser handles **bold**, __italic__, `code`, [links](url) automatically
const sentMsg = await client.sendMessage(entity, {
message: text,
replyTo: effectiveReplyTo,
...(commentTo !== undefined && { commentTo }),
...(schedule !== undefined && { schedule }),
});
if (!sentMsg) {
outputError('Telegram did not return the sent message result; retrying may create a duplicate.', ErrorCode.MESSAGE_RESULT_UNAVAILABLE);
return;
}
const serialized = serializeMessage(sentMsg as any);
if (schedule === undefined) outputSuccess(serialized);
else {
const scheduled: ScheduledMessageResult = { ...serialized, scheduledAt: new Date(schedule * 1000).toISOString() };
outputSuccess(scheduled);
}
});
}

View file

@ -0,0 +1,50 @@
import type { Command } from 'commander';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError, formatError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { markedPeerId } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { parseMessageId } from '../../lib/validate.js';
import type { GlobalOptions, PinResult } from '../../lib/types.js';
/**
* Action handler for `tg message unpin <chat> <msg-id>`.
*
* Unpins a specific message from a chat.
* API returns undefined (no confirmation payload), so we synthesize a PinResult.
*
* Returns PinResult with messageId, chatId, action: 'unpinned' (no silent field).
* Uses translateTelegramError for Telegram-specific permission errors.
*/
export async function messageUnpinAction(this: Command, chat: string, msgId: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
let messageId: number;
try {
messageId = parseMessageId(msgId);
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
try {
// API returns undefined — that's expected (Pitfall 2 from research)
await client.unpinMessage(entity, messageId);
// Synthesize confirmation since API gives no response payload
const result: PinResult = {
messageId,
chatId: markedPeerId(entity),
action: 'unpinned',
};
outputSuccess(result);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}

View file

@ -0,0 +1,68 @@
import type { Command } from 'commander';
import { createConfig } from '../../lib/config.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { DaemonPaths } from '../../lib/daemon/pid.js';
import { DaemonClient } from '../../lib/daemon/client.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { parseTopicId } from '../../lib/validate.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Stream new messages in a chat via the daemon. Stays up until Ctrl+C.
* Each message is written through outputSuccess (JSON envelope / --human / --toon).
*/
export async function messageWatchAction(this: Command, chatInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { topic?: string };
const { profile, quiet } = opts;
let topicId: number | undefined;
if (opts.topic !== undefined) {
try {
topicId = parseTopicId(opts.topic);
} catch (err: unknown) {
outputError(
err instanceof Error ? err.message : 'Invalid topic ID: must be a number',
ErrorCode.INVALID_TOPIC_ID,
);
return;
}
}
const config = createConfig(opts.config);
const configDir = config.path.replace(/[/\\][^/\\]+$/, '');
const paths = new DaemonPaths(configDir, profile);
if (!paths.socketExists()) {
outputError(
'message watch requires a running daemon. Start one with: tg daemon start',
ErrorCode.DAEMON_NOT_RUNNING,
);
return;
}
logStatus(`Watching ${chatInput} for new messages... (Ctrl+C to stop)`, quiet);
const client = new DaemonClient(paths.socketPath);
const stop = () => client.close();
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
try {
await client.watch(
{ chat: chatInput, topic: topicId },
(payload) => {
outputSuccess(payload);
},
);
} catch (err: unknown) {
outputError(
`Watch failed: ${(err as Error).message}`,
ErrorCode.DAEMON_CONNECTION_FAILED,
);
} finally {
process.removeListener('SIGINT', stop);
process.removeListener('SIGTERM', stop);
client.close();
}
}

View file

@ -0,0 +1,55 @@
import type { Command } from 'commander';
import { createConfig } from '../../lib/config.js';
import { SessionStore } from '../../lib/session-store.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js';
import type { GlobalOptions, ProfileData } from '../../lib/types.js';
/**
* Export action handler for `tg session export`.
*
* By default, outputs the raw session string to stdout (ideal for piping).
* When --json is explicitly passed on the CLI, outputs a JSON envelope
* with session string plus metadata (phone, created).
*
* Uses Commander's getOptionValueSource to detect explicit --json
* vs the app default (json: true by default).
*/
export async function exportAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const { profile, quiet } = opts;
if (await refuseDirectConnectIfDaemon(opts)) return;
const config = createConfig(opts.config);
const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, ''));
const sessionString = await store.load(profile);
if (!sessionString) {
outputError(`No session found for profile '${profile}'`, ErrorCode.NO_SESSION);
return;
}
// Raw string is the default (piping). Structured modes still go through outputSuccess.
const jsonSource = this.getOptionValueSourceWithGlobals('json');
const jsonExplicit = jsonSource === 'cli';
const structured =
jsonExplicit ||
opts.human === true ||
opts.json === false ||
!!opts.toon ||
!!opts.jsonl;
if (structured) {
const profileData = config.get(`profiles.${profile}`) as ProfileData | undefined;
outputSuccess({
session: sessionString,
phone: profileData?.phone,
created: profileData?.created,
});
} else {
logStatus('Exporting session...', quiet);
process.stdout.write(sessionString + '\n');
}
}

View file

@ -0,0 +1,136 @@
import type { Command } from 'commander';
import { createConfig, resolveCredentials, getCredentialsOrThrow } from '../../lib/config.js';
import { resolveTransport } from '../../lib/transport.js';
import { withClient } from '../../lib/client.js';
import { SessionStore } from '../../lib/session-store.js';
import { outputSuccess, outputError, logStatus } from '../../lib/output.js';
import { formatError } from '../../lib/errors.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js';
import type { GlobalOptions } from '../../lib/types.js';
/**
* Read all data from stdin until EOF.
* Used when session string is piped via stdin instead of passed as argument.
*/
function readStdin(): Promise<string> {
return new Promise((resolve, reject) => {
let data = '';
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (chunk: string) => {
data += chunk;
});
process.stdin.on('end', () => resolve(data));
process.stdin.on('error', reject);
});
}
/**
* Import action handler for `tg session import [session]`.
*
* Accepts a session string as a positional argument, or reads from stdin
* when piped. By default validates the session by connecting to Telegram
* and checking authorization. Use --skip-verify to skip validation.
*
* Saves the session to the SessionStore and updates the config profile
* with the session string and creation timestamp.
*/
export async function importAction(
this: Command,
sessionString: string | undefined,
): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { skipVerify?: boolean };
const { profile, quiet } = opts;
if (await refuseDirectConnectIfDaemon(opts)) return;
const skipVerify = opts.skipVerify ?? false;
let session = sessionString;
if (!session) {
// Check if stdin is piped (not a TTY)
if (process.stdin.isTTY) {
outputError(
'Provide session string as argument or pipe via stdin',
ErrorCode.NO_INPUT,
);
return;
}
logStatus('Reading session from stdin...', quiet);
session = await readStdin();
}
// Trim and validate
session = session.trim();
if (!session) {
outputError(
'Provide session string as argument or pipe via stdin',
ErrorCode.NO_INPUT,
);
return;
}
const config = createConfig(opts.config);
const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, ''));
const importedSession = session;
await store.withLock(profile, async (_previousSession, holdUntil) => {
const transport = resolveTransport(config, profile, opts.transport);
// Validate session unless --skip-verify is set
let wasVerified = false;
if (!skipVerify) {
const hasCredentials = config.get(`profiles.${profile}.client`) || resolveCredentials(config);
const creds = hasCredentials ? await getCredentialsOrThrow(config, undefined, profile) : null;
if (!creds) {
logStatus(
'Warning: Cannot verify session — API credentials not configured. Saving without verification.',
quiet,
);
} else {
try {
let authorized = false;
await withClient(
{ apiId: creds.apiId, apiHash: creds.apiHash, sessionString: importedSession, transport },
async (client) => {
authorized = await client.checkAuthorization();
},
{ holdUntil },
);
if (!authorized) {
outputError(
'Session is not authorized. The session string may be invalid or expired. Use --skip-verify to import anyway.',
ErrorCode.INVALID_SESSION,
);
return;
}
wasVerified = true;
logStatus('Session verified — authorized.', quiet);
} catch (err: unknown) {
const { message } = formatError(err);
outputError(
`Session verification failed: ${message}. Use --skip-verify to import anyway.`,
ErrorCode.VERIFY_FAILED,
);
return;
}
}
}
// Save session to file store
store.saveUnlocked(profile, importedSession);
// Update config profile with metadata
const clientName = config.get(`profiles.${profile}.client`);
config.set(`profiles.${profile}`, {
...(clientName ? { client: clientName } : {}),
transport,
created: new Date().toISOString(),
});
logStatus('Session imported successfully!', quiet);
outputSuccess({ imported: true, profile, verified: wasVerified });
});
}

View file

@ -0,0 +1,29 @@
import { Command } from 'commander';
import { exportAction } from './export.js';
import { importAction } from './import.js';
/**
* Create the `session` command group with export and import subcommands.
*
* Usage:
* tg session export - Export session string for portability
* tg session import - Import a session string (argument or stdin pipe)
*/
export function createSessionCommand(): Command {
const session = new Command('session')
.description('Session management commands');
session
.command('export')
.description('Export session string for portability')
.action(exportAction);
session
.command('import')
.argument('[session]', 'Session string to import')
.option('--skip-verify', 'Skip session validation via Telegram API')
.description('Import a session string')
.action(importAction);
return session;
}

View file

@ -0,0 +1,51 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { bigIntToString } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import type { GlobalOptions, BlockResult } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg user block <user>`.
*
* Blocks a single user. Validates that the resolved entity is a User
* (not a Channel or Chat). Idempotent: blocking an already-blocked user
* returns success silently.
*
* Returns BlockResult with userId, username, firstName, action: 'blocked'.
*/
export async function userBlockAction(this: Command, userInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, userInput);
// Validate entity is a User (not Channel/Chat)
if (!(entity instanceof Api.User)) {
outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER);
return;
}
const user = entity;
try {
await client.invoke(new Api.contacts.Block({ id: user }));
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
return;
}
const result: BlockResult = {
userId: bigIntToString(user.id),
username: user.username ?? null,
firstName: user.firstName ?? null,
action: 'blocked',
};
outputSuccess(result);
});
}

View file

@ -0,0 +1,69 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError, formatError } from '../../lib/errors.js';
import { validatePagination } from '../../lib/validate.js';
import { bigIntToString } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import type { GlobalOptions, BlockedListItem, BlockedListResult } from '../../lib/types.js';
/**
* Action handler for `tg user blocked`.
*
* Lists blocked users with pagination support.
* Handles both contacts.Blocked (full list, no .count) and
* contacts.BlockedSlice (paginated, has .count) response types.
*
* Returns BlockedListResult { users: BlockedListItem[], total: number }.
*/
export async function userBlockedAction(this: Command): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { limit?: string; offset?: string };
let limit: number;
let offset: number;
try {
({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset }));
} catch (err: unknown) {
const { message, code } = formatError(err);
outputError(message, code);
return;
}
await withAuth(opts, async (client) => {
let result: any;
try {
result = await client.invoke(
new Api.contacts.GetBlocked({ offset, limit }),
);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
return;
}
const total: number = (result as any).count ?? (result as any).blocked?.length ?? 0;
// Build userMap from result.users keyed by stringified user ID
const userMap = new Map<string, any>();
for (const user of (result as any).users ?? []) {
userMap.set(bigIntToString(user.id), user);
}
// Map blocked entries to BlockedListItem
const users: BlockedListItem[] = [];
for (const entry of (result as any).blocked ?? []) {
const userId = bigIntToString(entry.peerId.userId);
const user = userMap.get(userId);
users.push({
id: userId,
firstName: user?.firstName ?? null,
lastName: user?.lastName ?? null,
username: user?.username ?? null,
isBot: !!user?.bot,
});
}
const output: BlockedListResult = { users, total };
outputSuccess(output);
});
}

View file

@ -0,0 +1,50 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { existsSync, writeFileSync } from 'node:fs';
import { resolve, isAbsolute } from 'node:path';
import { withAuth } from '../../lib/with-auth.js';
import { resolveEntity } from '../../lib/peer.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { bigIntToString } from '../../lib/serialize.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { getDaemonContext } from '../../lib/daemon/execution-context.js';
import type { GlobalOptions, UserPhotoDownloadResult } from '../../lib/types.js';
/** Download the current visible profile photo; preserve existing files unless --force. */
export async function userDownloadPhotoAction(this: Command, user: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & { output: string; force?: boolean };
const context = getDaemonContext();
if (context && (!context.cwd || !isAbsolute(context.cwd))) {
outputError('Profile photo commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS);
return;
}
const target = resolve(context?.cwd ?? process.cwd(), opts.output);
if (existsSync(target) && !opts.force) {
outputError('Output file exists (use --force to overwrite)', ErrorCode.FILE_EXISTS);
return;
}
await withAuth(opts, async client => {
const entity = await resolveEntity(client, user);
if (!(entity instanceof Api.User)) {
outputError('Profile photo download requires a user', ErrorCode.NOT_A_USER);
return;
}
const buffer = await client.downloadProfilePhoto(entity, { isBig: true });
if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
outputError('No visible profile photo available', ErrorCode.NO_PROFILE_PHOTO);
return;
}
try {
// wx also closes the race between the initial existence check and download.
writeFileSync(target, buffer, { flag: opts.force ? 'w' : 'wx', mode: 0o600 });
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
outputError('Output file exists (use --force to overwrite)', ErrorCode.FILE_EXISTS);
return;
}
throw err;
}
const data: UserPhotoDownloadResult = { userId: bigIntToString(entity.id)!, path: target, size: buffer.length, profilePhoto: true };
outputSuccess(data);
});
}

View file

@ -0,0 +1,50 @@
import { Command } from 'commander';
import { userDownloadPhotoAction } from './download-photo.js';
import { userProfileAction } from './profile.js';
import { userBlockAction } from './block.js';
import { userUnblockAction } from './unblock.js';
import { userBlockedAction } from './blocked.js';
/**
* Create the `user` command group with profile, block, unblock, blocked subcommands.
*
* Usage:
* tg user profile <users> - Get detailed user profile(s) (comma-separated)
* tg user block <user> - Block a user
* tg user unblock <user> - Unblock a user
* tg user blocked - List blocked users (--limit, --offset)
*/
export function createUserCommand(): Command {
const user = new Command('user')
.description('User profiles and block management');
user.command('profile')
.argument('<users>', 'User ID(s) or username(s), comma-separated')
.description('Get detailed user profile(s)')
.action(userProfileAction);
user.command('block')
.argument('<user>', 'User ID or username')
.description('Block a user')
.action(userBlockAction);
user.command('unblock')
.argument('<user>', 'User ID or username')
.description('Unblock a user')
.action(userUnblockAction);
user.command('blocked')
.description('List blocked users')
.option('--limit <n>', 'Max results', '50')
.option('--offset <n>', 'Skip results', '0')
.action(userBlockedAction);
user.command('download-photo')
.argument('<user>', 'User ID or username')
.requiredOption('-o, --output <file>', 'Destination file')
.option('--force', 'Overwrite an existing file')
.description('Download the current visible user profile photo')
.action(userDownloadPhotoAction);
return user;
}

View file

@ -0,0 +1,80 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputError } from '../../lib/output.js';
import { resolveEntity } from '../../lib/peer.js';
import { bigIntToString } from '../../lib/serialize.js';
import { buildUserProfile } from '../../lib/user-profile.js';
import { withAuth } from '../../lib/with-auth.js';
import type { BatchItemError, GlobalOptions, UserProfile } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
import { batchError, outputBatchResult } from '../../lib/batch-results.js';
/**
* Action handler for `tg user profile <users>`.
*
* Fetches detailed user profiles. Accepts comma-separated usernames/IDs.
* Returns profiles, genuinely missing inputs, and per-input errors. Any failed
* input sets partial:true and a nonzero exit status without dropping successes.
*
* - Privacy-restricted phone shows '[restricted]' for non-bot users
* - Bots include botInlinePlaceholder and supportsInline fields
* - All 6 UserStatus types mapped to lastSeen strings
* - Bots always have lastSeen: null
*/
export async function userProfileAction(this: Command, usersInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
const inputs = usersInput.split(',').map(s => s.trim()).filter(Boolean);
if (inputs.length === 0) {
outputError('No users specified', ErrorCode.INVALID_INPUT);
return;
}
if (inputs.length > 50) {
outputError('Too many users (max 50)', ErrorCode.TOO_MANY_USERS);
return;
}
await withAuth(opts, async (client) => {
const profiles: UserProfile[] = [];
const notFound: string[] = [];
const errors: BatchItemError[] = [];
for (const input of inputs) {
try {
const entity = await resolveEntity(client, input);
// Validate entity is a User (not Channel/Chat)
if (!(entity instanceof Api.User)) {
notFound.push(input);
errors.push({ input, error: 'Peer is not a user', code: ErrorCode.NO_USERS_FOUND });
continue;
}
const user = entity;
// Fetch full user details
const result = await client.invoke(
new Api.users.GetFullUser({ id: user }),
);
const fullUser = result.fullUser;
const userFromResult = (result.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(user.id)) ?? user) as Api.User;
const profileData = await buildUserProfile(client, user, fullUser, userFromResult, err => {
errors.push(batchError(input, err, 'Could not fetch profile photos'));
});
profiles.push(profileData);
} catch (err: unknown) {
const error = batchError(input, err);
errors.push(error);
if ([ErrorCode.PEER_NOT_FOUND, 'USERNAME_NOT_OCCUPIED', 'USER_ID_INVALID'].includes(error.code)) {
notFound.push(input);
}
}
}
outputBatchResult({ profiles, notFound }, errors);
});
}

View file

@ -0,0 +1,51 @@
import type { Command } from 'commander';
import { Api } from 'teleproto';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { bigIntToString } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import type { GlobalOptions, BlockResult } from '../../lib/types.js';
import { ErrorCode } from '../../lib/error-codes.js';
/**
* Action handler for `tg user unblock <user>`.
*
* Unblocks a single user. Validates that the resolved entity is a User
* (not a Channel or Chat). Idempotent: unblocking an already-unblocked user
* returns success silently.
*
* Returns BlockResult with userId, username, firstName, action: 'unblocked'.
*/
export async function userUnblockAction(this: Command, userInput: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions;
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, userInput);
// Validate entity is a User (not Channel/Chat)
if (!(entity instanceof Api.User)) {
outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER);
return;
}
const user = entity;
try {
await client.invoke(new Api.contacts.Unblock({ id: user }));
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
return;
}
const result: BlockResult = {
userId: bigIntToString(user.id),
username: user.username ?? null,
firstName: user.firstName ?? null,
action: 'unblocked',
};
outputSuccess(result);
});
}

29
cli/src/index.ts Normal file
View file

@ -0,0 +1,29 @@
/**
* Public API for programmatic use of @miolamio/tg-cli.
*
* import { withAuth, resolveEntity, ErrorCode } from '@miolamio/tg-cli';
*/
export { outputSuccess, outputError, logStatus } from './lib/output.js';
export { createConfig, resolveCredentials, getCredentialsOrThrow } from './lib/config.js';
export { SessionStore } from './lib/session-store.js';
export { withClient } from './lib/client.js';
export { withAuth } from './lib/with-auth.js';
export type { WithAuthOptions } from './lib/with-auth.js';
export { resolveEntity } from './lib/peer.js';
export { ErrorCode } from './lib/error-codes.js';
export { TgError, CredentialError, SessionError, FloodWaitError } from './lib/errors.js';
export { DaemonClient, DaemonRpcError } from './lib/daemon/client.js';
export { DaemonPaths } from './lib/daemon/pid.js';
export { DAEMON_COMMANDS } from './lib/daemon/command-protocol.js';
export type { DaemonCommandOptions, DaemonCommandRequest, DaemonExecutionResult } from './lib/daemon/command-protocol.js';
export type {
GlobalOptions,
Transport,
TgConfig,
ProfileData,
OutputEnvelope,
SuccessEnvelope,
ErrorEnvelope,
} from './lib/types.js';

View file

@ -0,0 +1,18 @@
import { translateTelegramError } from './errors.js';
import { outputSuccess } from './output.js';
import type { BatchItemError } from './types.js';
import { markExitFailure } from './daemon/execution-context.js';
/** Preserve the failed input and the original Telegram or application error code. */
export function batchError(input: string, err: unknown, operation?: string): BatchItemError {
const { message, code } = translateTelegramError(err);
const transportCode = err != null && typeof err === 'object' && 'code' in err && typeof err.code === 'string'
? err.code : undefined;
return { input, error: operation ? `${operation}: ${message}` : message, code: code === 'UNKNOWN_ERROR' ? (transportCode ?? code) : code };
}
/** Emit one batch result, retaining successes and making failures visible to scripts. */
export function outputBatchResult<T extends object>(data: T, errors: BatchItemError[]): void {
if (errors.length > 0) markExitFailure();
outputSuccess({ ...data, partial: errors.length > 0, errors });
}

31
cli/src/lib/branding.ts Normal file
View file

@ -0,0 +1,31 @@
import pc from 'picocolors';
/** Printable ASCII mascot, shared by interactive login and the README. */
const LITTLE_DAEMON = String.raw` .------.
/ o o \
| \__/ |
| |
| /\ /\ |
\/ \/ \/`;
const TAGLINE = 'Telegram, from your terminal.';
function colors() {
return pc.createColors(pc.isColorSupported
&& process.env.NO_COLOR === undefined && process.env.FORCE_COLOR !== '0');
}
/** Main help runs before preAction, so it must use the parsed quiet flag. */
export function formatHelpBanner(quiet = false): string {
if (quiet || !process.stdout.isTTY || process.env.TERM === 'dumb') return '';
const color = colors();
return `${color.cyan('(. .)')} ${color.bold('tg')} / ${TAGLINE}\n`;
}
/** Keep authentication data on stdout and omit decoration when any stream is redirected. */
export function showLoginBanner(quiet = false): void {
if (quiet || !process.stdin.isTTY || !process.stdout.isTTY || !process.stderr.isTTY
|| process.env.TERM === 'dumb') return;
const color = colors();
process.stderr.write(`\n${color.cyan(LITTLE_DAEMON)}\n\n${color.bold('tg')} / ${TAGLINE}\n\n`);
}

View file

@ -0,0 +1,26 @@
import { isQuietMode, isVerboseMode } from './cli-mode.js';
/**
* Keep dependency console dumps out of CLI data and avoid exposing SDK objects.
* Only executable entry points install this guard; library imports leave the
* embedding application's console unchanged. Use the returned function in tests.
*/
export function installCliConsoleGuard(): () => void {
const methods = ['log', 'info', 'debug', 'warn', 'error', 'dir', 'dirxml', 'table', 'trace', 'assert', 'count', 'countReset', 'time', 'timeLog', 'timeEnd', 'group', 'groupCollapsed', 'groupEnd', 'clear'] as const;
const target = console as unknown as Record<string, (...args: unknown[]) => void>;
const originals = methods.map(method => [method, target[method]] as const);
for (const method of methods) {
const diagnostic = (...args: unknown[]) => {
if (method === 'assert' && args[0]) return;
if (isQuietMode()) return;
if (!isVerboseMode() && !['warn', 'error', 'trace', 'assert'].includes(method)) return;
// gramjs has console.log(message) error branches outside its logger. Such
// objects can contain client/session data, so never format their arguments.
process.stderr.write(`[diagnostic] Dependency console.${method} output omitted.\n`);
};
target[method] = diagnostic;
}
return () => {
for (const [method, original] of originals) target[method] = original;
};
}

21
cli/src/lib/cli-mode.ts Normal file
View file

@ -0,0 +1,21 @@
/** Global --quiet / --verbose flags set from the preAction hook. */
import { getDaemonContext } from './daemon/execution-context.js';
let _quietMode = false;
let _verboseMode = false;
export function setQuietMode(enabled: boolean): void {
_quietMode = enabled;
}
export function setVerboseMode(enabled: boolean): void {
_verboseMode = enabled;
}
export function isQuietMode(): boolean {
return getDaemonContext() ? true : _quietMode;
}
export function isVerboseMode(): boolean {
return getDaemonContext() ? false : _verboseMode;
}

205
cli/src/lib/client.ts Normal file
View file

@ -0,0 +1,205 @@
import { TelegramClient, sessions } from 'teleproto';
import { TgError } from './errors.js';
import { ErrorCode } from './error-codes.js';
import { createGramjsLogger } from './gramjs-logger.js';
import { installClientErrorDiagnostics } from './transport-diagnostics.js';
import { connectionOptions } from './connection-options.js';
import type { Transport } from './types.js';
import { connectOrThrow } from './connect.js';
const { StringSession } = sessions;
/**
* Options for creating and connecting a TelegramClient.
*/
export interface ClientOptions {
apiId: number;
apiHash: string;
sessionString: string;
transport?: Transport;
}
/**
* Options for withClient behavior.
*/
export interface WithClientOptions {
/** Timeout in milliseconds. Defaults to 120_000 (2 minutes). */
timeout?: number;
/** Additional attempts after a retryable failure. Default 0 (one attempt). */
retries?: number;
/** Base delay in ms between retries (doubles each attempt). Default 1000. */
retryDelay?: number;
/** Keep session ownership until all started work and teardown have finished. */
holdUntil?: (cleanup: Promise<unknown>) => void;
}
/**
* Determine if an error is retryable (network/transient errors only).
* TgError and its subclasses are never retryable (they represent app-level errors).
* Telegram RPCErrors are not retryable (they represent API rejection).
*/
function isRetryable(err: unknown): boolean {
if (err instanceof TgError) return false;
if (err instanceof Error) {
const code = (err as any).code;
if (typeof code === 'string' && ['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN'].includes(code)) {
return true;
}
}
return false;
}
/** A retry wait owns its timer and removes it as soon as the deadline fires. */
function waitForRetry(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
signal.throwIfAborted();
const timer = setTimeout(() => {
signal.removeEventListener('abort', abort);
resolve();
}, ms);
const abort = () => {
clearTimeout(timer);
signal.removeEventListener('abort', abort);
reject(signal.reason);
};
signal.addEventListener('abort', abort, { once: true });
});
}
/**
* Execute a function with a connected TelegramClient, ensuring proper cleanup.
*
* - Creates the client with the given session string
* - Sets a configurable safety timeout (default 120s) that rejects with a structured TgError
* - Connects, runs the callback, and destroys the client in a finally block
* - Uses destroy() (not disconnect()) to avoid zombie _updateLoop
* - Aborts the callback signal at the deadline and cancels pending retries.
* An already running callback must observe the signal before further work;
* JavaScript cannot forcibly cancel an arbitrary promise or undo an RPC.
* A late completion is destroyed again. When holdUntil is supplied, session
* ownership remains held until that cleanup succeeds, even after TIMEOUT.
*
* @param opts - Client connection options
* @param fn - Async function to execute with the connected client
* @param options - Optional behavior config (timeout)
* @returns The result of the callback function
*/
export async function withClient<T>(
opts: ClientOptions,
fn: (client: TelegramClient, signal: AbortSignal) => Promise<T>,
options?: WithClientOptions,
): Promise<T> {
const timeoutMs = options?.timeout ?? 120_000;
const timeoutSeconds = Math.round(timeoutMs / 1000);
const retries = options?.retries ?? 0;
const baseDelay = options?.retryDelay ?? 1000;
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647
|| !Number.isSafeInteger(retries) || retries < 0
|| !Number.isFinite(baseDelay) || baseDelay < 0 || baseDelay > 2_147_483_647) {
throw new TgError('Invalid client timeout or retry options', ErrorCode.INVALID_OPTIONS);
}
const session = new StringSession(opts.sessionString);
const logger = createGramjsLogger([opts.apiHash, opts.sessionString]);
const client = new TelegramClient(session, opts.apiId, opts.apiHash, {
connectionRetries: 3,
requestRetries: 1,
catchUp: true,
retryDelay: 1000,
floodSleepThreshold: 60,
baseLogger: logger,
...connectionOptions(opts.transport),
});
installClientErrorDiagnostics(client, logger);
const cancellation = new AbortController();
let timeoutId: ReturnType<typeof setTimeout>;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
const error = new TgError(`Client operation timed out after ${timeoutSeconds} seconds`, ErrorCode.TIMEOUT);
cancellation.abort(error);
reject(error);
}, timeoutMs);
});
// Prevent unhandled rejection if timeout fires during microtask gap
// (Promise.race handles this, but detection can race in some runtimes)
timeoutPromise.catch(() => {});
// Defer execution to a microtask so the ownership hook is registered before
// connect or user work starts. Operation failure does not mean cleanup failed.
const operation = Promise.resolve().then(async () => {
await connectOrThrow(client);
for (let attempt = 0; ; attempt++) {
cancellation.signal.throwIfAborted();
try {
const result = await fn(client, cancellation.signal);
cancellation.signal.throwIfAborted();
return result;
} catch (err) {
cancellation.signal.throwIfAborted();
if (!isRetryable(err) || attempt >= retries) throw err;
const backoff = Math.min(baseDelay * Math.pow(2, attempt), 2_147_483_647);
await waitForRetry(backoff, cancellation.signal);
}
}
});
type TeardownResult = { ok: true } | { ok: false; error: unknown };
let finishTeardown!: (result: TeardownResult) => void;
const teardown = new Promise<TeardownResult>(resolve => { finishTeardown = resolve; });
const cleanup = Promise.all([operation.then(() => {}, () => {}), teardown]).then(async ([, result]) => {
// An SDK connect or callback can outlive the immediate timeout teardown.
// Final destruction runs after every started operation has settled.
if (cancellation.signal.aborted) await client.destroy();
if (!result.ok) throw result.error;
});
// Consumers without an ownership hook still get late cleanup, without an
// unhandled rejection. A lock owner receives the original success/failure.
cleanup.catch(() => {});
options?.holdUntil?.(cleanup);
try {
return await Promise.race([operation, timeoutPromise]);
} finally {
clearTimeout(timeoutId!);
// Use destroy() NOT disconnect() -- avoids zombie _updateLoop
try {
await client.destroy();
finishTeardown({ ok: true });
} catch (error) {
finishTeardown({ ok: false, error });
}
}
}
/**
* Create a TelegramClient for interactive auth flow (login).
*
* Returns an unconnected client with an empty StringSession.
* The caller manages the lifecycle: call client.start() for auth,
* then client.destroy() when done.
*
* @param apiId - Telegram API ID
* @param apiHash - Telegram API hash
* @returns Unconnected TelegramClient instance
*/
export async function createClientForAuth(
apiId: number,
apiHash: string,
transport: Transport = 'tcp',
): Promise<TelegramClient> {
const session = new StringSession('');
const logger = createGramjsLogger([apiHash]);
const client = new TelegramClient(session, apiId, apiHash, {
connectionRetries: 3,
catchUp: true,
retryDelay: 1000,
floodSleepThreshold: 60,
baseLogger: logger,
...connectionOptions(transport),
});
installClientErrorDiagnostics(client, logger);
return client;
}

113
cli/src/lib/config.ts Normal file
View file

@ -0,0 +1,113 @@
import Conf from 'conf';
import { dirname, basename, extname } from 'node:path';
import type { TgConfig } from './types.js';
import { CredentialError, TgError } from './errors.js';
import { ErrorCode } from './error-codes.js';
/** Telegram API IDs are positive TL int values; reject partial numeric strings. */
function parseApiId(value: unknown, source: string): number {
const parsed = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value;
if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed <= 0 || parsed > 2_147_483_647) {
throw new CredentialError(`${source} must be a positive integer within Telegram's 32-bit range`);
}
return parsed;
}
/**
* Create a Conf instance for tg-cli configuration.
* Default path: ~/.config/tg-cli/config.json (XDG via projectName).
* When configPath is provided (--config flag), uses that exact file path.
*
* @param configPath - Optional custom config file path from --config flag
*/
export function createConfig(configPath?: string): Conf<TgConfig> {
try {
if (configPath) {
return new Conf<TgConfig>({
projectName: 'tg-cli',
configName: basename(configPath, extname(configPath)),
cwd: dirname(configPath),
defaults: {
profiles: {},
},
});
}
return new Conf<TgConfig>({
projectName: 'telegram-cli',
configName: 'config',
defaults: {
profiles: {},
},
});
} catch {
// Do not expose malformed JSON contents: config files contain credentials.
throw new TgError('Cannot read configuration. Check that the config file is accessible and contains valid JSON.', ErrorCode.CONFIG_ERROR);
}
}
/**
* Resolve API credentials from environment variables or config file.
* Priority: env vars (TG_API_ID, TG_API_HASH) > config file values.
*
* @returns Credentials object or null if neither source has them.
*/
export function resolveCredentials(
config: Conf<TgConfig>,
): { apiId: number; apiHash: string } | null {
const envApiId = process.env.TG_API_ID;
const envApiHash = process.env.TG_API_HASH;
const rawApiId = envApiId || config.get('apiId');
const apiId = rawApiId == null ? undefined : parseApiId(rawApiId, envApiId ? 'TG_API_ID' : 'Config apiId');
const apiHash = envApiHash ?? config.get('apiHash');
if (apiHash != null && typeof apiHash !== 'string') {
throw new CredentialError('API hash must be a string');
}
if (apiId && apiHash) {
return { apiId, apiHash };
}
return null;
}
/**
* Resolve API credentials or throw a helpful error.
* Provides a clear message with link to https://my.telegram.org/apps.
*
* When clientName is provided, fetches credentials from opentele presets
* (runtime fetch, no keys stored in source). Env vars still take priority.
* Otherwise, a selected profile's saved client preset precedes global config
* credentials. Older profiles without a client name retain config fallback.
*/
export async function getCredentialsOrThrow(
config: Conf<TgConfig>,
clientName?: string,
profile?: string,
): Promise<{ apiId: number; apiHash: string }> {
// Env vars always take priority
const envApiId = process.env.TG_API_ID;
const envApiHash = process.env.TG_API_HASH;
if (envApiId && envApiHash) {
const apiId = parseApiId(envApiId, 'TG_API_ID');
return { apiId, apiHash: envApiHash };
}
// Client preset (fetched at runtime from opentele)
const presetName = clientName ?? (profile ? config.get(`profiles.${profile}.client`) as string | undefined : undefined);
if (presetName) {
const { getPreset } = await import('./presets.js');
return getPreset(config, presetName);
}
// Config file values
const creds = resolveCredentials(config);
if (!creds) {
throw new CredentialError(
'API credentials required. Get them at https://my.telegram.org/apps\n' +
'Set TG_API_ID and TG_API_HASH environment variables, or put apiId/apiHash in the config file.\n' +
'Or use a preset: tg auth login --client desktop',
);
}
return creds;
}

14
cli/src/lib/connect.ts Normal file
View file

@ -0,0 +1,14 @@
import type { TelegramClient } from 'teleproto';
import { TgError } from './errors.js';
import { ErrorCode } from './error-codes.js';
/** gramjs returns false after failed retries as well as for an existing connection. */
export async function connectOrThrow(client: TelegramClient): Promise<void> {
const connected = await client.connect();
if (connected === false && !client.connected) {
throw new TgError(
'Could not establish a Telegram connection after retries. Check the transport diagnostics on stderr; use --verbose for connection stages.',
ErrorCode.CONNECTION_FAILED,
);
}
}

View file

@ -0,0 +1,11 @@
import type { Transport } from './types.js';
import { validateTransport } from './transport.js';
import { DiagnosticTCPFull } from './transport-diagnostics.js';
import { DiagnosticWSS, WssSocket } from './wss.js';
/** Shared transport selection for auth, direct commands and the daemon. */
export function connectionOptions(transport: Transport = 'tcp') {
return validateTransport(transport) === 'wss'
? { connection: DiagnosticWSS, networkSocket: WssSocket, useWSS: true }
: { connection: DiagnosticTCPFull, useWSS: false };
}

View file

@ -0,0 +1,139 @@
import { createConnection, type Socket } from 'node:net';
import { encodeRequest, parseMessage } from './protocol.js';
import { JsonLineDecoder } from './frames.js';
import { isDaemonExecutionResult, validateDaemonCommand, type DaemonCommandOptions, type DaemonExecutionResult } from './command-protocol.js';
/** Preserve the daemon's JSON-RPC code and structured error details. */
export class DaemonRpcError extends Error {
constructor(readonly code: number, message: string, readonly data?: unknown) {
super(message);
this.name = 'DaemonRpcError';
}
}
/** JSON-RPC client. Each call or subscription owns a separate Unix socket. */
export class DaemonClient {
private nextId = 1;
private readonly pending = new Set<() => void>();
constructor(private readonly socketPath: string) {}
/** Execute a known CLI operation on the daemon's existing MTProto connection. */
async execute(argv: string[], opts?: DaemonCommandOptions): Promise<DaemonExecutionResult> {
const request = validateDaemonCommand({ argv, ...opts });
// The server owns the operation deadline; leave a small response grace period.
const result = await this.call('execute', { ...request }, { timeoutMs: (request.timeoutMs ?? 120_000) + 5_000 });
if (!isDaemonExecutionResult(result)) throw new Error('Invalid daemon execute response');
return result;
}
/** Send a request with one deadline covering both connection and response. */
async call(
method: string,
params: Record<string, unknown>,
opts?: { timeoutMs?: number },
): Promise<unknown> {
return this.exchange(method, params, opts?.timeoutMs ?? 30_000);
}
/**
* Deliver notifications after the subscribe ack. Unexpected EOF/error rejects;
* close() is intentional cancellation and resolves the subscription cleanly.
* The deadline covers connection and ack, not the lifetime of the stream.
*/
async watch(
params: Record<string, unknown>,
onMessage: (payload: Record<string, unknown>) => void,
opts?: { timeoutMs?: number },
): Promise<void> {
await this.exchange('subscribe', params, opts?.timeoutMs ?? 30_000, onMessage);
}
private exchange(
method: string,
params: Record<string, unknown>,
timeoutMs: number,
onMessage?: (payload: Record<string, unknown>) => void,
): Promise<unknown> {
if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {
return Promise.reject(new Error('Invalid daemon timeout'));
}
const id = this.nextId++;
return new Promise((resolve, reject) => {
let socket: Socket | undefined;
let settled = false;
let connected = false;
let acked = false;
const decoder = new JsonLineDecoder();
const finish = (err?: unknown, result?: unknown) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
this.pending.delete(cancel);
// Keep the error handler until close: already queued socket errors must
// remain contained even when a response or cancellation wins the race.
socket?.destroy();
if (err !== undefined) reject(err);
else resolve(result);
};
const cancel = () => finish(onMessage ? undefined : new Error('Daemon request cancelled'));
const timeout = setTimeout(() => {
const label = timeoutMs % 1000 === 0 ? `${timeoutMs / 1000}s` : `${timeoutMs}ms`;
finish(new Error(`Daemon ${onMessage ? 'subscribe' : 'request'} timed out (${label})`));
}, timeoutMs);
this.pending.add(cancel);
try {
socket = createConnection(this.socketPath);
socket.on('error', (err) => finish(connected ? err : new Error(
`Cannot connect to daemon at ${this.socketPath}: ${err.message}`,
)));
const disconnected = () => finish(new Error(onMessage
? acked ? 'Daemon disconnected while watching' : 'Daemon closed before subscribe ack'
: 'Daemon closed before response'));
socket.on('end', disconnected);
socket.on('close', disconnected);
socket.on('connect', () => {
if (settled) return;
connected = true;
socket!.write(encodeRequest(method, params, id) + '\n');
});
socket.on('data', (chunk: Buffer) => {
if (settled) return;
try {
decoder.push(chunk, (line) => {
if (settled) return;
const msg = parseMessage(line);
if (msg.type === 'response' || msg.type === 'error') {
// Ignore unrelated responses; they cannot satisfy this request
// or disable its deadline, including unrelated RPC errors.
if (msg.id !== id) return;
if (msg.type === 'error') {
finish(new DaemonRpcError(msg.error.code, msg.error.message, msg.error.data));
} else if (onMessage) {
acked = true;
clearTimeout(timeout);
} else {
finish(undefined, msg.result);
}
} else if (msg.type === 'notification') {
if (acked && onMessage && msg.method === 'message') onMessage(msg.params);
} else {
finish(new Error('Unexpected request from daemon'));
}
});
} catch (err) {
finish(err);
}
});
} catch (err) {
finish(err);
}
});
}
/** Cancel all active requests/subscriptions and release their sockets. */
close(): void {
for (const cancel of [...this.pending]) cancel();
}
}

View file

@ -0,0 +1,83 @@
import type { OutputEnvelope } from '../types.js';
import { TgError } from '../errors.js';
import { ErrorCode } from '../error-codes.js';
import { MAX_FRAME_BYTES } from './frames.js';
import { isAbsolute } from 'node:path';
/** Named CLI operations exposed by execute; lifecycle/auth remain separate. */
export const DAEMON_COMMANDS: Readonly<Record<string, readonly string[]>> = Object.freeze({
bridge: Object.freeze(['call']),
chat: Object.freeze(['list', 'info', 'join', 'leave', 'resolve', 'invite-info', 'members', 'topics', 'search', 'create', 'edit', 'kick']),
message: Object.freeze(['history', 'search', 'get', 'pinned', 'send', 'forward', 'react', 'replies', 'edit', 'delete', 'pin', 'unpin', 'poll']),
media: Object.freeze(['download', 'send']),
user: Object.freeze(['profile', 'block', 'unblock', 'blocked', 'download-photo']),
contact: Object.freeze(['list', 'add', 'delete', 'search', 'set-photo']),
});
export interface DaemonCommandOptions {
/** Explicit stdin for commands accepting a dash as message text. */
stdin?: string;
/** Absolute caller working directory; required for media operations. */
cwd?: string;
/** Server deadline, 1–120000 ms. A timed-out send may already have happened. */
timeoutMs?: number;
}
export interface DaemonCommandRequest extends DaemonCommandOptions {
/** Command group, action and CLI arguments, without global output/auth flags. */
argv: string[];
}
export interface DaemonExecutionResult {
/** The usual CLI envelope, before fields/JSONL/TOON/human rendering. */
output: OutputEnvelope<unknown>;
/** Includes partial failures that still have a success envelope. */
exitCode: number;
}
export function isDaemonCommand(path: readonly string[]): boolean {
return path.length === 2 && Object.hasOwn(DAEMON_COMMANDS, path[0])
&& DAEMON_COMMANDS[path[0]].includes(path[1]);
}
/** Bound and validate the new API without interpreting any shell text. */
export function validateDaemonCommand(params: Record<string, unknown>): DaemonCommandRequest {
const invalid = (message: string): never => { throw new TgError(message, ErrorCode.INVALID_OPTIONS); };
if (!params || typeof params !== 'object' || Array.isArray(params)) invalid('execute params must be an object');
if (Object.keys(params).some(key => !['argv', 'stdin', 'cwd', 'timeoutMs'].includes(key))) {
invalid('execute accepts only argv, stdin, cwd and timeoutMs');
}
if (!Array.isArray(params.argv) || params.argv.length < 2 || params.argv.length > 1024
|| params.argv.some(arg => typeof arg !== 'string' || arg.includes('\0'))) {
invalid('execute argv must contain 2–1024 strings without NUL characters');
}
const argv = params.argv as string[];
if (!isDaemonCommand(argv.slice(0, 2))) {
throw new TgError('This command cannot run through execute; auth/session/lifecycle and watch use their own commands', ErrorCode.DAEMON_PROXY_UNAVAILABLE);
}
if (params.stdin !== undefined && typeof params.stdin !== 'string') invalid('execute stdin must be a string');
if (params.cwd !== undefined && (typeof params.cwd !== 'string' || !isAbsolute(params.cwd) || params.cwd.includes('\0'))) {
invalid('execute cwd must be an absolute path');
}
if (argv[0] === 'media' && params.cwd === undefined) invalid('Media commands require an absolute cwd');
const photoCommand = (argv[0] === 'user' && argv[1] === 'download-photo')
|| (argv[0] === 'contact' && argv[1] === 'set-photo');
if (photoCommand && params.cwd === undefined) invalid('Photo commands require an absolute cwd');
if (params.timeoutMs !== undefined && (!Number.isInteger(params.timeoutMs) || (params.timeoutMs as number) < 1 || (params.timeoutMs as number) > 120_000)) {
invalid('execute timeoutMs must be an integer from 1 to 120000');
}
// Leave room for the JSON-RPC envelope and request ID.
if (Buffer.byteLength(JSON.stringify(params), 'utf8') > MAX_FRAME_BYTES - 256) invalid('execute request exceeds the 1 MiB frame limit');
return { argv: [...argv], ...(params.stdin !== undefined && { stdin: params.stdin as string }),
...(params.cwd !== undefined && { cwd: params.cwd as string }),
...(params.timeoutMs !== undefined && { timeoutMs: params.timeoutMs as number }) };
}
export function isDaemonExecutionResult(value: unknown): value is DaemonExecutionResult {
if (!value || typeof value !== 'object') return false;
const result = value as DaemonExecutionResult;
if (![0, 1].includes(result.exitCode) || !result.output || typeof result.output !== 'object') return false;
return result.output.ok === true ? Object.hasOwn(result.output, 'data')
: result.output.ok === false && typeof result.output.error === 'string'
&& (result.output.code === undefined || typeof result.output.code === 'string');
}

View file

@ -0,0 +1,44 @@
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* Resolve the compiled daemon entry for `fork()`.
*
* After tsup, command code lives in `dist/bin/tg.js` (or a dist/ chunk).
* The entry file is always `dist/lib/daemon/entry.js`. A path computed
* as if we were still under `src/commands/daemon/` misses that file.
*
* Tries `import.meta.url` of the caller and `process.argv[1]` (the
* running binary) against a few relative layouts; first existing path wins.
*/
export function resolveDaemonEntry(moduleUrl: string = import.meta.url): string {
const bases: string[] = [];
try {
bases.push(dirname(fileURLToPath(moduleUrl)));
} catch {
// moduleUrl is not a file URL
}
if (process.argv[1]) {
bases.push(dirname(process.argv[1]));
}
const relatives = [
join('..', 'lib', 'daemon', 'entry.js'), // dist/bin/tg.js
join('lib', 'daemon', 'entry.js'), // dist/chunk.js
join('..', '..', 'lib', 'daemon', 'entry.js'), // src/commands/daemon (built colocated)
];
const candidates: string[] = [];
for (const base of bases) {
for (const rel of relatives) {
candidates.push(join(base, rel));
}
}
for (const p of candidates) {
if (existsSync(p)) return p;
}
return candidates[0] ?? join('lib', 'daemon', 'entry.js');
}

View file

@ -0,0 +1,53 @@
import { DaemonServer } from './server.js';
import { DaemonPaths } from './pid.js';
import { installDaemonSignals } from './lifecycle.js';
import { createConfig, getCredentialsOrThrow } from '../config.js';
import { parseIntegerOption, validateProfile } from '../validate.js';
import { installCliConsoleGuard } from '../cli-console.js';
import { resolveTransport, validateTransport } from '../transport.js';
installCliConsoleGuard();
async function main(): Promise<void> {
const configDir = process.env.TG_DAEMON_CONFIG_DIR;
const profile = process.env.TG_DAEMON_PROFILE;
const idleInput = process.env.TG_DAEMON_IDLE_TIMEOUT;
const configPath = process.env.TG_DAEMON_CONFIG;
const transportInput = process.env.TG_DAEMON_TRANSPORT;
const pidPreclaimed = process.env.TG_DAEMON_PID_PRECLAIMED === '1';
delete process.env.TG_DAEMON_SESSION;
delete process.env.TG_DAEMON_API_HASH;
delete process.env.TG_DAEMON_API_ID;
delete process.env.TG_DAEMON_CONFIG_DIR;
delete process.env.TG_DAEMON_PROFILE;
delete process.env.TG_DAEMON_IDLE_TIMEOUT;
delete process.env.TG_DAEMON_CONFIG;
delete process.env.TG_DAEMON_TRANSPORT;
delete process.env.TG_DAEMON_PID_PRECLAIMED;
if (!configDir || !profile || idleInput == null) {
process.stderr.write('Daemon missing TG_DAEMON_CONFIG_DIR / PROFILE / IDLE_TIMEOUT\n');
process.exit(1);
}
validateProfile(profile);
const idleTimeout = parseIntegerOption(idleInput, 'daemon idle timeout');
const config = createConfig(configPath);
const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile);
const transport = resolveTransport(config, profile, transportInput === undefined ? undefined : validateTransport(transportInput));
const paths = new DaemonPaths(configDir, profile);
const server = new DaemonServer(
paths,
{ apiId, apiHash, transport },
{ idleTimeout, onIdle: () => process.exit(0), pidPreclaimed },
);
installDaemonSignals(() => server.stop());
await server.start();
}
main().catch((err) => {
process.stderr.write(`Daemon start failed: ${(err as Error).message}\n`);
process.exit(1);
});

View file

@ -0,0 +1,66 @@
import { createBridgeCommand } from '../../commands/bridge/index.js';
import { Command, CommanderError } from 'commander';
import type { TelegramClient } from 'teleproto';
import { createChatCommand } from '../../commands/chat/index.js';
import { createMessageCommand } from '../../commands/message/index.js';
import { createMediaCommand } from '../../commands/media/index.js';
import { createUserCommand } from '../../commands/user/index.js';
import { createContactCommand } from '../../commands/contact/index.js';
import { outputError } from '../output.js';
import { TgError, translateTelegramError } from '../errors.js';
import { ErrorCode } from '../error-codes.js';
import { isDaemonCommand, validateDaemonCommand, type DaemonExecutionResult } from './command-protocol.js';
import { runWithDaemonContext, type DaemonExecutionContext } from './execution-context.js';
export type { DaemonExecutionResult } from './command-protocol.js';
/** Fresh Commander instances isolate arguments/defaults across API requests. */
function createExecutionProgram(profile: string): Command {
const program = new Command('tg');
program.setOptionValue('profile', profile).setOptionValue('quiet', true)
.setOptionValue('json', true).setOptionValue('daemon', false);
for (const group of [createBridgeCommand(), createChatCommand(), createMessageCommand(), createMediaCommand(), createUserCommand(), createContactCommand()]) {
program.addCommand(group);
}
program.hook('preAction', (_program, action) => {
if (!isDaemonCommand([action.parent?.name() ?? '', action.name()])) {
throw new TgError('This action is not available through execute', ErrorCode.DAEMON_PROXY_UNAVAILABLE);
}
});
const configure = (command: Command) => {
command.exitOverride().helpOption(false).addHelpCommand(false).allowExcessArguments(false);
command.configureOutput({ writeOut: () => {}, writeErr: () => {}, outputError: () => {} });
for (const child of command.commands) configure(child);
};
configure(program);
return program;
}
/** Run known handlers on the daemon's client, capturing DTOs rather than stdout. */
export async function executeDaemonCommand(
client: TelegramClient,
profile: string,
params: Record<string, unknown>,
signal: AbortSignal,
): Promise<DaemonExecutionResult> {
const context: DaemonExecutionContext = { client, profile, signal, exitCode: 0 };
return runWithDaemonContext(context, async () => {
try {
signal.throwIfAborted();
const request = validateDaemonCommand(params);
context.stdin = request.stdin;
context.cwd = request.cwd;
await createExecutionProgram(profile).parseAsync(request.argv, { from: 'user' });
signal.throwIfAborted();
if (!context.output) outputError('Command completed without a result', ErrorCode.UNKNOWN_ERROR);
} catch (error) {
const formatted = translateTelegramError(error);
outputError(formatted.message, error instanceof CommanderError ? ErrorCode.INVALID_OPTIONS : formatted.code);
}
if (signal.aborted) {
const { message, code } = translateTelegramError(signal.reason);
return { output: { ok: false, error: message, code }, exitCode: 1 };
}
return { output: context.output!, exitCode: context.exitCode };
});
}

View file

@ -0,0 +1,49 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import type { TelegramClient } from 'teleproto';
import type { OutputEnvelope } from '../types.js';
/** State belonging to one command on the daemon's existing Telegram client. */
export interface DaemonExecutionContext {
client: TelegramClient;
profile: string;
signal: AbortSignal;
stdin?: string;
cwd?: string;
output?: OutputEnvelope<unknown>;
exitCode: number;
}
const contexts = new AsyncLocalStorage<DaemonExecutionContext>();
/** Keep async continuations attached to their request, including concurrent commands. */
export async function runWithDaemonContext<T>(
context: DaemonExecutionContext,
fn: () => T | Promise<T>,
): Promise<T> {
return contexts.run(context, fn);
}
/** Undefined outside a daemon command; direct CLI and library calls keep their behavior. */
export function getDaemonContext(): DaemonExecutionContext | undefined {
return contexts.getStore();
}
/** Shared SDK timers and transport loops must outlive requests without retaining their DTOs. */
export function runOutsideDaemonContext<T>(fn: () => T): T {
return contexts.exit(fn);
}
/** A failed command must not change the exit status of the daemon hosting it. */
export function markExitFailure(): void {
const context = getDaemonContext();
if (context) context.exitCode = 1;
else process.exitCode = 1;
}
/** Capture raw DTOs before formatting. Later output cannot replace the first response. */
export function captureDaemonOutput(envelope: OutputEnvelope<unknown>): boolean {
const context = getDaemonContext();
if (!context) return false;
context.output ??= envelope;
return true;
}

View file

@ -0,0 +1,29 @@
/** Maximum UTF-8 bytes in one NDJSON frame, excluding the newline delimiter. */
export const MAX_FRAME_BYTES = 1_048_576;
/**
* Incremental, byte-bounded NDJSON framing. Counts individual frames rather than
* whole data events, which may contain several lines or fragments of UTF-8 text.
*/
export class JsonLineDecoder {
private chunks: Buffer[] = [];
private bytes = 0;
push(chunk: Buffer, onLine: (line: string) => void): void {
let offset = 0;
while (offset < chunk.length) {
const newline = chunk.indexOf(10, offset);
const end = newline === -1 ? chunk.length : newline;
const part = chunk.subarray(offset, end);
this.bytes += part.length;
if (this.bytes > MAX_FRAME_BYTES) throw new Error('Message too large');
if (part.length) this.chunks.push(part);
if (newline === -1) return;
const line = Buffer.concat(this.chunks, this.bytes).toString('utf-8');
this.chunks = [];
this.bytes = 0;
onLine(line);
offset = newline + 1;
}
}
}

View file

@ -0,0 +1,82 @@
import { outputError } from '../output.js';
import { ErrorCode } from '../error-codes.js';
import { createConfig } from '../config.js';
import { DaemonPaths } from './pid.js';
import { DaemonClient } from './client.js';
import { isProcessAlive } from './lifecycle.js';
const PROXY_MSG =
'This operation cannot be proxied. Use CLI --daemon or DaemonClient.execute for supported commands; auth/session operations require stopping the daemon.';
const RUNNING_MSG =
'A daemon is running for this profile. Use --daemon for commands, or tg daemon stop before auth/session operations.';
/** Refuse --daemon on commands that open their own MTProto client. */
export function rejectDaemonProxy(opts: { daemon?: boolean }): boolean {
if (!opts.daemon) return false;
outputError(PROXY_MSG, ErrorCode.DAEMON_PROXY_UNAVAILABLE);
return true;
}
export function daemonPidAlive(paths: DaemonPaths): boolean {
const pid = paths.readPid();
return pid != null && isProcessAlive(pid);
}
/** Unlink socket/pid only when no live process is holding them. */
export function cleanupStaleDaemon(paths: DaemonPaths): boolean {
if (daemonPidAlive(paths)) return false;
paths.cleanup();
return true;
}
/** True if the unix socket answers JSON-RPC ping. Never unlinks. */
export async function pingDaemon(paths: DaemonPaths, timeoutMs = 1500): Promise<boolean> {
if (!paths.socketExists()) return false;
const daemon = new DaemonClient(paths.socketPath);
try {
const pong = await daemon.call('ping', {}, { timeoutMs });
return pong === 'pong';
} catch {
return false;
} finally {
daemon.close();
}
}
/**
* True if a live daemon answered ping or a live PID still holds the files.
* Prints an error when blocking.
*/
export async function blockIfDaemonRunning(paths: DaemonPaths): Promise<boolean> {
if (paths.socketExists()) {
if (await pingDaemon(paths)) {
outputError(RUNNING_MSG, ErrorCode.DAEMON_ALREADY_RUNNING);
return true;
}
if (!cleanupStaleDaemon(paths)) {
outputError(
'Daemon is not responding. Try: tg daemon stop && tg daemon start',
ErrorCode.DAEMON_CONNECTION_FAILED,
);
return true;
}
}
if (daemonPidAlive(paths)) {
outputError(RUNNING_MSG, ErrorCode.DAEMON_ALREADY_RUNNING);
return true;
}
return false;
}
/** --daemon refuse, or block a direct MTProto connect beside a live daemon. */
export async function refuseDirectConnectIfDaemon(opts: {
profile: string;
config?: string;
daemon?: boolean;
}): Promise<boolean> {
if (rejectDaemonProxy(opts)) return true;
const config = createConfig(opts.config);
const configDir = config.path.replace(/[/\\][^/\\]+$/, '');
return blockIfDaemonRunning(new DaemonPaths(configDir, opts.profile));
}

View file

@ -0,0 +1,70 @@
/**
* Daemon process helpers: liveness, signals, child env without secrets.
*/
import type { Transport } from '../types.js';
export function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (err) {
// EPERM: process exists but we cannot signal it (other uid). Not dead.
return (err as NodeJS.ErrnoException).code === 'EPERM';
}
}
/** Env passed to a forked daemon. Never includes session string or apiHash. */
export function daemonChildEnv(opts: {
configDir: string;
profile: string;
idleTimeout: number;
configPath?: string;
transport?: Transport;
}): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env };
delete env.TG_DAEMON_SESSION;
delete env.TG_DAEMON_API_HASH;
delete env.TG_DAEMON_API_ID;
env.TG_DAEMON_CONFIG_DIR = opts.configDir;
env.TG_DAEMON_PROFILE = opts.profile;
env.TG_DAEMON_IDLE_TIMEOUT = String(opts.idleTimeout);
env.TG_DAEMON_PID_PRECLAIMED = '1';
delete env.TG_DAEMON_TRANSPORT;
if (opts.transport) env.TG_DAEMON_TRANSPORT = opts.transport;
if (opts.configPath) env.TG_DAEMON_CONFIG = opts.configPath;
return env;
}
/**
* SIGTERM/SIGINT → await stop(), then process.exit.
* Returns an uninstall function (for tests).
*/
export function installDaemonSignals(stop: () => Promise<void>): () => void {
let stopping = false;
const onSignal = () => {
if (stopping) return;
stopping = true;
stop()
.then(() => process.exit(0))
.catch(() => process.exit(1));
};
process.on('SIGTERM', onSignal);
process.on('SIGINT', onSignal);
return () => {
process.off('SIGTERM', onSignal);
process.off('SIGINT', onSignal);
};
}
export async function waitWhile(
predicate: () => boolean,
timeoutMs: number,
stepMs = 50,
): Promise<boolean> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (!predicate()) return true;
await new Promise((r) => setTimeout(r, stepMs));
}
return !predicate();
}

106
cli/src/lib/daemon/pid.ts Normal file
View file

@ -0,0 +1,106 @@
// src/lib/daemon/pid.ts
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
import { join, dirname, basename } from 'node:path';
/**
* Manages daemon PID file and socket path for a given profile.
*
* Paths:
* Socket: {configDir}/daemon/{profile}.sock
* PID: {configDir}/daemon/{profile}.pid
*/
export class DaemonPaths {
readonly socketPath: string;
readonly pidPath: string;
readonly logPath: string;
constructor(readonly configDir: string, readonly profile: string) {
const daemonDir = join(configDir, 'daemon');
const safe = basename(profile);
this.socketPath = join(daemonDir, `${safe}.sock`);
this.pidPath = join(daemonDir, `${safe}.pid`);
this.logPath = join(daemonDir, `${safe}.log`);
}
/**
* Validate that the socket path fits within AF_UNIX limits.
* macOS: 104 bytes, Linux: 108 bytes. Use 104 for portability.
*/
validateSocketPath(): void {
if (Buffer.byteLength(this.socketPath, 'utf-8') > 104) {
throw new Error(
`Socket path too long (${this.socketPath.length} chars, max 104). ` +
'Use --config to set a shorter config directory path.',
);
}
}
/** Ensure the daemon directory exists with owner-only access. */
ensureDir(): void {
const dir = dirname(this.socketPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
}
/** Write the current process PID. */
writePid(pid: number): void {
this.ensureDir();
writeFileSync(this.pidPath, String(pid), { encoding: 'utf-8', mode: 0o600 });
}
/** Create the PID file exclusively. False if it already exists. */
writePidExclusive(pid: number): boolean {
this.ensureDir();
try {
writeFileSync(this.pidPath, String(pid), { encoding: 'utf-8', flag: 'wx', mode: 0o600 });
return true;
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;
throw err;
}
}
unlinkSocket(): void {
if (existsSync(this.socketPath)) {
try { unlinkSync(this.socketPath); } catch { /* stale socket */ }
}
}
/** Read the stored PID, or null if file doesn't exist or PID is invalid. */
readPid(): number | null {
if (!existsSync(this.pidPath)) return null;
const content = readFileSync(this.pidPath, 'utf-8').trim();
const pid = /^\d+$/.test(content) ? Number(content) : NaN;
// Reject non-positive, NaN, and implausibly large PIDs to prevent
// process.kill(0) (kill process group) or kill(-1) (kill all user procs)
if (!Number.isSafeInteger(pid) || pid <= 0 || pid > 4_194_304) return null;
return pid;
}
/** Check whether the socket file exists. */
socketExists(): boolean {
return existsSync(this.socketPath);
}
/** Remove PID file and socket file. Caller must have checked nothing live owns them. */
cleanup(): void {
for (const p of [this.pidPath, this.socketPath]) {
if (existsSync(p)) {
try { unlinkSync(p); } catch {}
}
}
}
/**
* Unlink socket then pid, each only if the pid file still contains `pid`.
* Socket first: unlinking pid first lets a successor take `wx` and then
* get its socket deleted. No-op when another process owns the files.
*/
cleanupOwned(pid: number): void {
if (this.readPid() === pid) this.unlinkSocket();
if (this.readPid() === pid) {
try { unlinkSync(this.pidPath); } catch { /* gone */ }
}
}
}

View file

@ -0,0 +1,76 @@
// src/lib/daemon/protocol.ts
/**
* JSON-RPC 2.0 message types for daemon IPC.
* Messages are newline-delimited JSON over Unix domain sockets.
*/
export interface JsonRpcRequest {
jsonrpc: '2.0';
method: string;
params: Record<string, unknown>;
id: number;
}
export interface JsonRpcResponse {
jsonrpc: '2.0';
result: unknown;
id: number;
}
export interface JsonRpcError {
jsonrpc: '2.0';
error: { code: number; message: string; data?: unknown };
id: number | null;
}
export type JsonRpcMessage =
| { type: 'request'; method: string; params: Record<string, unknown>; id: number }
| { type: 'notification'; method: string; params: Record<string, unknown> }
| { type: 'response'; result: unknown; id: number }
| { type: 'error'; error: { code: number; message: string; data?: unknown }; id: number | null };
export function encodeRequest(method: string, params: Record<string, unknown>, id: number): string {
return JSON.stringify({ jsonrpc: '2.0', method, params, id });
}
export function encodeResponse(result: unknown, id: number): string {
return JSON.stringify({ jsonrpc: '2.0', result, id });
}
export function encodeError(code: number, message: string, data: unknown, id: number | null): string {
return JSON.stringify({ jsonrpc: '2.0', error: { code, message, data }, id });
}
/** Server-push event. No `id` — JSON-RPC notification. */
export function encodeNotification(method: string, params: Record<string, unknown>): string {
return JSON.stringify({ jsonrpc: '2.0', method, params });
}
export function parseMessage(raw: string): JsonRpcMessage {
let msg: any;
try {
msg = JSON.parse(raw);
} catch {
throw new Error(`Invalid JSON: ${raw.slice(0, 100)}`);
}
if (msg.jsonrpc !== '2.0') {
throw new Error('Invalid JSON-RPC: missing jsonrpc 2.0 field');
}
if ('method' in msg) {
if (msg.id === undefined || msg.id === null) {
return { type: 'notification', method: msg.method, params: msg.params ?? {} };
}
return { type: 'request', method: msg.method, params: msg.params ?? {}, id: msg.id };
}
if ('result' in msg) {
return { type: 'response', result: msg.result, id: msg.id };
}
if ('error' in msg) {
return { type: 'error', error: msg.error, id: msg.id };
}
throw new Error('Invalid JSON-RPC message: neither request, response, nor error');
}

View file

@ -0,0 +1,114 @@
import type { TelegramClient } from 'teleproto';
import { runOutsideDaemonContext } from './execution-context.js';
// These SDK methods create/cache transport objects, retain callbacks or change
// the shared connection. They must never retain the lifetime of one request.
// Once started, their maintenance finishes even if that request is cancelled.
const SHARED_LIFETIME_METHODS = new Set<PropertyKey>([
'_leaseSender', '_makeSender', '_createConnection', 'getSender', '_borrowExportedSender', '_createExportedSender', '_connectSender',
'_switchDC', 'connect', '_disconnect', 'disconnect', 'destroy',
'_authKeyCallback', '_cleanupExportedSender', '_handleReconnect',
]);
/** SDK view and outstanding work owned by one daemon command. */
export interface RequestClient {
client: TelegramClient;
/** Wait for every already-started SDK promise, including detached calls. */
settled(): Promise<void>;
}
/**
* A request-local client view: cancellation never destroys the shared client.
* Calls keep this view as `this`, so SDK helpers that make another client call
* after an await also observe cancellation. Shared transport maintenance keeps
* the real client as `this`; it must complete and its retained callbacks must
* remain usable after this request ends. Lazy iterators and sender queue entry
* points are guarded as well. Existing RPCs remain tracked until settled.
*/
export function createRequestClient(client: TelegramClient, signal: AbortSignal): RequestClient {
const pending = new Set<Promise<unknown>>();
const views = new WeakMap<object, object>();
let reconnectRequired = false;
const track = (promise: PromiseLike<unknown>, transform: (value: unknown) => unknown): Promise<unknown> => {
const tracked = Promise.resolve(promise).then(transform);
pending.add(tracked);
// Both branches handle rejection even if an SDK helper detaches its promise.
void tracked.then(() => pending.delete(tracked), () => pending.delete(tracked));
return tracked;
};
const wrapResult = (value: unknown, sender = false): unknown => {
if (value == null || (typeof value !== 'object' && typeof value !== 'function')) return value;
if (typeof (value as PromiseLike<unknown>).then === 'function') {
return track(value as PromiseLike<unknown>, (result) => wrapResult(result, sender));
}
if (sender || typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'
|| typeof (value as Iterator<unknown>).next === 'function') {
return wrap(value as object, sender ? 'sender' : 'iterator');
}
return value;
};
const wrap = (target: object, kind: 'client' | 'sender' | 'iterator'): object => {
const existing = views.get(target);
if (existing) return existing;
const functions = new Map<PropertyKey, { original: Function; guarded: Function }>();
const view = new Proxy(target, {
get(object, key, receiver) {
// Avoid SDK request replay without changing the shared client's options.
if (kind === 'client' && key === '_requestRetries') { signal.throwIfAborted(); return 1; }
if (kind === 'client' && key === 'floodSleepThreshold') return 0;
const value = Reflect.get(object, key, receiver);
if (kind === 'client' && key === '_sender' && value) return wrap(value, 'sender');
if (kind === 'client' && (key === '_connection' || key === 'networkSocket')) return value;
if (typeof value !== 'function' || key === 'constructor') return value;
const cached = functions.get(key);
if (cached && cached.original === value) return cached.guarded;
// SDK properties also include classes such as MarkdownParser. A
// function proxy preserves their static APIs and constructor behavior.
const guarded = new Proxy(value, {
apply(fn, _thisArg, args: unknown[]) {
// SDK invoke repairs CONNECTION_NOT_INITED with disconnect(), a
// delay, then connect(). Complete that repair across cancellation;
// the next user RPC still passes through the guarded sender queue.
if (!(kind === 'client' && key === 'connect' && reconnectRequired)) signal.throwIfAborted();
if (kind === 'client' && key === 'disconnect') reconnectRequired = true;
const sharedLifetime = kind === 'client' && SHARED_LIFETIME_METHODS.has(key);
const result = sharedLifetime
? runOutsideDaemonContext(() => Reflect.apply(fn, object, args))
: Reflect.apply(fn, receiver, args);
if (kind === 'client' && key === 'connect') reconnectRequired = false;
if (kind === 'client' && key === '_leaseSender') {
return track(Promise.resolve(result), (lease: any) => ({ sender: wrap(lease.sender, 'sender'), release: lease.release.bind(lease) }));
}
return wrapResult(result, kind === 'client' && (
key === 'getSender' || key === '_borrowExportedSender' || key === '_createExportedSender' || key === '_connectSender'
));
},
construct(fn, args, newTarget) {
signal.throwIfAborted();
return Reflect.construct(fn, args, newTarget);
},
});
functions.set(key, { original: value, guarded });
return guarded;
},
set(object, key, value) {
return Reflect.set(object, key, value, object);
},
});
views.set(target, view);
views.set(view, view);
return view;
};
return {
client: wrap(client, 'client') as TelegramClient,
async settled() {
while (pending.size > 0) {
await Promise.allSettled([...pending]);
}
},
};
}

View file

@ -0,0 +1,91 @@
import type { Command } from 'commander';
import { createConfig } from '../config.js';
import { outputError, outputSuccess } from '../output.js';
import { ErrorCode } from '../error-codes.js';
import { TgError, formatError } from '../errors.js';
import { DaemonPaths } from './pid.js';
import { DaemonClient, DaemonRpcError } from './client.js';
import { daemonPidAlive } from './guard.js';
import { isDaemonCommand, type DaemonCommandRequest } from './command-protocol.js';
import { MAX_FRAME_BYTES } from './frames.js';
/** Stop Commander before the local action once its remote result is rendered. */
export class DaemonCommandHandled extends Error {}
export function commandPath(command: Command): string[] {
const path: string[] = [];
for (let current: Command | null = command; current?.parent; current = current.parent) path.unshift(current.name());
return path;
}
/** Re-encode parsed values as argv, preserving positional dashes and repeated options. */
export function daemonRequestForCommand(command: Command): DaemonCommandRequest {
const argv = commandPath(command);
const opts = command.opts();
for (const option of command.options) {
const value = opts[option.attributeName()];
if (value === undefined || !option.long) continue;
if (option.negate) {
if (value === false) argv.push(option.long);
} else if (option.required || option.optional) {
for (const entry of Array.isArray(value) ? value : [value]) argv.push(`${option.long}=${String(entry)}`);
} else if (value === true) argv.push(option.long);
}
const args = command.processedArgs.flatMap(arg => Array.isArray(arg) ? arg : [arg])
.filter(arg => arg !== undefined).map(String);
if (args.length) argv.push('--', ...args);
return { argv, cwd: process.cwd() };
}
async function readRequestStdin(): Promise<string> {
if (process.stdin.isTTY) throw new TgError('"-" requires piped message input', ErrorCode.STDIN_REQUIRED);
const chunks: Buffer[] = [];
let bytes = 0;
for await (const chunk of process.stdin) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
bytes += buffer.length;
if (bytes > MAX_FRAME_BYTES - 4096) throw new TgError('Piped message exceeds the daemon frame limit', ErrorCode.MESSAGE_TOO_LONG);
chunks.push(buffer);
}
return Buffer.concat(chunks).toString('utf8');
}
/** Route supported --daemon actions once; never fall back to a direct session. */
export async function routeThroughDaemon(command: Command): Promise<boolean> {
const opts = command.optsWithGlobals();
const path = commandPath(command);
if (!opts.daemon || !isDaemonCommand(path)) return false;
let daemon: DaemonClient | undefined;
try {
const config = createConfig(opts.config);
const configDir = config.path.replace(/[/\\][^/\\]+$/, '');
const paths = new DaemonPaths(configDir, opts.profile);
if (!paths.socketExists()) {
throw new TgError(daemonPidAlive(paths) ? 'Daemon is starting or not responding' : 'Daemon is not running. Start one with: tg daemon start',
daemonPidAlive(paths) ? ErrorCode.DAEMON_CONNECTION_FAILED : ErrorCode.DAEMON_NOT_RUNNING);
}
const request = daemonRequestForCommand(command);
const textIndex = path[0] === 'message' ? path[1] === 'send' ? 1 : path[1] === 'edit' ? 2 : -1 : -1;
if (textIndex >= 0 && command.processedArgs[textIndex] === '-') request.stdin = await readRequestStdin();
daemon = new DaemonClient(paths.socketPath);
const result = await daemon.execute(request.argv, request);
if (result.output.ok) outputSuccess(result.output.data);
else outputError(result.output.error, result.output.code);
if (result.exitCode !== 0) process.exitCode = result.exitCode;
} catch (error) {
if (error instanceof DaemonRpcError) {
if (error.code === -32601) {
outputError('Running daemon does not support execute. Restart it with the current tg binary.', ErrorCode.DAEMON_PROXY_UNAVAILABLE);
} else {
const data = error.data as { tgCode?: unknown } | undefined;
outputError(error.message, typeof data?.tgCode === 'string' ? data.tgCode : ErrorCode.DAEMON_CONNECTION_FAILED);
}
} else {
const { message, code } = formatError(error);
outputError(message, code ?? ErrorCode.DAEMON_CONNECTION_FAILED);
}
} finally {
daemon?.close();
}
return true;
}

View file

@ -0,0 +1,483 @@
// src/lib/daemon/server.ts
import { createServer, type Server, type Socket } from 'node:net';
import { chmodSync } from 'node:fs';
import type { TelegramClient } from 'teleproto';
import { NewMessage } from 'teleproto/events/NewMessage.js';
import { DaemonPaths } from './pid.js';
import { cleanupStaleDaemon, daemonPidAlive, pingDaemon } from './guard.js';
import { encodeResponse, encodeError, encodeNotification, parseMessage } from './protocol.js';
import { resolveEntity } from '../peer.js';
import { markedPeerId, messagePeerMarkedId, serializeMessage } from '../serialize.js';
import { parseTopicId } from '../validate.js';
import { messageMatchesTopic } from './topic-filter.js';
import { SessionStore } from '../session-store.js';
import { JsonLineDecoder, MAX_FRAME_BYTES } from './frames.js';
import { createGramjsLogger } from '../gramjs-logger.js';
import { installClientErrorDiagnostics } from '../transport-diagnostics.js';
import { connectionOptions } from '../connection-options.js';
import type { Transport } from '../types.js';
import { connectOrThrow } from '../connect.js';
import { createRequestClient } from './request-client.js';
import { executeDaemonCommand } from './execute.js';
import { TgError } from '../errors.js';
import { ErrorCode } from '../error-codes.js';
const MAX_ACTIVE_REQUESTS = 16;
const MAX_EXECUTION_TIMEOUT = 120_000;
interface ActiveRequest {
controller: AbortController;
done: Promise<void>;
socket: Socket;
}
interface DaemonClientOpts {
apiId: number;
apiHash: string;
transport?: Transport;
/** Optional in-memory session for library callers; CLI always reads under lock. */
sessionString?: string;
}
interface DaemonServerOpts {
/** Idle timeout in ms before auto-shutdown. Default: 300_000 (5 min). */
idleTimeout?: number;
/** Called after stop() from idle timeout or shutdown RPC (not from explicit stop()). */
onIdle?: () => void;
/** Parent already `writePidExclusive(child.pid)` — wait for that file, never stale-clean it. */
pidPreclaimed?: boolean;
}
/**
* Daemon server that holds a persistent TelegramClient connection
* and accepts JSON-RPC 2.0 requests over a Unix domain socket.
*/
export class DaemonServer {
private readonly paths: DaemonPaths;
private readonly clientOpts: DaemonClientOpts;
private readonly idleTimeout: number;
private readonly onIdle?: () => void;
private readonly pidPreclaimed: boolean;
private server: Server | null = null;
private client: TelegramClient | null = null;
private idleTimer: ReturnType<typeof setTimeout> | null = null;
private startTime: number = 0;
private stopping: Promise<void> | null = null;
private starting: Promise<void> | null = null;
private releaseSession: (() => Promise<void>) | null = null;
private stopRequested = false;
private ownsPid = false;
private readonly sockets = new Set<Socket>();
private readonly activeRequests = new Set<ActiveRequest>();
constructor(paths: DaemonPaths, clientOpts: DaemonClientOpts, opts?: DaemonServerOpts) {
this.paths = paths;
this.clientOpts = clientOpts;
this.idleTimeout = opts?.idleTimeout ?? 300_000;
if (!Number.isSafeInteger(this.idleTimeout) || this.idleTimeout < 0 || this.idleTimeout > 2_147_483_647) {
throw new Error('Daemon idle timeout must be an integer from 0 to 2147483647 milliseconds');
}
this.onIdle = opts?.onIdle;
this.pidPreclaimed = opts?.pidPreclaimed ?? false;
}
async start(): Promise<void> {
if (this.stopping) throw new Error('Daemon is stopping');
if (this.starting) return this.starting;
this.starting = this.doStart();
return this.starting;
}
private async doStart(): Promise<void> {
this.paths.ensureDir();
this.paths.validateSocketPath();
if (this.pidPreclaimed) {
const deadline = Date.now() + 2_000;
while (this.paths.readPid() !== process.pid && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 10));
}
}
const weOwnPid = this.paths.readPid() === process.pid;
if (!weOwnPid) {
if (this.pidPreclaimed) {
throw new Error('Daemon already running');
}
if (daemonPidAlive(this.paths) || await pingDaemon(this.paths)) {
throw new Error('Daemon already running');
}
if (!cleanupStaleDaemon(this.paths)) {
throw new Error('Daemon already running');
}
if (!this.paths.writePidExclusive(process.pid)) {
throw new Error('Daemon already running');
}
this.ownsPid = true;
} else if (await pingDaemon(this.paths)) {
throw new Error('Daemon already running');
}
try {
this.throwIfStopping();
const store = new SessionStore(this.paths.configDir);
this.releaseSession = await store.acquireLock(this.paths.profile);
// A preclaimed PID belongs to this instance only after it also owns the
// session. Another instance in this process may own the same PID already.
this.ownsPid = true;
this.throwIfStopping();
const sessionString = this.clientOpts.sessionString ?? store.loadUnlocked(this.paths.profile);
if (!sessionString) throw new Error('Not logged in. Run: tg auth login');
this.paths.unlinkSocket();
const { TelegramClient, sessions } = await import('teleproto');
this.throwIfStopping();
const session = new sessions.StringSession(sessionString);
const logger = createGramjsLogger([this.clientOpts.apiHash, sessionString]);
this.client = new TelegramClient(session, this.clientOpts.apiId, this.clientOpts.apiHash, {
connectionRetries: 3,
requestRetries: 1,
catchUp: true,
retryDelay: 1000,
floodSleepThreshold: 60,
baseLogger: logger,
...connectionOptions(this.clientOpts.transport),
});
installClientErrorDiagnostics(this.client, logger);
await connectOrThrow(this.client);
this.throwIfStopping();
this.server = createServer((socket) => this.handleConnection(socket));
await new Promise<void>((resolve, reject) => {
this.server!.listen(this.paths.socketPath, () => resolve());
this.server!.on('error', reject);
});
chmodSync(this.paths.socketPath, 0o600);
this.startTime = Date.now();
this.resetIdle();
} catch (err) {
// Failed destruction cannot prove the session is safe for another owner.
// Retain the lease and PID if teardown itself rejects.
await this.client?.destroy();
this.client = null;
if (this.server) {
const server = this.server;
this.server = null;
await new Promise<void>((resolve) => server.close(() => resolve()));
}
this.cleanupPid();
await this.releaseOwnership();
throw err;
}
}
async stop(): Promise<void> {
if (this.stopping) return this.stopping;
this.stopRequested = true;
this.stopping = this.doStop();
return this.stopping;
}
private async doStop(): Promise<void> {
for (const request of this.activeRequests) {
request.controller.abort(new TgError('Daemon is stopping; the outcome of submitted Telegram operations may be unknown.', ErrorCode.DAEMON_STOPPING));
}
// Closing transport is what interrupts an SDK connection attempt. Waiting
// for start() first would prevent SIGTERM from ever initiating that cleanup.
if (!this.server && this.client) await this.client.destroy();
await this.starting?.catch(() => {});
if (this.idleTimer) {
clearTimeout(this.idleTimer);
this.idleTimer = null;
}
for (const socket of this.sockets) {
socket.destroy();
}
this.sockets.clear();
const server = this.server;
this.server = null;
if (server) {
await new Promise<void>((resolve) => {
server.close(() => resolve());
});
}
if (this.client) {
const started = [...this.activeRequests].map(request => request.done);
await this.client.destroy();
// Cancelling the RPC reply does not cancel a request already sent to
// Telegram. Keep ownership until its command and all SDK work settle.
await Promise.all(started);
// A DC migration already in progress may reconnect after the first
// destroy. Tear down its late transport before handing over the lease.
if (started.length > 0) await this.client.destroy();
this.client = null;
}
this.cleanupPid();
await this.releaseOwnership();
}
private async releaseOwnership(): Promise<void> {
const release = this.releaseSession;
this.releaseSession = null;
await release?.();
}
private throwIfStopping(): void {
if (this.stopRequested) throw new Error('Daemon start cancelled');
}
private cleanupPid(): void {
if (this.ownsPid) this.paths.cleanupOwned(process.pid);
this.ownsPid = false;
}
getClient(): TelegramClient | null {
return this.client;
}
private resetIdle(): void {
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
if (this.stopping) return;
if (this.idleTimeout <= 0) return;
if (this.sockets.size > 0) return;
if (this.activeRequests.size > 0) return;
this.idleTimer = setTimeout(() => {
void this.stop().then(() => this.onIdle?.()).catch(() => {});
}, this.idleTimeout);
}
private handleConnection(socket: Socket): void {
this.sockets.add(socket);
this.resetIdle();
socket.on('close', () => {
for (const request of this.activeRequests) {
if (request.socket === socket) request.controller.abort(new TgError(
'Caller disconnected; the outcome of submitted Telegram operations may be unknown.', ErrorCode.DAEMON_CANCELLED,
));
}
this.sockets.delete(socket);
this.resetIdle();
});
// A peer's reset, oversized frame or failed write belongs to that peer only.
socket.on('error', () => socket.destroy());
const decoder = new JsonLineDecoder();
const write = (line: string) => {
if (!socket.destroyed && socket.writable) socket.write(line + '\n');
};
const handleLine = async (line: string) => {
if (socket.destroyed) return;
this.resetIdle();
let id: number | null = null;
try {
const msg = parseMessage(line);
if (msg.type !== 'request') {
write(encodeError(-32600, 'Expected request', null, null));
return;
}
id = msg.id;
const result = await this.dispatch(msg.method, msg.params, socket);
const response = encodeResponse(result, id);
if (Buffer.byteLength(response, 'utf-8') > MAX_FRAME_BYTES) {
throw new TgError('Command completed but its response is too large. Narrow the requested data; do not blindly repeat writes.', ErrorCode.DAEMON_RESPONSE_TOO_LARGE);
}
write(response);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
const code = err instanceof Error && 'code' in err ? (err as any).code : -32000;
const data = err instanceof Error && 'code' in err && typeof (err as any).code === 'string'
? { tgCode: (err as any).code }
: undefined;
write(encodeError(typeof code === 'number' ? code : -32000, message, data, id));
}
};
socket.on('data', (chunk: Buffer) => {
try {
decoder.push(chunk, (line) => {
void handleLine(line).catch(() => socket.destroy());
});
} catch {
socket.destroy();
}
});
}
private async dispatch(
method: string,
params: Record<string, unknown>,
socket: Socket,
): Promise<unknown> {
switch (method) {
case 'ping':
return 'pong';
case 'status':
return {
running: true,
pid: process.pid,
uptime: Math.round((Date.now() - this.startTime) / 1000),
idleTimeout: this.idleTimeout / 1000,
connected: this.client != null && (this.client.connected ?? true),
transport: this.clientOpts.transport ?? 'tcp',
activeRequests: this.activeRequests.size,
apiVersion: 1,
capabilities: ['execute', 'subscribe'],
};
case 'shutdown':
setTimeout(() => {
void this.stop().then(() => this.onIdle?.()).catch(() => {});
}, 100);
return { shuttingDown: true };
case 'subscribe':
return this.subscribe(params, socket);
case 'execute':
return this.execute(params, socket);
default:
throw Object.assign(new Error(`Unknown method: ${method}`), { code: -32601 });
}
}
/** Execute one allowlisted command against the already-connected client. */
private async execute(params: Record<string, unknown>, socket: Socket): Promise<unknown> {
if (params == null || typeof params !== 'object' || Array.isArray(params)) {
throw new TgError('execute params must be an object', ErrorCode.INVALID_INPUT);
}
const timeoutMs = params.timeoutMs === undefined ? MAX_EXECUTION_TIMEOUT : params.timeoutMs;
if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_EXECUTION_TIMEOUT) {
throw new TgError('timeoutMs must be an integer from 1 to 120000', ErrorCode.INVALID_INPUT);
}
return this.runRequest(socket, timeoutMs, (client, signal) =>
executeDaemonCommand(client, this.paths.profile, params, signal));
}
/** Bound active SDK work, while allowing the caller to stop waiting sooner. */
private async runRequest<T>(
socket: Socket,
timeoutMs: number,
work: (client: TelegramClient, signal: AbortSignal) => Promise<T>,
): Promise<T> {
if (this.stopRequested || !this.client) {
throw new TgError('Daemon is stopping or has no connected client', ErrorCode.DAEMON_STOPPING);
}
if (this.activeRequests.size >= MAX_ACTIVE_REQUESTS) {
throw new TgError('Daemon is busy (16 commands are still running). Wait for active work to finish.', ErrorCode.DAEMON_BUSY);
}
if (socket.destroyed) throw new TgError('Caller disconnected before execution', ErrorCode.DAEMON_CANCELLED);
const controller = new AbortController();
const view = createRequestClient(this.client, controller.signal);
const request: ActiveRequest = { controller, done: Promise.resolve(), socket };
this.activeRequests.add(request);
this.resetIdle();
const timer = setTimeout(() => controller.abort(new TgError(
'Daemon request timed out. The outcome of submitted Telegram operations is unknown; check before repeating writes.', ErrorCode.TIMEOUT,
)), timeoutMs);
let rejectAborted!: (reason: unknown) => void;
const aborted = new Promise<never>((_resolve, reject) => { rejectAborted = reject; });
const onAbort = () => rejectAborted(controller.signal.reason);
controller.signal.addEventListener('abort', onAbort, { once: true });
const operation = Promise.resolve().then(async () => {
controller.signal.throwIfAborted();
const result = await work(view.client, controller.signal);
controller.signal.throwIfAborted();
return result;
});
request.done = operation.then(() => {}, () => {}).then(() => view.settled()).finally(() => {
clearTimeout(timer);
controller.signal.removeEventListener('abort', onAbort);
this.activeRequests.delete(request);
this.resetIdle();
});
// The caller can stop waiting before work finishes; keep cleanup handled.
void request.done.catch(() => {});
try {
return await Promise.race([operation, aborted]);
} finally {
clearTimeout(timer);
}
}
/**
* Ack the subscribe RPC, then push `message` notifications on this socket
* until it closes. Matching is by resolved peer id (+ optional topic).
*/
private async subscribe(params: Record<string, unknown>, socket: Socket): Promise<unknown> {
if (params == null || typeof params !== 'object' || Array.isArray(params)) {
throw new TgError('subscribe params must be an object', ErrorCode.INVALID_INPUT);
}
return this.runRequest(socket, MAX_EXECUTION_TIMEOUT, (client, signal) =>
this.prepareSubscription(params, socket, client, signal));
}
private async prepareSubscription(
params: Record<string, unknown>, socket: Socket, client: TelegramClient, signal: AbortSignal,
): Promise<unknown> {
const chat = String(params.chat ?? '').trim();
if (!chat) {
throw new Error('chat is required');
}
let topic: number | undefined;
if (params.topic != null) {
topic = parseTopicId(String(params.topic));
}
const entity = await resolveEntity(client, chat);
signal.throwIfAborted();
if (socket.destroyed || !this.client) throw new Error('Subscriber disconnected');
const wantId = markedPeerId(entity);
if (!wantId) {
throw new Error(`Could not resolve chat id for ${chat}`);
}
const handler = (event: any) => {
try {
const msg = event?.message ?? event;
if (!msg || msg.id == null) return;
const chatId = messagePeerMarkedId(msg);
if (!chatId || chatId !== wantId) return;
if (topic != null && !messageMatchesTopic(msg, topic)) return;
const payload = serializeMessage(msg, msg._sender) as unknown as Record<string, unknown>;
if (!socket.destroyed) {
this.resetIdle();
socket.write(encodeNotification('message', payload) + '\n');
}
} catch {
// Never throw into gramjs _updateLoop
}
};
const builder = new NewMessage({});
// After the acknowledgement, this handler belongs to the shared transport
// and socket, independent of the request view used to prepare it.
const sharedClient = this.client;
sharedClient.addEventHandler(handler, builder);
socket.once('close', () => {
try {
sharedClient.removeEventHandler(handler, builder);
} catch {
// gramjs removeEventHandler is best-effort
}
});
return { subscribed: true, chat, topic: topic ?? null };
}
}

View file

@ -0,0 +1,29 @@
/**
* Forum-topic membership for `message watch --topic`.
*
* Telegram: `replyTo.forumTopic === true` means a named topic.
* The topic root is `replyToTopId`, or `replyToMsgId` when that flag is set.
* General (id 1) is everything that is not a named forum topic.
* The topic-root message itself has `id === topic`.
*/
export function messageMatchesTopic(
msg: {
id?: number;
replyTo?: {
forumTopic?: boolean;
replyToTopId?: number;
replyToMsgId?: number;
} | null;
},
topic: number,
): boolean {
if (msg.id === topic) return true;
const reply = msg.replyTo;
const forumTopic = reply?.forumTopic === true;
const top = reply?.replyToTopId ?? (forumTopic ? reply?.replyToMsgId : undefined);
if (topic === 1) {
if (forumTopic && top != null && top !== 1) return false;
return true;
}
return top === topic;
}

18
cli/src/lib/entity-map.ts Normal file
View file

@ -0,0 +1,18 @@
/**
* Build entity lookup map from API result users/chats arrays.
* Shared utility used by replies, get-by-ID, and pinned message commands.
*
* @param result - API response containing optional users[] and chats[] arrays
* @returns Map keyed by marked peer ID, keeping user/chat/channel namespaces distinct
*/
export function buildEntityMap(result: any): Map<string, any> {
const map = new Map<string, any>();
for (const u of result.users ?? []) {
map.set(markedPeerId(u), u);
}
for (const c of result.chats ?? []) {
map.set(markedPeerId(c), c);
}
return map;
}
import { markedPeerId } from './serialize.js';

View file

@ -0,0 +1,64 @@
import { Api } from 'teleproto';
/**
* Convert Telegram MessageEntity[] to Markdown-formatted text.
*
* Processes entities from end to start (descending offset) to avoid
* offset shifts when replacing substrings with longer Markdown syntax.
*
* Handles: Bold, Italic, Code, Pre, TextUrl, Strike, Blockquote, MentionName,
* Spoiler, Underline, CustomEmoji.
* Mention and Url entities are kept as-is (already readable).
*/
export function entitiesToMarkdown(
text: string,
entities: Api.TypeMessageEntity[] | undefined,
): string {
if (!entities || entities.length === 0) return text;
// Sort by offset descending so replacements don't shift earlier offsets
const sorted = [...entities].sort((a, b) => b.offset - a.offset);
let result = text;
for (const entity of sorted) {
const start = entity.offset;
const end = start + entity.length;
const substr = result.substring(start, end);
let replacement = substr;
if (entity instanceof Api.MessageEntityBold) {
replacement = `**${substr}**`;
} else if (entity instanceof Api.MessageEntityItalic) {
replacement = `_${substr}_`;
} else if (entity instanceof Api.MessageEntityCode) {
replacement = `\`${substr}\``;
} else if (entity instanceof Api.MessageEntityPre) {
const lang = (entity as any).language || '';
replacement = `\`\`\`${lang}\n${substr}\n\`\`\``;
} else if (entity instanceof Api.MessageEntityTextUrl) {
replacement = `[${substr}](${(entity as any).url})`;
} else if (entity instanceof Api.MessageEntityStrike) {
replacement = `~~${substr}~~`;
} else if (entity instanceof Api.MessageEntityBlockquote) {
replacement = substr
.split('\n')
.map((line) => `> ${line}`)
.join('\n');
} else if (entity instanceof Api.MessageEntityMentionName) {
replacement = `[${substr}](tg://user?id=${(entity as any).userId})`;
} else if (entity instanceof Api.MessageEntitySpoiler) {
replacement = `||${substr}||`;
} else if (entity instanceof Api.MessageEntityUnderline) {
replacement = `<u>${substr}</u>`;
} else if (entity instanceof Api.MessageEntityCustomEmoji) {
const id = (entity as any).documentId;
replacement = `![${substr}](tg://emoji?id=${id})`;
}
// Mention, Url, and other entities are kept as-is
result = result.substring(0, start) + replacement + result.substring(end);
}
return result;
}

107
cli/src/lib/error-codes.ts Normal file
View file

@ -0,0 +1,107 @@
/**
* Centralized error codes for tg-cli.
* Every outputError() call should reference these constants
* instead of string literals to prevent typos and ease refactoring.
*/
export const ErrorCode = Object.freeze({
CONNECTION_FAILED: 'CONNECTION_FAILED',
// Auth
NOT_AUTHENTICATED: 'NOT_AUTHENTICATED',
NOT_LOGGED_IN: 'NOT_LOGGED_IN',
NOT_INTERACTIVE: 'NOT_INTERACTIVE',
// Input validation
INVALID_INPUT: 'INVALID_INPUT',
INVALID_OPTIONS: 'INVALID_OPTIONS',
INVALID_TOPIC_ID: 'INVALID_TOPIC_ID',
INVALID_MESSAGE_ID: 'INVALID_MESSAGE_ID',
INVALID_MSG_ID: 'INVALID_MSG_ID',
INVALID_MESSAGE_IDS: 'INVALID_MESSAGE_IDS',
INVALID_REPLY_TO: 'INVALID_REPLY_TO',
INVALID_COMMENT_TO: 'INVALID_COMMENT_TO',
INVALID_INVITE: 'INVALID_INVITE',
INVALID_CHAT_TYPE: 'INVALID_CHAT_TYPE',
INVALID_ID: 'INVALID_ID',
INVALID_FILTER: 'INVALID_FILTER',
// Message
MESSAGE_RESULT_UNAVAILABLE: 'MESSAGE_RESULT_UNAVAILABLE',
EMPTY_MESSAGE: 'EMPTY_MESSAGE',
MESSAGE_TOO_LONG: 'MESSAGE_TOO_LONG',
STDIN_REQUIRED: 'STDIN_REQUIRED',
DELETE_MODE_REQUIRED: 'DELETE_MODE_REQUIRED',
TOO_MANY_IDS: 'TOO_MANY_IDS',
MISSING_QUERY: 'MISSING_QUERY',
EMPTY_QUESTION: 'EMPTY_QUESTION',
QUESTION_TOO_LONG: 'QUESTION_TOO_LONG',
TOO_FEW_OPTIONS: 'TOO_FEW_OPTIONS',
TOO_MANY_OPTIONS: 'TOO_MANY_OPTIONS',
EMPTY_OPTION: 'EMPTY_OPTION',
OPTION_TOO_LONG: 'OPTION_TOO_LONG',
DUPLICATE_OPTION: 'DUPLICATE_OPTION',
QUIZ_MISSING_CORRECT: 'QUIZ_MISSING_CORRECT',
SOLUTION_WITHOUT_QUIZ: 'SOLUTION_WITHOUT_QUIZ',
QUIZ_MULTIPLE_CONFLICT: 'QUIZ_MULTIPLE_CONFLICT',
INVALID_CORRECT_INDEX: 'INVALID_CORRECT_INDEX',
INVALID_CLOSE_IN: 'INVALID_CLOSE_IN',
// Entity
PEER_NOT_FOUND: 'PEER_NOT_FOUND',
NOT_A_USER: 'NOT_A_USER',
NOT_A_FORUM: 'NOT_A_FORUM',
NOT_A_MEMBER: 'NOT_A_MEMBER',
NO_USERS_FOUND: 'NO_USERS_FOUND',
// Chat
USER_ALREADY_PARTICIPANT: 'USER_ALREADY_PARTICIPANT',
CHANNELS_TOO_MUCH: 'CHANNELS_TOO_MUCH',
UNKNOWN_INVITE_TYPE: 'UNKNOWN_INVITE_TYPE',
// Contact
MISSING_FIRST_NAME: 'MISSING_FIRST_NAME',
PHONE_NOT_FOUND: 'PHONE_NOT_FOUND',
INVALID_SCHEDULE: 'INVALID_SCHEDULE',
INVALID_PHOTO: 'INVALID_PHOTO',
NO_PROFILE_PHOTO: 'NO_PROFILE_PHOTO',
PHOTO_RESULT_UNAVAILABLE: 'PHOTO_RESULT_UNAVAILABLE',
// Media
ALBUM_TOO_LARGE: 'ALBUM_TOO_LARGE',
NO_MEDIA: 'NO_MEDIA',
PATH_TRAVERSAL: 'PATH_TRAVERSAL',
FILE_NOT_FOUND: 'FILE_NOT_FOUND',
FILE_EXISTS: 'FILE_EXISTS',
// Session & client
NO_SESSION: 'NO_SESSION',
NO_INPUT: 'NO_INPUT',
TIMEOUT: 'TIMEOUT',
TOO_MANY_USERS: 'TOO_MANY_USERS',
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
TG_ERROR: 'TG_ERROR',
CREDENTIAL_ERROR: 'CREDENTIAL_ERROR',
CONFIG_ERROR: 'CONFIG_ERROR',
SESSION_ERROR: 'SESSION_ERROR',
INVALID_SESSION: 'INVALID_SESSION',
VERIFY_FAILED: 'VERIFY_FAILED',
FLOOD_WAIT: 'FLOOD_WAIT',
// Presets
FETCH_FAILED: 'FETCH_FAILED',
UNKNOWN_PRESET: 'UNKNOWN_PRESET',
// Daemon
DAEMON_NOT_RUNNING: 'DAEMON_NOT_RUNNING',
DAEMON_ALREADY_RUNNING: 'DAEMON_ALREADY_RUNNING',
DAEMON_START_FAILED: 'DAEMON_START_FAILED',
DAEMON_STOP_FAILED: 'DAEMON_STOP_FAILED',
DAEMON_CONNECTION_FAILED: 'DAEMON_CONNECTION_FAILED',
DAEMON_PROXY_UNAVAILABLE: 'DAEMON_PROXY_UNAVAILABLE',
DAEMON_BUSY: 'DAEMON_BUSY',
DAEMON_CANCELLED: 'DAEMON_CANCELLED',
DAEMON_STOPPING: 'DAEMON_STOPPING',
DAEMON_RESPONSE_TOO_LARGE: 'DAEMON_RESPONSE_TOO_LARGE',
} as const);
export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];

113
cli/src/lib/errors.ts Normal file
View file

@ -0,0 +1,113 @@
import { ErrorCode } from './error-codes.js';
/**
* Base error class for tg-cli.
* All custom errors extend this for consistent error handling.
*/
export class TgError extends Error {
readonly code: string;
constructor(message: string, code: string = ErrorCode.TG_ERROR) {
super(message);
this.name = 'TgError';
this.code = code;
}
}
/**
* Thrown when API credentials are missing or invalid.
*/
export class CredentialError extends TgError {
constructor(message: string) {
super(message, ErrorCode.CREDENTIAL_ERROR);
this.name = 'CredentialError';
}
}
/**
* Thrown for session-related errors (corrupt, expired, locked).
*/
export class SessionError extends TgError {
constructor(message: string) {
super(message, ErrorCode.SESSION_ERROR);
this.name = 'SessionError';
}
}
/**
* Thrown when Telegram rate-limits a request.
* Includes the number of seconds to wait before retrying.
*/
export class FloodWaitError extends TgError {
readonly seconds: number;
constructor(seconds: number) {
super(`Rate limited. Retry after ${seconds} seconds.`, ErrorCode.FLOOD_WAIT);
this.name = 'FloodWaitError';
this.seconds = seconds;
}
}
/**
* Extract a structured error message and optional code from any thrown value.
* Handles Error instances, TgError subclasses, and arbitrary thrown values.
*/
export function formatError(err: unknown): { message: string; code?: string } {
if (err instanceof TgError) {
return { message: err.message, code: err.code };
}
if (err instanceof Error) {
if ('code' in err && err.code === 'ELOCKED') {
return { message: 'Session profile is busy. Wait for the running command or stop its daemon.', code: ErrorCode.SESSION_ERROR };
}
return { message: err.message };
}
return { message: String(err) };
}
/**
* Map of Telegram RPCError codes to human-readable messages.
* Used by translateTelegramError to produce actionable CLI output.
*/
const TELEGRAM_ERROR_MAP: Record<string, string> = {
'MESSAGE_EDIT_TIME_EXPIRED': 'Cannot edit: 48-hour edit window has expired',
'MESSAGE_AUTHOR_REQUIRED': 'Cannot edit: you can only edit your own messages',
'MESSAGE_DELETE_FORBIDDEN': 'Cannot delete this message',
'CHAT_ADMIN_REQUIRED': 'Admin privileges required',
'MESSAGE_ID_INVALID': 'Message not found',
'PEER_ID_INVALID': 'Peer not found',
'MESSAGE_NOT_MODIFIED': 'Message content unchanged',
'USER_BOT_INVALID': 'Cannot block this bot',
'INPUT_USER_DEACTIVATED': 'User account deleted',
'CONTACT_ID_INVALID': 'Contact not found',
'CONTACT_NAME_EMPTY': 'First name is required',
'CONTACT_REQ_MISSING': 'Contact request required',
'SEARCH_QUERY_EMPTY': 'Search query cannot be empty',
'PREMIUM_ACCOUNT_REQUIRED': 'Telegram Premium is required for this search',
'OFFSET_PEER_ID_INVALID': 'Invalid pagination peer. Pass nextOffsetPeer from the previous page',
// Poll error codes
'POLL_ANSWERS_INVALID': 'Invalid poll: need 2-10 answer options',
'POLL_OPTION_DUPLICATE': 'Duplicate poll option',
'POLL_OPTION_INVALID': 'Poll option text is invalid or too long',
'POLL_QUESTION_INVALID': 'Poll question is invalid or too long',
'QUIZ_CORRECT_ANSWERS_EMPTY': 'Quiz poll requires a correct answer',
'QUIZ_CORRECT_ANSWERS_TOO_MUCH': 'Quiz poll allows only one correct answer',
'CHAT_SEND_POLL_FORBIDDEN': 'You cannot send polls in this chat',
};
/**
* Translate a Telegram API error into a user-friendly message + code pair.
*
* Handles gramjs RPCError objects (which have an `errorMessage` property)
* by mapping known error codes to human-readable messages.
* Falls back to formatError for non-RPCError thrown values.
*/
export function translateTelegramError(err: unknown): { message: string; code: string } {
if (err != null && typeof err === 'object' && 'errorMessage' in err) {
const errorMessage = (err as any).errorMessage as string;
const humanMessage = TELEGRAM_ERROR_MAP[errorMessage] || errorMessage;
return { message: humanMessage, code: errorMessage };
}
const result = formatError(err);
return { message: result.message, code: result.code ?? ErrorCode.UNKNOWN_ERROR };
}

135
cli/src/lib/fields.ts Normal file
View file

@ -0,0 +1,135 @@
/**
* Field selection utilities for --fields CLI option.
* Supports dot-notation for nested paths (e.g., "media.filename").
*/
/** Known array property names for list command detection. */
const LIST_KEYS = ['messages', 'chats', 'members', 'topics', 'files', 'profiles', 'users', 'contacts', 'results', 'posts'] as const;
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
/**
* Pick specific fields from an object, supporting dot-notation paths.
* Missing or invalid paths are silently omitted.
*
* @example
* pickFields({ id: 1, text: "hi", date: "2026" }, ["id", "text"])
* // => { id: 1, text: "hi" }
*
* pickFields({ id: 1, media: { filename: "a.jpg", fileSize: 100 } }, ["id", "media.filename"])
* // => { id: 1, media: { filename: "a.jpg" } }
*/
export function pickFields<T>(obj: T, fields: string[]): Partial<T> {
const result: Record<string, unknown> = {};
for (const field of fields) {
const parts = field.split('.');
if (parts.some(part => !part || UNSAFE_KEYS.has(part))) continue;
// Walk source object to find value
let value: unknown = obj;
let valid = true;
for (const part of parts) {
if (value == null || typeof value !== 'object' || !Object.hasOwn(value, part)) {
valid = false;
break;
}
value = (value as Record<string, unknown>)[part];
if (value === undefined) {
valid = false;
break;
}
}
if (!valid) continue;
// Reconstruct nested path in result
let target = result;
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
if (!Object.hasOwn(target, part) || typeof target[part] !== 'object' || target[part] == null) {
target[part] = {};
}
target = target[part] as Record<string, unknown>;
}
target[parts[parts.length - 1]] = value;
}
return result as Partial<T>;
}
/**
* Apply field selection to a data object.
* For list data (containing arrays of objects), filters each item with pickFields
* while preserving metadata fields (total, count, etc.).
*
* @example
* applyFieldSelection({ messages: [{ id: 1, text: "hi" }], total: 5 }, ["id"])
* // => { messages: [{ id: 1 }], total: 5 }
*/
export function applyFieldSelection(data: unknown, fields: string[]): unknown {
if (data == null || typeof data !== 'object') return data;
const obj = data as Record<string, unknown>;
const isNamedListKey = (key: string) =>
(LIST_KEYS as readonly string[]).includes(key);
const isListShaped = Object.entries(obj).some(([key, value]) => {
if (key === 'errors' || UNSAFE_KEYS.has(key)) return false;
if (!Array.isArray(value)) return false;
if (isNamedListKey(key)) return true;
return value.length > 0 && typeof value[0] === 'object' && value[0] !== null;
});
// Single-object output (e.g., MessageItem from `message send`)
if (!isListShaped) {
const selected = pickFields(obj, fields);
if (Array.isArray(obj.errors)) {
selected.errors = obj.errors;
if (typeof obj.partial === 'boolean') selected.partial = obj.partial;
}
return selected;
}
// List-shaped data: filter each array item, preserve metadata (including empty lists)
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
if (UNSAFE_KEYS.has(key)) continue;
// Failures are operation metadata, not successful list items. Never
// erase their error/code when selecting fields such as --fields id.
if (key === 'errors' && Array.isArray(value)) {
result[key] = value;
continue;
}
if (
Array.isArray(value) &&
(isNamedListKey(key) || (value.length > 0 && typeof value[0] === 'object' && value[0] !== null))
) {
result[key] = value.map((item) =>
item != null && typeof item === 'object' ? pickFields(item, fields) : item,
);
} else {
result[key] = value;
}
}
return result;
}
/**
* Extract the list items array from a data object, if present.
* Checks known array property names in order: messages, chats, members, topics, files.
* Returns null if no list array is found.
*/
export function extractListItems(data: unknown): unknown[] | null {
if (data == null || typeof data !== 'object') return null;
const obj = data as Record<string, unknown>;
for (const key of LIST_KEYS) {
if (Array.isArray(obj[key])) {
return obj[key] as unknown[];
}
}
return null;
}

614
cli/src/lib/format.ts Normal file
View file

@ -0,0 +1,614 @@
import pc from 'picocolors';
import type {
MessageItem,
ChatListItem,
ChatInfo,
MemberItem,
SearchResultItem,
DownloadResult,
AlbumResult,
TopicItem,
DeleteResult,
PinResult,
UserProfile,
BlockResult,
BlockedListItem,
PollData,
} from './types.js';
import { formatBytes } from './media-utils.js';
/**
* Format a date string to local "YYYY-MM-DD HH:MM" display.
*/
function formatTimestamp(dateStr: string): string {
const d = new Date(dateStr);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
/**
* Build a rich media annotation string from a message's media metadata.
*
* With media metadata: [photo 1920x1080 240KB], [video 1280x720 0:32 1.2MB], [document report.pdf 3.4MB]
* Without metadata but with mediaType: [photo] (existing behavior for messages without full metadata)
* Neither: empty string
*/
function formatMediaAnnotation(m: MessageItem): string {
if (m.media) {
const parts: string[] = [m.mediaType ?? 'file'];
if (m.media.width != null && m.media.height != null) {
parts.push(`${m.media.width}x${m.media.height}`);
}
if (m.media.duration != null) {
const mins = Math.floor(m.media.duration / 60);
const secs = String(m.media.duration % 60).padStart(2, '0');
parts.push(`${mins}:${secs}`);
}
if (m.media.fileSize != null) {
parts.push(formatBytes(m.media.fileSize));
}
if (m.media.filename != null) {
parts.push(m.media.filename);
}
return `[${parts.join(' ')}]`;
}
if (m.mediaType) {
return `[${m.mediaType}]`;
}
return '';
}
/**
* Format poll data as expanded multi-line text.
*
* Renders question, numbered options with vote counts and correct markers,
* and config tags (Quiz, Public, Multiple, Closes in Ns, Closed, voter count).
*/
export function formatPoll(poll: PollData): string {
const lines: string[] = [];
lines.push(`\u{1F4CA} Poll: ${poll.question}`);
poll.options.forEach((opt, i) => {
const num = i + 1;
const correct = opt.correct ? ' \u2713' : '';
const votes = opt.voters > 0
? ` (${opt.voters} vote${opt.voters !== 1 ? 's' : ''})`
: '';
lines.push(` ${num}. ${opt.text}${correct}${votes}`);
});
const tags: string[] = [];
if (poll.isQuiz) tags.push('Quiz');
if (poll.isPublic) tags.push('Public');
if (poll.isMultiple) tags.push('Multiple');
if (poll.closePeriod) tags.push(`Closes in ${poll.closePeriod}s`);
if (poll.isClosed) {
tags.push('Closed');
tags.push(`${poll.totalVoters} voter${poll.totalVoters !== 1 ? 's' : ''}`);
}
if (tags.length > 0) {
lines.push(` ${tags.join(' \u00B7 ')}`);
}
return lines.join('\n');
}
/**
* Format a single message line in conversational style.
* [2026-03-11 12:30] Alice: Hello world
* [2026-03-11 12:31] Bob (reply to 42): Thanks!
* [2026-03-11 12:32] Alice: [photo 1920x1080 240KB] Check this out
*/
function formatSingleMessage(m: MessageItem): string {
const ts = pc.dim(`[${formatTimestamp(m.date)}]`);
const sender = pc.bold(m.senderName ?? 'Unknown');
const reply = m.replyToMsgId != null ? pc.dim(` (reply to ${m.replyToMsgId})`) : '';
const edited = m.editDate ? pc.dim(' (edited)') : '';
const annotation = formatMediaAnnotation(m);
const media = annotation ? pc.yellow(annotation) + ' ' : '';
let line = `${ts} ${sender}${reply}${edited}: ${media}${m.text}`;
if (m.poll) {
line += '\n' + formatPoll(m.poll);
}
return line;
}
/**
* Format a list of messages in conversational style.
* Each message on its own line with timestamp, sender, optional reply/media annotations.
*/
export function formatMessages(messages: MessageItem[]): string {
if (messages.length === 0) return '';
return messages.map(formatSingleMessage).join('\n');
}
/**
* Format a chat list in table format.
* [channel] My Channel @mychan
* [supergroup] Dev Group @devs (5 unread)
* [user] Alice @alice
*/
export function formatChatList(chats: ChatListItem[]): string {
if (chats.length === 0) return '';
// Determine max type length for alignment
const maxTypeLen = Math.max(...chats.map(c => c.type.length));
return chats.map(c => {
const typePad = c.type.padEnd(maxTypeLen);
const typeTag = pc.dim(`[${typePad}]`);
const title = pc.bold(c.title);
const username = c.username ? pc.dim(` @${c.username}`) : '';
const unread = c.unreadCount > 0 ? pc.yellow(` (${c.unreadCount} unread)`) : '';
return `${typeTag} ${title}${username}${unread}`;
}).join('\n');
}
/**
* Format chat info as key-value pairs.
* Title: My Channel
* Type: channel
* Username: @mychan
* Description: A test channel
* Members: 1,234
*/
export function formatChatInfo(info: ChatInfo): string {
const pairs: [string, string][] = [];
pairs.push(['Title', info.title]);
pairs.push(['Type', info.type]);
if (info.username != null) pairs.push(['Username', `@${info.username}`]);
if (info.description != null) pairs.push(['Description', info.description]);
if (info.memberCount != null) pairs.push(['Members', info.memberCount.toLocaleString()]);
if (info.creationDate != null) pairs.push(['Created', info.creationDate]);
if (info.linkedChatId != null) pairs.push(['Linked Chat', info.linkedChatId]);
if (info.slowmodeSeconds != null) pairs.push(['Slowmode', `${info.slowmodeSeconds}s`]);
if (info.inviteLink != null) pairs.push(['Invite Link', info.inviteLink]);
if (info.migratedFrom != null) pairs.push(['Migrated From', info.migratedFrom]);
const maxLabelLen = Math.max(...pairs.map(([label]) => label.length));
return pairs.map(([label, value]) => {
const paddedLabel = label.padEnd(maxLabelLen);
return `${pc.bold(paddedLabel)} ${value}`;
}).join('\n');
}
/**
* Format members list with name, username, and bot tag.
* Alice @alice
* Bob @bob [bot]
*/
export function formatMembers(members: Pick<MemberItem, 'firstName' | 'lastName' | 'username' | 'isBot'>[]): string {
if (members.length === 0) return '';
return members.map(m => {
const name = pc.bold([m.firstName, m.lastName].filter(Boolean).join(' ') || 'Unknown');
const username = m.username ? pc.dim(` @${m.username}`) : '';
const bot = m.isBot ? pc.cyan(' [bot]') : '';
return `${name}${username}${bot}`;
}).join('\n');
}
/**
* Format search results grouped by chat title.
* --- Dev Group ---
* [2026-03-11 12:30] Alice: found this
* --- General Chat ---
* [2026-03-11 12:35] Bob: also here
*/
export function formatSearchResults(results: SearchResultItem[]): string {
if (results.length === 0) return '';
// Group by chatTitle preserving order
const groups = new Map<string, SearchResultItem[]>();
for (const r of results) {
const existing = groups.get(r.chatTitle);
if (existing) {
existing.push(r);
} else {
groups.set(r.chatTitle, [r]);
}
}
const sections: string[] = [];
for (const [chatTitle, msgs] of groups) {
sections.push(pc.bold(`--- ${chatTitle} ---`));
for (const m of msgs) {
sections.push(formatSingleMessage(m));
}
}
return sections.join('\n');
}
/**
* Format a download result with path, filename, size, and type.
*/
export function formatDownloadResult(result: DownloadResult): string {
const lines = [
`${pc.bold('Downloaded:')} ${result.filename}`,
`${pc.bold('Path:')} ${pc.green(result.path)}`,
`${pc.bold('Size:')} ${formatBytes(result.size)}`,
`${pc.bold('Type:')} ${result.mediaType}`,
];
return lines.join('\n');
}
/**
* Format an upload/send result.
* Handles both single MessageItem (delegates to formatSingleMessage) and
* AlbumResult (header + each message formatted).
*/
export function formatUploadResult(result: AlbumResult | MessageItem): string {
// AlbumResult shape
if ('messages' in result && 'sent' in result) {
const album = result as AlbumResult;
const header = pc.bold(`Sent ${album.sent} files`);
const msgs = album.messages.map(formatSingleMessage).join('\n');
return `${header}\n${msgs}`;
}
// Single MessageItem
return formatSingleMessage(result);
}
/**
* Format forum topics as a human-readable list.
* Each topic shows its ID, title, and optional pinned/closed indicators.
* Example:
* 42 General Discussion [pinned]
* 43 Off Topic [closed]
* 44 Normal Topic
*/
export function formatTopics(topics: TopicItem[]): string {
if (topics.length === 0) return '';
// Determine max ID width for alignment
const maxIdLen = Math.max(...topics.map(t => String(t.id).length));
return topics.map(t => {
const idStr = String(t.id).padStart(maxIdLen);
const id = pc.dim(idStr);
const title = pc.bold(t.title);
const indicators: string[] = [];
if (t.isPinned) indicators.push(pc.cyan('[pinned]'));
if (t.isClosed) indicators.push(pc.yellow('[closed]'));
const suffix = indicators.length > 0 ? ' ' + indicators.join(' ') : '';
return ` ${id} ${title}${suffix}`;
}).join('\n');
}
/**
* Format a get-by-ID result with messages and a not-found footer.
* Renders found messages with formatMessages, appends dim "Not found: ..." line.
*/
export function formatGetResult(data: { messages: MessageItem[]; notFound: number[] }): string {
const parts: string[] = [];
if (data.messages.length > 0) {
parts.push(formatMessages(data.messages));
} else {
parts.push('No messages found.');
}
if (data.notFound.length > 0) {
parts.push(pc.dim('Not found: ' + data.notFound.join(', ')));
}
return parts.join('\n');
}
/**
* Format a delete result with count, mode, and any failed entries.
* "Deleted 3 messages (revoke)." or "Failed: 42 (permission denied)"
*/
export function formatDeleteResult(result: DeleteResult): string {
const parts: string[] = [];
if (result.deleted.length > 0) {
parts.push(`Deleted ${result.deleted.length} message${result.deleted.length > 1 ? 's' : ''} (${result.mode}).`);
}
for (const f of result.failed) {
parts.push(pc.red(`Failed: ${f.id} (${f.reason})`));
}
if (parts.length === 0) {
parts.push('No messages deleted.');
}
return parts.join('\n');
}
/**
* Format a pin/unpin result with action, message ID, chat ID, and silent indicator.
* "Pinned message 456 in @group (silent)" or "Unpinned message 456 in @group"
*/
export function formatPinResult(result: PinResult): string {
const action = result.action === 'pinned' ? 'Pinned' : 'Unpinned';
const suffix = result.action === 'pinned'
? (result.silent ? ' (silent)' : ' (notified)')
: '';
return `${action} message ${result.messageId} in ${result.chatId}${suffix}`;
}
/**
* Format user profiles as aligned key-value pairs with color-coded status.
*
* Each profile displays: Name, ID, Username, Phone, Bio, Last Seen,
* Photos, Common Chats, and conditional flags (Blocked, Premium, Verified, Bot).
* Multiple profiles separated by blank lines.
* Appends dim "Not found: ..." for any unresolved inputs.
*/
export function formatUserProfile(profiles: UserProfile[], notFound: string[]): string {
const parts: string[] = [];
for (const p of profiles) {
const pairs: [string, string][] = [];
const name = [p.firstName, p.lastName].filter(Boolean).join(' ') || 'Unknown';
pairs.push(['Name', name]);
pairs.push(['ID', p.id]);
if (p.username != null) pairs.push(['Username', `@${p.username}`]);
// Phone: restricted indicator rendered dim
if (p.phone === '[restricted]') {
pairs.push(['Phone', pc.dim('[restricted]')]);
} else if (p.phone != null) {
pairs.push(['Phone', p.phone]);
}
if (p.bio != null) pairs.push(['Bio', p.bio]);
// Last Seen: color-coded by status
if (p.lastSeen != null) {
let lastSeenFormatted: string;
if (p.lastSeen === 'online') {
lastSeenFormatted = pc.green('online');
} else if (['recently', 'within_week', 'within_month', 'long_time_ago'].includes(p.lastSeen)) {
lastSeenFormatted = pc.dim(p.lastSeen.replace(/_/g, ' '));
} else {
// ISO timestamp
lastSeenFormatted = p.lastSeen;
}
pairs.push(['Last Seen', lastSeenFormatted]);
}
pairs.push(['Photos', String(p.photoCount)]);
pairs.push(['Common Chats', String(p.commonChatsCount)]);
// Conditional flags
if (p.blocked) pairs.push(['Blocked', pc.red('yes')]);
if (p.premium) pairs.push(['Premium', pc.yellow('yes')]);
if (p.verified) pairs.push(['Verified', pc.cyan('yes')]);
if (p.mutualContact) pairs.push(['Mutual Contact', 'yes']);
if (p.isBot) {
pairs.push(['Bot', pc.cyan('yes')]);
if (p.supportsInline) pairs.push(['Inline', 'yes']);
if (p.botInlinePlaceholder) pairs.push(['Placeholder', p.botInlinePlaceholder]);
}
if (p.langCode != null) pairs.push(['Language', p.langCode]);
const maxLabelLen = Math.max(...pairs.map(([label]) => label.length));
const section = pairs.map(([label, value]) => {
const paddedLabel = label.padEnd(maxLabelLen);
return `${pc.bold(paddedLabel)} ${value}`;
}).join('\n');
parts.push(section);
}
if (notFound.length > 0) {
parts.push(pc.dim('Not found: ' + notFound.join(', ')));
}
return parts.join('\n\n');
}
/**
* Format a blocked user list.
* Empty list returns 'No blocked users.'.
* Non-empty list delegates to formatMembers (BlockedListItem is MemberItem-compatible).
*/
export function formatBlockedList(users: BlockedListItem[]): string {
if (users.length === 0) return 'No blocked users.';
return formatMembers(users);
}
/**
* Format a contact list for human-readable output.
* Empty list returns 'No contacts.'.
* Delegates to formatMembers for compact name + username + bot tag display.
*/
export function formatContactList(contacts: UserProfile[]): string {
if (contacts.length === 0) return 'No contacts.';
return formatMembers(contacts);
}
/**
* Format contact search results for human-readable output.
* Empty list returns 'No results.'.
* Each result shows name, username, and [contact] tag for contacts.
*/
export function formatContactSearch(results: (UserProfile & { isContact: boolean })[]): string {
if (results.length === 0) return 'No results.';
return results.map(r => {
const name = pc.bold([r.firstName, r.lastName].filter(Boolean).join(' ') || 'Unknown');
const username = r.username ? pc.dim(` @${r.username}`) : '';
const bot = r.isBot ? pc.cyan(' [bot]') : '';
const contact = r.isContact ? pc.green(' [contact]') : '';
return `${name}${username}${bot}${contact}`;
}).join('\n');
}
/**
* Fallback formatter: pretty-prints any data as indented JSON.
* Used for auth status, session export/import, join/leave confirmations, etc.
*/
export function formatGeneric(data: unknown): string {
return JSON.stringify(data, null, 2);
}
/**
* Auto-detect data shape and dispatch to the appropriate formatter.
*
* Detection order:
* 1. .messages[] with .chatTitle -> formatSearchResults
* 2. .messages[] with .text and .date -> formatMessages
* 3. .chats[] with .type and .title -> formatChatList
* 4. .title + .type + .memberCount (ChatInfo) -> formatChatInfo
* 5. .members[] with .isBot -> formatMembers
* 6. Default -> formatGeneric
*/
export function formatData(data: unknown): string {
if (data == null || typeof data !== 'object') {
return formatGeneric(data);
}
const obj = data as Record<string, any>;
if (typeof obj.scheduledAt === 'string' && 'text' in obj && 'date' in obj) {
return `Scheduled for ${obj.scheduledAt}\n${formatMessages([obj as MessageItem])}`;
}
if (Array.isArray(obj.errors)) {
const { errors, partial: _partial, ...successfulData } = obj;
const formatted = formatData(successfulData);
const failures = errors.map((failure: { input: string; error: string; code: string }) =>
`Failed ${failure.input}: ${failure.error} [${failure.code}]`,
);
return [formatted, ...failures].filter(Boolean).join('\n');
}
// Check for UserProfileResult shape (profiles[] + notFound[])
if (Array.isArray(obj.profiles) && Array.isArray(obj.notFound)) {
return formatUserProfile(obj.profiles as UserProfile[], obj.notFound as string[]);
}
// Check for ContactListResult shape (contacts[] + total number)
if (Array.isArray(obj.contacts) && typeof obj.total === 'number') {
return formatContactList(obj.contacts as UserProfile[]);
}
// Check for ContactSearchResult shape (results[] + total number)
if (Array.isArray(obj.results) && typeof obj.total === 'number') {
return formatContactSearch(obj.results as (UserProfile & { isContact: boolean })[]);
}
// Check for ContactDeleteResult shape (userId + action === 'deleted')
if ('userId' in obj && 'action' in obj && obj.action === 'deleted') {
const name = obj.firstName || obj.username || obj.userId;
return `Deleted contact ${name}`;
}
// Check for BlockedListResult shape (users[] + total number, first item has isBot)
if (Array.isArray(obj.users) && typeof obj.total === 'number') {
if (obj.users.length === 0) return 'No blocked users.';
if ('isBot' in obj.users[0]) {
return formatMembers(obj.users as BlockedListItem[]);
}
}
// Check for BlockResult shape (userId + action blocked/unblocked)
if ('userId' in obj && 'action' in obj && (obj.action === 'blocked' || obj.action === 'unblocked')) {
const name = (obj as any).firstName || (obj as any).username || (obj as any).userId;
return `${obj.action === 'blocked' ? 'Blocked' : 'Unblocked'} ${name}`;
}
if (obj.personal === true && 'photoId' in obj && 'userId' in obj) {
return `Set personal photo ${obj.photoId} for ${obj.userId} (visible only to you)`;
}
if (obj.profilePhoto === true && 'path' in obj && 'userId' in obj) {
return `Downloaded profile photo for ${obj.userId}: ${obj.path} (${obj.size} bytes)`;
}
// Check for DownloadResult shape (has path + filename + size + mediaType + messageId)
if ('path' in obj && 'filename' in obj && 'size' in obj && 'mediaType' in obj && 'messageId' in obj) {
return formatDownloadResult(obj as DownloadResult);
}
// Check for batch download shape (has files[] + downloaded count)
if (Array.isArray(obj.files) && 'downloaded' in obj) {
const header = pc.bold(`Downloaded ${obj.downloaded} files`);
const items = (obj.files as DownloadResult[]).map(f => formatDownloadResult(f)).join('\n\n');
return `${header}\n\n${items}`;
}
// Check for AlbumResult shape (messages[] + sent number) - before generic messages check
if (Array.isArray(obj.messages) && typeof obj.sent === 'number') {
return formatUploadResult(obj as AlbumResult);
}
// Check for single MessageItem at top level (e.g. from send command)
if ('id' in obj && 'text' in obj && 'date' in obj && 'type' in obj && !('messages' in obj) && !('chats' in obj)) {
return formatMessages([obj as MessageItem]);
}
// Check for get-by-ID result shape (messages[] + notFound[]) — BEFORE generic messages check
// to avoid notFound being silently dropped
if (Array.isArray(obj.messages) && Array.isArray(obj.notFound)) {
return formatGetResult(obj as { messages: MessageItem[]; notFound: number[] });
}
// Check for messages array
if (Array.isArray(obj.messages)) {
if (obj.messages.length === 0) return 'No messages.';
const first = obj.messages[0];
if ('chatTitle' in first) {
return formatSearchResults(obj.messages as SearchResultItem[]);
}
if ('text' in first && 'date' in first) {
return formatMessages(obj.messages as MessageItem[]);
}
}
// Check for chats array
if (Array.isArray(obj.chats)) {
if (obj.chats.length === 0) return 'No chats.';
const first = obj.chats[0];
if ('type' in first && 'title' in first) {
return formatChatList(obj.chats as ChatListItem[]);
}
}
// Check for ChatInfo shape (has title + type + memberCount at top level)
if ('title' in obj && 'type' in obj && 'memberCount' in obj) {
return formatChatInfo(obj as ChatInfo);
}
// Check for topics array (forum topics)
if (Array.isArray(obj.topics)) {
if (obj.topics.length === 0) return 'No topics.';
const first = obj.topics[0];
if ('title' in first && 'isClosed' in first) {
return formatTopics(obj.topics as TopicItem[]);
}
}
// Check for members array
if (Array.isArray(obj.members)) {
if (obj.members.length === 0) return 'No members.';
const first = obj.members[0];
if ('isBot' in first) {
return formatMembers(obj.members as MemberItem[]);
}
}
// Check for DeleteResult shape (has deleted[] + mode)
if (Array.isArray(obj.deleted) && 'mode' in obj) {
return formatDeleteResult(obj as DeleteResult);
}
// Check for PinResult shape (has action pinned/unpinned + messageId, but NOT emoji to avoid react conflict)
if ('action' in obj && 'messageId' in obj && !('emoji' in obj) &&
(obj.action === 'pinned' || obj.action === 'unpinned')) {
return formatPinResult(obj as PinResult);
}
// Fallback
return formatGeneric(data);
}

View file

@ -0,0 +1,32 @@
import { Logger, LogLevel } from 'teleproto/extensions/Logger.js';
import { isQuietMode, isVerboseMode } from './cli-mode.js';
/** Keep gramjs diagnostics on stderr, including its constructor banner. */
class GramjsLogger extends Logger {
constructor(private readonly sensitiveValues: readonly string[]) {
super(LogLevel.DEBUG);
}
override canSend(level: LogLevel): boolean {
if (isQuietMode() || level === LogLevel.NONE) return false;
if (!isVerboseMode() && level !== LogLevel.WARN && level !== LogLevel.ERROR) return false;
return super.canSend(level);
}
override log(level: LogLevel, message: string, _color: string): void {
if (!this.canSend(level)) return;
// These SDK diagnostics include raw response bytes, which can contain
// account data. A protocol failure does not require dumping its payload.
let safeMessage = String(message)
.replace(/(remaining data|Received response without parent request:)[\s\S]*/i, '$1 [redacted]');
for (const secret of this.sensitiveValues) {
if (secret) safeMessage = safeMessage.split(secret).join('[redacted]');
}
process.stderr.write(`[gramjs ${level}] ${safeMessage}\n`);
}
}
/** Pass as baseLogger when constructing every TelegramClient. */
export function createGramjsLogger(sensitiveValues: readonly string[] = []): Logger {
return new GramjsLogger(sensitiveValues);
}

View file

@ -0,0 +1,99 @@
import { Api } from 'teleproto';
/**
* Map of user-facing filter names to factory functions that create
* gramjs InputMessagesFilter instances for search filtering.
*
* Factory functions ensure a fresh instance per call (gramjs mutates filter objects).
*/
export const FILTER_MAP: Record<string, () => InstanceType<any>> = {
photos: () => new Api.InputMessagesFilterPhotos(),
videos: () => new Api.InputMessagesFilterVideo(),
photo_video: () => new Api.InputMessagesFilterPhotoVideo(),
documents: () => new Api.InputMessagesFilterDocument(),
urls: () => new Api.InputMessagesFilterUrl(),
gifs: () => new Api.InputMessagesFilterGif(),
voice: () => new Api.InputMessagesFilterVoice(),
music: () => new Api.InputMessagesFilterMusic(),
round: () => new Api.InputMessagesFilterRoundVideo(),
round_voice: () => new Api.InputMessagesFilterRoundVoice(),
chat_photos: () => new Api.InputMessagesFilterChatPhotos(),
phone_calls: () => new Api.InputMessagesFilterPhoneCalls({ missed: false }),
mentions: () => new Api.InputMessagesFilterMyMentions(),
geo: () => new Api.InputMessagesFilterGeo(),
contacts: () => new Api.InputMessagesFilterContacts(),
pinned: () => new Api.InputMessagesFilterPinned(),
};
/**
* Array of valid filter names for validation and help text.
*/
export const VALID_FILTERS: string[] = Object.keys(FILTER_MAP);
/**
* MIME type to file extension map for auto-naming downloaded files.
*/
const MIME_EXT_MAP: Record<string, string> = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/webp': '.webp',
'image/bmp': '.bmp',
'video/mp4': '.mp4',
'video/quicktime': '.mov',
'video/x-msvideo': '.avi',
'video/x-matroska': '.mkv',
'video/webm': '.webm',
'audio/ogg': '.ogg',
'audio/mpeg': '.mp3',
'audio/opus': '.opus',
};
/**
* Generate an auto-name for a downloaded media file.
*
* Format: {mediaType}_{msgId}{ext}
* Extension derived from MIME type; falls back to .bin.
*/
export function generateFilename(
mediaType: string,
msgId: number,
mimeType: string | null,
): string {
const ext = mimeType ? (MIME_EXT_MAP[mimeType] ?? '.bin') : '.bin';
return `${mediaType}_${msgId}${ext}`;
}
/**
* Extension sets for file type classification.
*/
const PHOTO_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']);
const VIDEO_EXTS = new Set(['.mp4', '.mov', '.avi', '.mkv', '.webm']);
const VOICE_EXTS = new Set(['.ogg', '.opus']);
/**
* Classify a file by its extension for upload type detection.
*/
export function detectFileType(
ext: string,
): 'photo' | 'video' | 'voice' | 'document' {
const lower = ext.toLowerCase();
if (PHOTO_EXTS.has(lower)) return 'photo';
if (VIDEO_EXTS.has(lower)) return 'video';
if (VOICE_EXTS.has(lower)) return 'voice';
return 'document';
}
/**
* Format a byte count as a human-readable string.
*
* <1024 -> NB, <1MB -> NKB (rounded), <1GB -> N.NMB, else N.NGB
*/
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes}B`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`;
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
}

Some files were not shown because too many files have changed in this diff Show more