better-tg-cli 0.38.1 → 0.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.es.md CHANGED
@@ -58,10 +58,10 @@ Un fork de [skillhq/telegram](https://github.com/skillhq/telegram), rehecho para
58
58
  - **Lecturas exactas.** Paginación real para `--since/--until`, `--unread`, hilos y comentarios de
59
59
  canales, temas de foros, `get` por ID, filtros de búsqueda por tipo, remitente o fecha, y `me` /
60
60
  `Избранное` para los Mensajes guardados.
61
- - **Seguro por defecto.** La cuenta es de solo lectura hasta que una persona ejecuta
62
- `write-access on [--for 1h]` y lo confirma en un prompt del terminal o en un diálogo de macOS, así
63
- que un agente no puede activarlo por su cuenta. Cada escritura se registra en
64
- `~/.config/tg/audit.jsonl`. Los secretos se guardan en el Keychain de macOS, en el Secret Service
61
+ - **Tú apruebas cada mensaje.** Tras iniciar sesión, el agente te pregunta en el chat antes de
62
+ cada envío, edición o borrado y te muestra el texto exacto; solo envía tras tu sí. Escribir sin
63
+ preguntar (`write-access on`) requiere tu propia confirmación en un terminal o en un diálogo de
64
+ macOS. Cada escritura se registra en `~/.config/tg/audit.jsonl`. Los secretos se guardan en el Keychain de macOS, en el Secret Service
65
65
  de Linux o en 1Password.
66
66
  - **Pequeño y autónomo.** El paquete de npm es un único archivo de 0,3 MB sin dependencias en tiempo
67
67
  de ejecución. Homebrew instala un binario independiente que no necesita Node.
@@ -196,8 +196,10 @@ La sesión se guarda en el Keychain de macOS (servicio `tg-cli`) o en 1Password
196
196
  `--op-vault <vault>`. `telegram logout` la elimina. En Linux va al Secret Service (GNOME Keyring,
197
197
  KWallet, KeePassXC) a través de `secret-tool`, que necesita el paquete `libsecret-tools`. Una sesión
198
198
  ya guardada en el archivo de configuración se traslada allí automáticamente. Sin ningún almacén de
199
- secretos, la sesión se guarda en `~/.config/tg/config.json5` (modo 0600) y los comandos de escritura
200
- siguen desactivados. En Linux, `write-access on` se confirma en un prompt del terminal. En Windows los
199
+ secretos, la sesión se guarda en `~/.config/tg/config.json5` (modo 0600). En Linux sin un Secret
200
+ Service que funcione (sin `secret-tool` o sin bus de sesión, como en los ordenadores de agentes en la
201
+ nube) el modo de escritura también se guarda en un archivo normal del perfil, que protege de errores
202
+ pero no de un agente que pueda editar archivos. En Linux, `write-access on` se confirma en un prompt del terminal. En Windows los
201
203
  secretos se guardan en `%APPDATA%\tg\secrets.dpapi`, cifrados con DPAPI para tu usuario de Windows
202
204
  (solo tú puedes descifrarlos en esta máquina), y `write-access on` pregunta en una ventana Sí/No
203
205
  cuando no hay terminal.
@@ -213,7 +215,8 @@ telegram get "Chat" 812 813 # mensajes exactos por ID
213
215
  telegram download "Chat" 812 # guarda el archivo adjunto
214
216
  telegram sync --chat "Chat" --output ./export --resume # exportación incremental a markdown
215
217
 
216
- telegram write-access on --for 1h # esto lo confirma una persona
218
+ telegram write-access ask # cada escritura espera tu sí en el chat (por defecto tras onboard)
219
+ telegram write-access on --for 1h # o: escribir sin preguntar durante una hora
217
220
  telegram send @alice "on my way"
218
221
  printf '%s' "$text" | telegram send @alice - # texto largo o de varias líneas: desde stdin, sin problemas de comillas
219
222
  telegram reply "Chat" 812 "on it" --silent
@@ -281,12 +284,120 @@ telegram mcp --http --read-only # escucha en 127.0.0.1:8787; quita -
281
284
  tailscale funnel --bg 8787 # o: cloudflared tunnel --url http://127.0.0.1:8787
282
285
  ```
283
286
 
284
- Mantén el servidor y el túnel en un terminal o en tmux. Después añade un conector en Grok Bot con la
287
+ Mantén el servidor y el túnel en un terminal o en tmux, o ejecuta el servidor como servicio en
288
+ segundo plano (abajo). Después añade un conector en Grok Bot con la
285
289
  URL del túnel más `/mcp` (por ejemplo `https://<machine>.<tailnet>.ts.net/mcp`) y la cabecera
286
290
  `Authorization: Bearer <token>`. `tailscale funnel` da una URL estable, pero antes hay que permitirlo
287
291
  para tu tailnet. Un túnel rápido de `cloudflared` obtiene una URL nueva en cada arranque. Lee antes
288
292
  "Remote MCP over HTTP" en [SECURITY.md](SECURITY.md).
289
293
 
294
+ #### El servidor como servicio en segundo plano
295
+
296
+ Un servicio arranca el servidor por sí solo y lo vuelve a levantar tras un fallo. En macOS el
297
+ LaunchAgent de abajo arranca al iniciar sesión y funciona mientras sigues con la sesión iniciada. En
298
+ Linux la unidad de usuario también puede arrancar al encender, sin iniciar sesión (ver linger
299
+ abajo). Ninguno de los archivos de abajo guarda secretos: la sesión y el token bearer siguen en el Keychain o en el
300
+ Secret Service, y el servidor los lee al arrancar. El túnel también tiene que seguir activo:
301
+ `tailscale funnel --bg` sigue funcionando por sí solo, un túnel rápido de `cloudflared` no.
302
+
303
+ Ambos archivos necesitan las rutas que imprimen `command -v telegram` y, tras instalar con npm,
304
+ `command -v node`. La versión npm de `telegram` es un script de Node, y un servicio arranca con un
305
+ `PATH` corto sin los directorios de Homebrew ni de nvm, así que sin el `PATH` correcto termina con
306
+ `env: node: No such file or directory`.
307
+
308
+ **macOS (launchd).** Guarda esto como `~/Library/LaunchAgents/com.better-tg-cli.mcp.plist`, con tu
309
+ ruta a `telegram` en `ProgramArguments`, el directorio de `node` en `PATH` y tu nombre de usuario
310
+ (`id -un`) en lugar de `you` (launchd no expande ni `~` ni `$HOME`):
311
+
312
+ ```xml
313
+ <?xml version="1.0" encoding="UTF-8"?>
314
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
315
+ <plist version="1.0">
316
+ <dict>
317
+ <key>Label</key>
318
+ <string>com.better-tg-cli.mcp</string>
319
+ <key>ProgramArguments</key>
320
+ <array>
321
+ <string>/opt/homebrew/bin/telegram</string>
322
+ <string>mcp</string>
323
+ <string>--http</string>
324
+ <string>--read-only</string>
325
+ </array>
326
+ <key>EnvironmentVariables</key>
327
+ <dict>
328
+ <key>PATH</key>
329
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
330
+ <key>TG_NO_UPDATE_CHECK</key>
331
+ <string>1</string>
332
+ </dict>
333
+ <key>RunAtLoad</key>
334
+ <true/>
335
+ <key>KeepAlive</key>
336
+ <dict>
337
+ <key>SuccessfulExit</key>
338
+ <false/>
339
+ </dict>
340
+ <key>StandardOutPath</key>
341
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
342
+ <key>StandardErrorPath</key>
343
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
344
+ </dict>
345
+ </plist>
346
+ ```
347
+
348
+ ```bash
349
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.better-tg-cli.mcp.plist
350
+ launchctl print gui/$(id -u)/com.better-tg-cli.mcp | grep -E 'state|last exit'
351
+ launchctl kickstart -k gui/$(id -u)/com.better-tg-cli.mcp # reiniciar
352
+ launchctl bootout gui/$(id -u)/com.better-tg-cli.mcp # detener y descargar
353
+ ```
354
+
355
+ `KeepAlive` con `SuccessfulExit` false reinicia el servidor cuando falla o lo matan. Si macOS pide
356
+ acceso al Keychain en el primer arranque, permítelo.
357
+
358
+ **Linux (unidad de usuario de systemd).** Guarda esto como
359
+ `~/.config/systemd/user/better-tg-cli-mcp.service`, con los directorios de `telegram` y `node` en
360
+ `PATH`:
361
+
362
+ ```ini
363
+ [Unit]
364
+ Description=Better-TG-CLI MCP server over HTTP
365
+ After=network-online.target
366
+
367
+ [Service]
368
+ Environment=PATH=/usr/local/bin:/usr/bin:/bin
369
+ Environment=TG_NO_UPDATE_CHECK=1
370
+ ExecStart=/usr/bin/env telegram mcp --http --read-only
371
+ Restart=on-failure
372
+ RestartSec=5
373
+
374
+ [Install]
375
+ WantedBy=default.target
376
+ ```
377
+
378
+ ```bash
379
+ systemctl --user daemon-reload
380
+ systemctl --user enable --now better-tg-cli-mcp.service
381
+ systemctl --user status better-tg-cli-mcp.service
382
+ journalctl --user -u better-tg-cli-mcp.service -f
383
+ ```
384
+
385
+ La unidad funciona mientras tienes la sesión iniciada. `sudo loginctl enable-linger "$USER"` la
386
+ arranca al encender y la mantiene tras cerrar sesión, pero no desbloquea el llavero. Si el servicio
387
+ no tiene Secret Service o está bloqueado, el servidor termina con "The HTTP server needs a secret
388
+ store for its token" y systemd lo vuelve a arrancar 5 segundos después. Para ver qué almacén de
389
+ secretos encuentra el servicio, ejecuta `telegram check` con el entorno de la unidad.
390
+
391
+ Si el servicio no tiene Secret Service (por ejemplo, en un servidor sin escritorio), usa el almacén
392
+ de 1Password. Inicia sesión una vez con `telegram auth --op-vault <vault>` en el mismo perfil, añade
393
+ el directorio de `op` al `PATH` de la unidad y guarda `OP_SERVICE_ACCOUNT_TOKEN=…` en un archivo que
394
+ solo tú puedas leer (modo 0600), cargado con `EnvironmentFile=%h/.config/tg/mcp.env` en
395
+ `[Service]`. Ese token es un secreto, así que no va en la unidad.
396
+
397
+ Tras `telegram mcp --rotate-token`, reinicia el servicio (`launchctl kickstart -k …` o
398
+ `systemctl --user restart better-tg-cli-mcp`): hasta entonces el servidor en marcha acepta el token
399
+ antiguo.
400
+
290
401
  ## FAQ
291
402
 
292
403
  **¿Telegram baneará mi cuenta?**
@@ -296,7 +407,7 @@ Usar tu propia cuenta desde un cliente de terceros está permitido por los [tér
296
407
  No. Inicia sesión como tú por MTProto, igual que Telegram Desktop, y ve exactamente lo que ves tú. Los bots no pueden leer tus chats; esto sí.
297
408
 
298
409
  **¿Puede un agente enviar mensajes por su cuenta?**
299
- Solo después de que actives la escritura. `telegram write-access on` te pide que lo confirmes en el terminal o en un diálogo de macOS, algo que un agente no puede responder. A partir de ahí, las escrituras necesitan un chat exacto y cada una queda registrada. Por MCP, escribir es una herramienta aparte que los clientes pueden pedirte que apruebes cada vez. Los detalles están en [SECURITY.md](SECURITY.md).
410
+ No debería. Tras iniciar sesión el perfil está en modo `ask`: antes de cada escritura el agente te muestra en el chat la acción exacta y solo la envía tras tu sí, y el código que recibe por ese sí funciona una vez y solo para ese texto. Por MCP, los clientes que admiten elicitation te preguntan en su propio diálogo. Todo esto depende de que el agente siga sus instrucciones: un agente con una terminal en tu usuario puede leer la sesión del Keychain y actuar en tu nombre, así que dale solo chats de confianza o conéctalo solo por MCP. `write-access on` (sin preguntar) requiere tu confirmación en un terminal o en un diálogo de macOS. Más detalles en [SECURITY.md](SECURITY.md).
300
411
 
301
412
  **¿Leer marca los mensajes como leídos?**
302
413
  No. `read`, `inbox` y `search` dejan los chats sin leer. Solo `telegram mark-read` los marca.
@@ -318,6 +429,9 @@ Linux. Por favor, informa de los problemas en los issues.
318
429
  **¿Puedo usarlo desde Grok Bot, ChatGPT u otro agente en la nube?**
319
430
  Los agentes en la nube no pueden iniciar un programa en tu ordenador, así que ejecuta el servidor MCP por HTTP y accede a él a través de un túnel. Consulta [Grok Bot](#grok-bot-mcp-remoto-por-http).
320
431
 
432
+ **¿Cómo permito escribir en Grok Bot u otro agente en la nube?**
433
+ Tras `telegram onboard` ya está en modo `ask`: el agente te pregunta en el chat antes de cada escritura. Si dice que la escritura está desactivada, pídele que ejecute `telegram write-access ask`; ahí funciona tal cual. Solo `telegram write-access on --for 1h` (sin preguntar) necesita tu elección: esos ordenadores no tienen almacén de secretos ni una terminal para ti, así que abre una página en el navegador del propio agente donde eliges. Ejecutarlo en tu terminal no sirve: cambia la CLI de tu ordenador, no la del agente. El agente no debe intentar instalar un llavero allí: sin sesión de escritorio no funciona. En esos ordenadores el ajuste está en un archivo normal, que protege de errores pero no de un agente malicioso.
434
+
321
435
  **El inicio de sesión falla con «NetSocket was closed» en un ordenador en la nube (Grok Bot y otros).**
322
436
  Algunos ordenadores de agentes en la nube solo dejan salir HTTPS, y eso corta el transporte TCP de Telegram. La CLI cambia entonces sola a MTProto sobre WebSocket (`wss://*.web.telegram.org`, el transporte de web.telegram.org) y lo recuerda para el perfil. `TG_TRANSPORT=tcp|wss|auto` elige el transporte a mano.
323
437
 
package/README.md CHANGED
@@ -57,9 +57,10 @@ A fork of [skillhq/telegram](https://github.com/skillhq/telegram), reworked for
57
57
  - **Exact reads.** Real pagination for `--since/--until`, `--unread`, threads and channel
58
58
  comments, forum topics, `get` by ID, search filters by type, sender or date, and `me` / `Избранное`
59
59
  for Saved Messages.
60
- - **Safe by default.** The account is read-only until a human runs `write-access on [--for 1h]`
61
- and confirms it in a terminal prompt or a macOS dialog, so an agent cannot switch it on itself.
62
- Every write is logged to `~/.config/tg/audit.jsonl`. Secrets live in the macOS Keychain, the
60
+ - **You approve every message.** After login the agent asks you in the chat before each send,
61
+ edit or delete, and shows the exact text; it sends only after your yes. Writing without asking
62
+ (`write-access on`) needs your own confirmation in a terminal or a macOS dialog. Every write is
63
+ logged to `~/.config/tg/audit.jsonl`. Secrets live in the macOS Keychain, the
63
64
  Linux Secret Service or 1Password.
64
65
  - **Small and self-contained.** The npm package is one 0.3 MB file with zero runtime
65
66
  dependencies. Homebrew installs a standalone binary with no Node.
@@ -188,8 +189,10 @@ The session is stored in the macOS Keychain (service `tg-cli`), or in 1Password
188
189
  `--op-vault <vault>`. `telegram logout` removes it. On Linux it goes to the Secret Service (GNOME
189
190
  Keyring, KWallet, KeePassXC) through `secret-tool`, which needs the `libsecret-tools` package. A
190
191
  session already saved in the config file moves there automatically. Without any secret store, the
191
- session is kept in `~/.config/tg/config.json5` (mode 0600) and write commands stay disabled.
192
- On Linux, `write-access on` is confirmed at a terminal prompt. On Windows the secrets live in
192
+ session is kept in `~/.config/tg/config.json5` (mode 0600). On Linux without a working Secret
193
+ Service (no `secret-tool` or no session bus, as on cloud agent computers) the write mode is then kept
194
+ in a plain file in the profile too, which guards against mistakes, not against an agent that can
195
+ edit files. On Linux, `write-access on` is confirmed at a terminal prompt. On Windows the secrets live in
193
196
  `%APPDATA%\tg\secrets.dpapi`, encrypted with DPAPI for your Windows user (only you on this machine
194
197
  can decrypt it), and `write-access on` asks in a Yes/No window when there's no terminal.
195
198
 
@@ -212,7 +215,8 @@ telegram stats "Mock News" --graphs # full channel stats + growth grap
212
215
  telegram sessions ; telegram stars # active login sessions; Telegram Stars balance & transactions
213
216
  telegram invites "Team" --requests # a chat's invite links, or its pending join requests
214
217
 
215
- telegram write-access on --for 1h # a human confirms this
218
+ telegram write-access ask # each write waits for your yes in the chat (default after onboard)
219
+ telegram write-access on --for 1h # or: writes without asking, for an hour
216
220
  telegram send @alice "on my way"
217
221
  printf '%s' "$text" | telegram send @alice - # long or multi-line text: from stdin, no quoting problems
218
222
  telegram reply "Chat" 812 "on it" --silent
@@ -300,12 +304,117 @@ telegram mcp --http --read-only # listens on 127.0.0.1:8787; drop --
300
304
  tailscale funnel --bg 8787 # or: cloudflared tunnel --url http://127.0.0.1:8787
301
305
  ```
302
306
 
303
- Keep the server and the tunnel in a terminal or tmux. Then add a connector in Grok Bot with the
307
+ Keep the server and the tunnel in a terminal or tmux, or run the server as a background service
308
+ (below). Then add a connector in Grok Bot with the
304
309
  tunnel URL plus `/mcp` (for example `https://<machine>.<tailnet>.ts.net/mcp`) and the header
305
310
  `Authorization: Bearer <token>`. `tailscale funnel` gives a stable URL, but it has to be allowed
306
311
  for your tailnet first. A `cloudflared` quick tunnel gets a new URL on every start. Read "Remote
307
312
  MCP over HTTP" in [SECURITY.md](SECURITY.md) first.
308
313
 
314
+ #### Running the server as a background service
315
+
316
+ A service starts the server on its own and brings it back after a crash. On macOS the LaunchAgent
317
+ below starts when you log in and runs while you stay logged in. On Linux the user unit can also
318
+ start at boot without a login (see linger below). Neither file below holds a secret: the session and the bearer token stay in the Keychain or the Secret Service, and the server
319
+ reads them when it starts. The tunnel has to stay up as well: `tailscale funnel --bg` keeps running
320
+ by itself, a `cloudflared` quick tunnel does not.
321
+
322
+ Both files need the paths that `command -v telegram` and, after an npm install, `command -v node`
323
+ print. The npm build of `telegram` is a Node script, and a service starts with a short `PATH`
324
+ without Homebrew's or nvm's directories, so without the right `PATH` it exits with
325
+ `env: node: No such file or directory`.
326
+
327
+ **macOS (launchd).** Save this as `~/Library/LaunchAgents/com.better-tg-cli.mcp.plist`, with your
328
+ path to `telegram` in `ProgramArguments`, the directory of `node` in `PATH`, and your user name
329
+ (`id -un`) where `you` is (launchd expands neither `~` nor `$HOME`):
330
+
331
+ ```xml
332
+ <?xml version="1.0" encoding="UTF-8"?>
333
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
334
+ <plist version="1.0">
335
+ <dict>
336
+ <key>Label</key>
337
+ <string>com.better-tg-cli.mcp</string>
338
+ <key>ProgramArguments</key>
339
+ <array>
340
+ <string>/opt/homebrew/bin/telegram</string>
341
+ <string>mcp</string>
342
+ <string>--http</string>
343
+ <string>--read-only</string>
344
+ </array>
345
+ <key>EnvironmentVariables</key>
346
+ <dict>
347
+ <key>PATH</key>
348
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
349
+ <key>TG_NO_UPDATE_CHECK</key>
350
+ <string>1</string>
351
+ </dict>
352
+ <key>RunAtLoad</key>
353
+ <true/>
354
+ <key>KeepAlive</key>
355
+ <dict>
356
+ <key>SuccessfulExit</key>
357
+ <false/>
358
+ </dict>
359
+ <key>StandardOutPath</key>
360
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
361
+ <key>StandardErrorPath</key>
362
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
363
+ </dict>
364
+ </plist>
365
+ ```
366
+
367
+ ```bash
368
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.better-tg-cli.mcp.plist
369
+ launchctl print gui/$(id -u)/com.better-tg-cli.mcp | grep -E 'state|last exit'
370
+ launchctl kickstart -k gui/$(id -u)/com.better-tg-cli.mcp # restart
371
+ launchctl bootout gui/$(id -u)/com.better-tg-cli.mcp # stop and unload
372
+ ```
373
+
374
+ `KeepAlive` with `SuccessfulExit` false restarts the server whenever it fails or is killed. If macOS
375
+ asks for Keychain access on the first start, allow it.
376
+
377
+ **Linux (systemd user unit).** Save this as `~/.config/systemd/user/better-tg-cli-mcp.service`, with
378
+ the directories of `telegram` and `node` in `PATH`:
379
+
380
+ ```ini
381
+ [Unit]
382
+ Description=Better-TG-CLI MCP server over HTTP
383
+ After=network-online.target
384
+
385
+ [Service]
386
+ Environment=PATH=/usr/local/bin:/usr/bin:/bin
387
+ Environment=TG_NO_UPDATE_CHECK=1
388
+ ExecStart=/usr/bin/env telegram mcp --http --read-only
389
+ Restart=on-failure
390
+ RestartSec=5
391
+
392
+ [Install]
393
+ WantedBy=default.target
394
+ ```
395
+
396
+ ```bash
397
+ systemctl --user daemon-reload
398
+ systemctl --user enable --now better-tg-cli-mcp.service
399
+ systemctl --user status better-tg-cli-mcp.service
400
+ journalctl --user -u better-tg-cli-mcp.service -f
401
+ ```
402
+
403
+ The unit runs while you are logged in. `sudo loginctl enable-linger "$USER"` starts it at boot and
404
+ keeps it after you log out, but it does not unlock the keyring. If the Secret Service is missing or
405
+ locked for the service, the server exits with "The HTTP server needs a secret store for its token",
406
+ and systemd starts it again 5 seconds later. To see which secret store the service finds, run
407
+ `telegram check` with the unit's environment.
408
+
409
+ Where the service has no Secret Service (a headless server, say), use the 1Password store. Log in
410
+ once with `telegram auth --op-vault <vault>` under the same profile, put the directory of `op` in
411
+ the unit's `PATH`, and keep `OP_SERVICE_ACCOUNT_TOKEN=…` in a file only you can read (mode 0600),
412
+ loaded with `EnvironmentFile=%h/.config/tg/mcp.env` in `[Service]`. That token is a secret, so it
413
+ stays out of the unit file.
414
+
415
+ After `telegram mcp --rotate-token`, restart the service (`launchctl kickstart -k …` or
416
+ `systemctl --user restart better-tg-cli-mcp`): the running server keeps the old token until then.
417
+
309
418
  ## FAQ
310
419
 
311
420
  **Will Telegram ban my account?**
@@ -315,7 +424,7 @@ Using your own account from a third-party client is allowed by the [Telegram API
315
424
  No. It logs in as you over MTProto, like Telegram Desktop, and sees exactly what you see. Bots can't read your chats; this can.
316
425
 
317
426
  **Can an agent send messages on its own?**
318
- Only after you turn writes on. `telegram write-access on` asks you to confirm in the terminal or in a macOS dialog, which an agent can't answer. Writes then need an exact chat, and each one is logged. Over MCP, writing is a separate tool that clients can ask you to approve every time. Details are in [SECURITY.md](SECURITY.md).
427
+ Not by design. After login the profile is in mode `ask`: before each write the agent shows you the exact action in the chat and sends only after your yes, and the code it gets for that yes works once, for that exact text. Over MCP, clients that support elicitation ask you in their own dialog instead. This relies on the agent following its instructions: an agent that has a shell on your user account can read the session from the Keychain and act as you, so give such agents only chats you trust, or connect them through MCP only. `write-access on` (no questions) needs your confirmation in a terminal or a macOS dialog. Details are in [SECURITY.md](SECURITY.md).
319
428
 
320
429
  **Does reading mark messages as read?**
321
430
  No. `read`, `inbox` and `search` leave chats unread. Only `telegram mark-read` marks them.
@@ -337,6 +446,9 @@ report problems in the issues.
337
446
  **Can I use it from Grok Bot, ChatGPT or another cloud agent?**
338
447
  Cloud agents can't start a program on your computer, so run the MCP server over HTTP and reach it through a tunnel. See [Grok Bot](#grok-bot-remote-mcp-over-http).
339
448
 
449
+ **How do I allow writes on Grok Bot or another cloud agent?**
450
+ After `telegram onboard` it is already in mode `ask`: the agent asks you in the chat before each write. If it says writes are off, ask it to run `telegram write-access ask`; that works there as is. Only `telegram write-access on --for 1h` (no questions) needs your choice: those computers have no secret store and no terminal for you, so it opens a page in the agent's own browser where you choose. Running the command in your own terminal doesn't help: it changes the CLI on your computer, not the agent's. The agent should not try to install a keyring there; it can't work without a desktop session. On such computers the setting sits in a plain file, which protects against mistakes but not against a hostile agent.
451
+
340
452
  **Login fails with "NetSocket was closed" on a cloud computer (Grok Bot and others).**
341
453
  Some hosted agent computers let only HTTPS out, which drops Telegram's TCP transport. The CLI then switches to MTProto over WebSocket (`wss://*.web.telegram.org`, the transport of web.telegram.org) by itself and remembers it for the profile. `TG_TRANSPORT=tcp|wss|auto` picks the transport by hand.
342
454
 
package/README.ru.md CHANGED
@@ -56,9 +56,10 @@ $ telegram inbox -n 3
56
56
  - **Точное чтение.** `--since` и `--until` честно листают историю. Работают `--unread`, треды и
57
57
  комментарии в каналах, темы форумов, `get` по ID, поиск по типу, отправителю и дате. `me` и
58
58
  `Избранное` означают «Избранное».
59
- - **Безопасность по умолчанию.** Аккаунт открыт только на чтение, пока человек не выполнит
60
- `write-access on [--for 1h]` и не подтвердит это в терминале или в диалоге macOS. Сам агент
61
- запись не включит. Каждая запись попадает в `~/.config/tg/audit.jsonl`. Секреты хранятся в
59
+ - **Каждое сообщение одобряете вы.** После входа агент перед каждой отправкой, правкой или
60
+ удалением спрашивает вас в чате и показывает точный текст; отправляет только после вашего «да».
61
+ Писать без вопросов (`write-access on`) можно только после вашего подтверждения в терминале или
62
+ в диалоге macOS. Каждая запись попадает в `~/.config/tg/audit.jsonl`. Секреты хранятся в
62
63
  Keychain macOS, в Secret Service на Linux или в 1Password.
63
64
  - **Маленький и самодостаточный.** npm-пакет — один файл на 0,3 МБ без runtime-зависимостей.
64
65
  Homebrew ставит отдельный бинарник, которому не нужен Node.
@@ -187,7 +188,9 @@ npx skills add TheVilfer/better-tg-cli -g -a claude-code -a codex -y
187
188
  `telegram logout` её удаляет. На Linux сессия хранится в Secret Service (GNOME Keyring, KWallet,
188
189
  KeePassXC) через `secret-tool`, для этого нужен пакет `libsecret-tools`. Сессия, которая уже лежит
189
190
  в конфиге, переедет туда сама. Если хранилища секретов нет, сессия лежит в
190
- `~/.config/tg/config.json5` (права 0600), а запись остаётся выключенной. На Linux
191
+ `~/.config/tg/config.json5` (права 0600). На Linux без работающего Secret Service (нет `secret-tool`
192
+ или сессионной шины, как на облачных компьютерах агентов) режим записи тогда тоже хранится в
193
+ обычном файле профиля: это защита от ошибок, но не от агента, который может править файлы. На Linux
191
194
  `write-access on` подтверждается в терминале. На Windows секреты лежат в
192
195
  `%APPDATA%\tg\secrets.dpapi`, зашифрованные DPAPI для вашего пользователя Windows (расшифровать их
193
196
  можете только вы на этой машине), а `write-access on` без терминала спрашивает в окне «Да/Нет».
@@ -203,7 +206,8 @@ telegram get "Чат" 812 813 # конкретные сооб
203
206
  telegram download "Чат" 812 # сохранить вложение
204
207
  telegram sync --chat "Чат" --output ./export --resume # инкрементальная выгрузка в markdown
205
208
 
206
- telegram write-access on --for 1h # подтверждает человек
209
+ telegram write-access ask # каждая запись ждёт вашего «да» в чате (по умолчанию после onboard)
210
+ telegram write-access on --for 1h # или: запись без вопросов на час
207
211
  telegram send @alice "уже еду"
208
212
  printf '%s' "$text" | telegram send @alice - # длинный или многострочный текст: из stdin, без проблем с кавычками
209
213
  telegram reply "Чат" 812 "беру" --silent
@@ -270,12 +274,117 @@ telegram mcp --http --read-only # слушает 127.0.0.1:8787; б
270
274
  tailscale funnel --bg 8787 # или: cloudflared tunnel --url http://127.0.0.1:8787
271
275
  ```
272
276
 
273
- Держите сервер и туннель в терминале или в tmux. Затем добавьте в Grok Bot коннектор: адрес
277
+ Держите сервер и туннель в терминале или в tmux либо запустите сервер как фоновую службу (ниже).
278
+ Затем добавьте в Grok Bot коннектор: адрес
274
279
  туннеля плюс `/mcp` (например, `https://<машина>.<tailnet>.ts.net/mcp`) и заголовок
275
280
  `Authorization: Bearer <токен>`. У `tailscale funnel` адрес постоянный, но сначала Funnel надо
276
281
  разрешить для вашего tailnet. Быстрый туннель `cloudflared` при каждом запуске получает новый
277
282
  адрес. Сначала прочитайте раздел «Remote MCP over HTTP» в [SECURITY.md](SECURITY.md).
278
283
 
284
+ #### Сервер как фоновая служба
285
+
286
+ Служба запускает сервер сама и поднимает его заново после сбоя. На macOS LaunchAgent ниже
287
+ стартует при входе в систему и работает, пока вы в ней. На Linux пользовательский юнит может
288
+ стартовать и при загрузке, без входа (см. linger ниже). Ни один из файлов ниже не хранит секретов: сессия и bearer-токен остаются в Keychain или Secret Service, и сервер
289
+ читает их при запуске. Туннель тоже должен работать постоянно: `tailscale funnel --bg` живёт сам по
290
+ себе, а быстрый туннель `cloudflared` — нет.
291
+
292
+ Обоим файлам нужны пути, которые печатают `command -v telegram` и, если вы ставили через npm,
293
+ `command -v node`. npm-сборка `telegram` — это скрипт Node, а служба стартует с коротким `PATH`, где
294
+ нет каталогов Homebrew и nvm. Без правильного `PATH` она завершится с
295
+ `env: node: No such file or directory`.
296
+
297
+ **macOS (launchd).** Сохраните это как `~/Library/LaunchAgents/com.better-tg-cli.mcp.plist`. В
298
+ `ProgramArguments` укажите свой путь к `telegram`, в `PATH` — каталог `node`, а вместо `you` — имя
299
+ пользователя (`id -un`): launchd не раскрывает ни `~`, ни `$HOME`.
300
+
301
+ ```xml
302
+ <?xml version="1.0" encoding="UTF-8"?>
303
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
304
+ <plist version="1.0">
305
+ <dict>
306
+ <key>Label</key>
307
+ <string>com.better-tg-cli.mcp</string>
308
+ <key>ProgramArguments</key>
309
+ <array>
310
+ <string>/opt/homebrew/bin/telegram</string>
311
+ <string>mcp</string>
312
+ <string>--http</string>
313
+ <string>--read-only</string>
314
+ </array>
315
+ <key>EnvironmentVariables</key>
316
+ <dict>
317
+ <key>PATH</key>
318
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
319
+ <key>TG_NO_UPDATE_CHECK</key>
320
+ <string>1</string>
321
+ </dict>
322
+ <key>RunAtLoad</key>
323
+ <true/>
324
+ <key>KeepAlive</key>
325
+ <dict>
326
+ <key>SuccessfulExit</key>
327
+ <false/>
328
+ </dict>
329
+ <key>StandardOutPath</key>
330
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
331
+ <key>StandardErrorPath</key>
332
+ <string>/Users/you/Library/Logs/better-tg-cli-mcp.log</string>
333
+ </dict>
334
+ </plist>
335
+ ```
336
+
337
+ ```bash
338
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.better-tg-cli.mcp.plist
339
+ launchctl print gui/$(id -u)/com.better-tg-cli.mcp | grep -E 'state|last exit'
340
+ launchctl kickstart -k gui/$(id -u)/com.better-tg-cli.mcp # перезапуск
341
+ launchctl bootout gui/$(id -u)/com.better-tg-cli.mcp # остановить и выгрузить
342
+ ```
343
+
344
+ `KeepAlive` с `SuccessfulExit` false перезапускает сервер, когда тот падает или его убивают. Если при
345
+ первом запуске macOS спросит доступ к Keychain, разрешите.
346
+
347
+ **Linux (пользовательский юнит systemd).** Сохраните это как
348
+ `~/.config/systemd/user/better-tg-cli-mcp.service`, указав в `PATH` каталоги `telegram` и `node`:
349
+
350
+ ```ini
351
+ [Unit]
352
+ Description=Better-TG-CLI MCP server over HTTP
353
+ After=network-online.target
354
+
355
+ [Service]
356
+ Environment=PATH=/usr/local/bin:/usr/bin:/bin
357
+ Environment=TG_NO_UPDATE_CHECK=1
358
+ ExecStart=/usr/bin/env telegram mcp --http --read-only
359
+ Restart=on-failure
360
+ RestartSec=5
361
+
362
+ [Install]
363
+ WantedBy=default.target
364
+ ```
365
+
366
+ ```bash
367
+ systemctl --user daemon-reload
368
+ systemctl --user enable --now better-tg-cli-mcp.service
369
+ systemctl --user status better-tg-cli-mcp.service
370
+ journalctl --user -u better-tg-cli-mcp.service -f
371
+ ```
372
+
373
+ Юнит работает, пока вы вошли в систему. `sudo loginctl enable-linger "$USER"` запускает его при
374
+ загрузке и оставляет после выхода, но связку ключей не разблокирует. Если Secret Service для службы
375
+ нет или он заблокирован, сервер завершается с «The HTTP server needs a secret store for its token»,
376
+ и systemd запускает его снова через 5 секунд. Чтобы увидеть, какое хранилище находит служба,
377
+ выполните `telegram check` с окружением юнита.
378
+
379
+ Если у службы нет Secret Service (например, на сервере без рабочего стола), используйте хранилище
380
+ 1Password. Один раз войдите с `telegram auth --op-vault <vault>` в том же профиле, добавьте каталог
381
+ `op` в `PATH` юнита, а `OP_SERVICE_ACCOUNT_TOKEN=…` держите в файле, доступном только вам (права
382
+ 0600), и подключите его строкой `EnvironmentFile=%h/.config/tg/mcp.env` в `[Service]`. Этот токен —
383
+ секрет, поэтому в самом юните его нет.
384
+
385
+ После `telegram mcp --rotate-token` перезапустите службу (`launchctl kickstart -k …` или
386
+ `systemctl --user restart better-tg-cli-mcp`): до этого работающий сервер принимает старый токен.
387
+
279
388
  ## FAQ
280
389
 
281
390
  **Не забанит ли Telegram мой аккаунт?**
@@ -285,7 +394,7 @@ tailscale funnel --bg 8787 # или: cloudflared tunnel --url h
285
394
  Нет. CLI входит от вашего имени по MTProto, как Telegram Desktop, и видит ровно то же, что и вы. Боты не читают ваши чаты, а этот клиент читает.
286
395
 
287
396
  **Может ли агент отправлять сообщения сам?**
288
- Только после того, как вы включите запись. `telegram write-access on` просит подтверждения в терминале или в диалоге macOS, на которое агент ответить не может. Дальше запись требует точно указанный чат, а каждая отправка пишется в журнал. В MCP запись вынесена в отдельный инструмент, и клиенты могут спрашивать вас перед каждым вызовом. Подробнее в [SECURITY.md](SECURITY.md).
397
+ Не должен. После входа профиль в режиме `ask`: перед каждой записью агент показывает вам в чате точное действие и отправляет только после вашего «да», а код, который он получает под это «да», срабатывает один раз и только для этого текста. Через MCP клиенты с поддержкой elicitation спрашивают вас в своём окне. Всё это держится на том, что агент слушается инструкций: агент с доступом к терминалу под вашим пользователем может прочитать сессию из Keychain и действовать от вашего имени, поэтому давайте таким агентам только доверенные чаты или подключайте их только через MCP. `write-access on` (без вопросов) требует вашего подтверждения в терминале или в диалоге macOS. Подробности в [SECURITY.md](SECURITY.md).
289
398
 
290
399
  **Отмечает ли чтение сообщения прочитанными?**
291
400
  Нет. `read`, `inbox` и `search` оставляют чаты непрочитанными. Отмечает только `telegram mark-read`.
@@ -307,6 +416,9 @@ tailscale funnel --bg 8787 # или: cloudflared tunnel --url h
307
416
  **Можно ли пользоваться из Grok Bot, ChatGPT или другого облачного агента?**
308
417
  Облачный агент не может запустить программу на вашем компьютере, поэтому поднимите MCP-сервер по HTTP и откройте к нему туннель. См. [Grok Bot](#grok-bot-удалённый-mcp-по-http).
309
418
 
419
+ **Как разрешить запись в Grok Bot или другом облачном агенте?**
420
+ После `telegram onboard` там уже режим `ask`: агент спрашивает вас в чате перед каждой записью. Если он пишет, что запись выключена, попросите его выполнить `telegram write-access ask`, это работает там как есть. Только `telegram write-access on --for 1h` (без вопросов) требует вашего выбора: на таких компьютерах нет хранилища секретов и терминала для вас, поэтому команда открывает страницу в браузере самого агента, где вы выбираете. Запускать команду в своём терминале бесполезно: она меняет CLI на вашем компьютере, а не у агента. Ставить там связку ключей агенту не нужно: без рабочего стола она не заработает. Настройка на таких компьютерах лежит в обычном файле, это защита от ошибок, но не от злонамеренного агента.
421
+
310
422
  **Вход падает с «NetSocket was closed» на облачном компьютере (Grok Bot и другие).**
311
423
  Некоторые облачные компьютеры агентов выпускают наружу только HTTPS, и TCP-транспорт Telegram обрывается. Тогда CLI сам переключается на MTProto поверх WebSocket (`wss://*.web.telegram.org`, тот же транспорт, что у web.telegram.org) и запоминает это для профиля. Выбрать транспорт вручную можно через `TG_TRANSPORT=tcp|wss|auto`.
312
424