@llblab/pi-telegram 0.25.1 → 0.25.3

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/AGENTS.md CHANGED
@@ -89,7 +89,7 @@ The core product loop is mobile continuation: start or supervise work in the ter
89
89
  - Instance thread names are provisioner-authored identity metadata, not model-authored output. Fresh Threaded Mode threads select one of five curated compact 4-6 letter Latin names for the assigned slot letter using provisioning timestamp entropy, then create the Telegram thread with that thread name immediately. The title is the thread name itself, not `{slot} {threadName}` or `{slot} — {threadName}`. Do not register or reintroduce an agent-facing thread rename tool; removing the extra rename prompt/tool turn is an intentional simplicity constraint. Thread names must mirror into terminal status, live diagnostics, and `[telegram|thread:name]` through one target-aware current-instance identity resolver. Registered follower/leader metadata takes precedence over a stale shared record for the same target, with the record used only as fallback; do not hide a valid baked/custom thread name behind old slot-prefix validation. A follower that later becomes leader keeps its existing name; leadership changes are transport role changes, not identity resets.
90
90
  - Telegram private-chat Threaded Mode treats `All` as an aggregate/control surface, not a durable `General` thread or process launcher, and leader activation proactively creates or reuses its private-DM thread. When the owner writes in an unknown thread, the leader reclaims and routes the first one only if it lacks an active binding; later unknown threads remain intact and receive an in-thread chooser to reroute the captured prompt or restore a stale binding. Destructive cleanup requires explicit confirmation through `thread-reconciler`; another Pi instance still requires a manually started process followed by `/telegram-connect`. Without Threaded Mode, process the message through classic routing.
91
91
  - Telegram extension work should not hold Pi's core agent lifecycle hostage once Pi has produced the semantic result. For Telegram-originated turns, final Telegram delivery, attachment upload, and transport cleanup are extension-owned side effects; schedule them off the critical `agent_end` path when ordering can still be preserved, record failures as runtime events, and keep dispatch of the next Telegram turn behind the delivery task when needed to avoid interleaving previews/finals. Treat a low-level error `agent_end` as retryable while its Telegram turn remains active; only a later successful `agent_end` or Pi's `agent_settled` boundary may finalize and release that turn. Public activity handlers run through isolated asynchronous per-handler queues; lifecycle hooks enqueue normalized events and never await consumer work. Proactive push defaults enabled and requires explicit `assistant.proactivePush: false` to opt out. While enabled, core delivery projects each completed Pi-visible assistant text block from local/autonomous work once and in order; bind admitted blocks to the exact target, profile/token transport stamp, direct leader epoch or follower registration generation, and session generation. Token deltas, hidden reasoning, tool traffic, stale authority, and Telegram-owned turns never enter that projection.
92
- - The only core reasoning/tool visibility path is the operator-enabled `assistant.activity: "verbose"` projection. It remains separate from proactive public prose and assistant Markdown: provider-exposed reasoning uses draft-only Rich `Thinking`, while completed executed tools use durable ordinary HTML messages with standard expandable blockquotes and never use Rich Messages. Keep it quiet by default, exact-target/transport-generation fenced, start-order preserving, boundary-aware, memory/transport bounded, and non-blocking; final delivery waits for admitted technical activity only inside the extension-owned background task, and session replacement abandons queued old-generation work without waiting on old transport. Read legacy `assistant.activityVerbosity` only when `assistant.activity` is absent and remove it on the next Settings write. Never persist reasoning, invent unavailable provider-private reasoning, or replay a possibly committed technical message.
92
+ - Core thinking/tool visibility is controlled by `assistant.activity: "quiet" | "thinking" | "tools" | "verbose"`. It remains separate from proactive public prose and assistant Markdown: provider-exposed thinking and completed executed tools use durable ordinary HTML messages with standard expandable blockquotes and never use Rich Messages. Thinking uses the `🧠` header with the current Pi thinking level instead of a generic lifecycle status, tools use `🛠`, `verbose` enables both, and every activity send/edit disables Telegram link previews. Keep it quiet by default, exact-target/transport-generation fenced, start-order preserving, boundary-aware, memory/transport bounded, and non-blocking; final delivery waits for admitted technical activity only inside the extension-owned background task, and session replacement abandons queued old-generation work without waiting on old transport. Read legacy `assistant.activityVerbosity` only when `assistant.activity` is absent and remove it on the next Settings write. Never invent unavailable provider-private thinking or replay a possibly committed technical message.
93
93
  - Telegram runtime state should be treated as event-driven reconciliation of extension assumptions against observable Telegram signals, not as a full Telegram bot read-model and not as a reason to query Telegram on every action. Keep a local assumption model for bot identity/capabilities, pairing assumptions, thread support, known thread lifecycle, bound instance targets, reservations, and transport health. Invalidate and reconcile the relevant slice on meaningful events: startup/reload, lifecycle service messages, stale-send/API errors, setup/pairing changes, follower register/prune, explicit status/debug requests, and bounded low-frequency leader health ticks. `lib/sync.ts` owns sync slices, observation intake, invalidation triggers, status/debug freshness, and reconciliation scheduling; it must not promise complete bot-state mirroring because Bot API lacks a complete topic listing surface. `lib/thread-reconciler.ts` owns pure Threaded Mode lifecycle planning and should become the only policy authority for destructive thread cleanup decisions. `threads` owns current Telegram UI thread/tab binding primitives and thread-name helpers mapped to Bot API topic transport, `status` renders projections, and `index.ts` only wires ports. `tmp/telegram/logs.jsonl` is a session-local redacted runtime evidence stream for race debugging and resets on extension start / runtime scope changes; it is diagnostics only, not routing/provisioning authority. `state.json` should be an observable/debug snapshot aligned with `/telegram-status` (extension runtime, bot capabilities including `bot.lastSlot`, runtime role, live roster projection, reservations, diagnostics), not routing/provisioning authority. Because every process on one Telegram profile shares this file, only the active transport lock owner may persist it; followers read current state and gain write authority only after promotion. Status-only writes must refresh disk-backed bindings before serialization so a stale loaded snapshot cannot erase newer leader state. Live bus/runtime state is authoritative; file reservations and fresh capability observations may be startup hints/collision guards only; stale snapshots must re-probe before suppressing bus/topic behavior. Do not persist stale/offline/failed thread target history as source of truth.
94
94
  - Thread bindings are bidirectional. From the Pi-instance side, an instance knows and preserves its target, slot, thread name, lifecycle state, and direct-delivery defaults. From the Telegram-client/bot side, the bridge observes thread creation/close/reopen/stale-send signals and reconciles them into instance binding state. Lifecycle transitions that affect operator understanding should be Telegram-visible when a live transport remains: every successful follower registration/re-registration gets a compact connected notice in the assigned thread, while heartbeat pruning stays silent because it is only liveness suspicion. These notices should use the instance thread name when known and fall back to the slot letter only while the thread is still unnamed. New unknown or command-created temporary threads receive the complete forward plus replace/restore control set and remain preserved until the user chooses one. Successful forward deletes the chooser and temporary thread; successful replace/restore always deletes the chooser, rebinds the temporary thread, and deletes only the replaced old thread. Any destructive cleanup must go through `thread-reconciler`. Unknown `forum_topic_created` service events are observations, not destructive cleanup proof.
95
95
  - The multi-instance bus uses private bot DMs with Telegram private-chat Threaded Mode enabled for the bot. No supergroup, group, or forum configuration is needed; the thread chat is always the private chat with the paired owner. Threaded capability checks must use bot/private-chat evidence such as `getMe.has_topics_enabled`, incoming `message_thread_id`, and topic operation success/failure; do not use group chat metadata as the control-plane truth for Telegram private-chat Threaded Mode.
package/BACKLOG.md CHANGED
@@ -4,15 +4,13 @@ _This backlog tracks only open release-relevant work: hotfixes, bounded maintena
4
4
 
5
5
  ## P1 — Configurable Activity Live Smoke
6
6
 
7
- Context: `0.25.0` shipped quiet-by-default configurable activity verbosity. The remaining work is live Telegram client verification of verbose reasoning and compact technical tool activity.
8
-
9
- Bot API evidence: Bot API 10.2 exposes explicit outgoing Rich Message blocks. `InputRichBlockThinking` is draft-only and disappears when the draft lifecycle ends; `InputRichBlockDetails` provides a collapsed disclosure container, and `InputRichBlockPreformatted` provides nested `<pre><code>` content. Exact mobile/Desktop rendering, edit behavior, and practical limits remain live-verification gates.
7
+ Context: configurable activity now offers quiet, thinking-only, tools-only, and verbose modes. Thinking and tools use persistent collapsed ordinary HTML messages instead of draft-only Rich Thinking blocks.
10
8
 
11
9
  Open work:
12
10
 
13
- - [ ] Live-smoke both modes in classic and Threaded Mode on Telegram mobile and Desktop, including multiple sequential tools, oversized output rollover, cancellation during reasoning, tool failure, session replacement, follower transport, and final-answer ordering.
11
+ - [ ] Live-smoke all four modes in classic and Threaded Mode on Telegram mobile and Desktop, including progressive thinking edits, multiple sequential tools, oversized output rollover, cancellation during thinking, tool failure, session replacement, follower transport, and final-answer ordering.
14
12
 
15
- Done when: live mobile and Desktop clients confirm the intended quiet/verbose draft, disclosure, routing, rollover, cancellation, failure, and final-answer ordering behavior in classic and Threaded Mode.
13
+ Done when: live mobile and Desktop clients confirm the intended mode isolation, persistent disclosures, routing, rollover, cancellation, failure, and final-answer ordering behavior in classic and Threaded Mode.
16
14
 
17
15
  ## P1 — Native Windows Runtime Smoke
18
16
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.25.3: Thinking Density Header Hotfix
4
+
5
+ - `Thinking Activity`: Replaced the generic `running`/`done` thinking header state with the current Pi thinking level, such as `high`, and stopped finalizing an already-current disclosure with a no-op completion edit. Impact: each persistent thinking block carries useful reasoning-density context instead of redundant lifecycle noise.
6
+
7
+ ## 0.25.2: Persistent Thinking Activity Hotfix
8
+
9
+ - `Activity Modes`: Expanded `assistant.activity` to `quiet`, `thinking`, `tools`, and `verbose`; thinking now uses persistent ordinary HTML messages with a `🧠` header and collapsed bounded disclosure instead of ephemeral Rich drafts, while tools retain `🛠` disclosures. Every activity send/edit disables Telegram link previews. Impact: operators can inspect thinking-only, tools-only, or combined technical history without Telegram removing thinking when the final answer arrives or URL-like evidence expanding into distracting previews.
10
+
3
11
  ## 0.25.1: Config And Activity Presentation
4
12
 
5
13
  - `Time Injection Config`: Moved the Settings-owned mode to `assistant.timeInjection`, while retaining `time.interval` as the independent interval duration. The old `time.injectionMode` key is ignored without fallback, migration, or automatic rewriting. Impact: assistant presentation controls share one config domain without silently mutating historical user data.
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  It is a **runtime adapter**, not a remote terminal. Start or supervise work in the Pi TUI, then continue from Telegram while away from the keyboard. Each Telegram destination follows a running Pi instance and sends prompts into that instance's currently active session; it is not permanently bound to one session file or session identity. The bridge preserves Pi session semantics instead of pretending Telegram is a PTY, shell, process launcher, or session browser. That boundary is the product: Telegram gets safe runtime handles, not raw terminal power.
10
10
 
11
- Proactive push is enabled by default. `assistant.proactivePush` projects every completed public assistant text block from local or autonomous work—including visible checkpoints and the final answer—to the authorized Telegram target once and in order; set it explicitly to `false` to disable projection. Proactive push itself never mirrors local prompts, reasoning, tool traffic, token deltas, Telegram-owned turns, or stale-generation work. The separate quiet-by-default `Activity` setting can add ephemeral provider-exposed reasoning and bounded collapsed tool evidence. See [Outbound](docs/outbound.md#proactive-public-output) and the [configuration reference](docs/public-api.md#configuration-api).
11
+ Proactive push is enabled by default. `assistant.proactivePush` projects every completed public assistant text block from local or autonomous work—including visible checkpoints and the final answer—to the authorized Telegram target once and in order; set it explicitly to `false` to disable projection. Proactive push itself never mirrors local prompts, thinking, tool traffic, token deltas, Telegram-owned turns, or stale-generation work. The separate quiet-by-default `Activity` setting can persist collapsed provider-exposed thinking, tool evidence, or both. See [Outbound](docs/outbound.md#proactive-public-output) and the [configuration reference](docs/public-api.md#configuration-api).
12
12
 
13
13
  This repository is an actively maintained fork of [`badlogic/pi-telegram`](https://github.com/badlogic/pi-telegram). It started from upstream commit [`cb34008`](https://github.com/badlogic/pi-telegram/commit/cb34008460b6c1ca036d92322f69d87f626be0fc) and has since diverged substantially.
14
14
 
@@ -98,12 +98,12 @@ The first Telegram user to message the bot becomes the allowed owner. Other user
98
98
  | Queue control | Inspect waiting turns, delete stale work, promote important prompts, continue, abort, stop, or force the next queued item. | Long Pi tasks keep running while new mobile prompts stay visible and controllable instead of interrupting or disappearing. |
99
99
  | Operator menu | Use `/start` for status, prompt templates, model, thinking, settings, queue, extension sections, and diagnostics. | The bot is an operator panel, not a command cheat sheet. |
100
100
  | Prompt templates | Run Pi prompt templates as Telegram-safe commands such as `/fix_tests`. | Reusable local workflows become phone-accessible without exposing arbitrary terminal commands. |
101
- | Model and thinking | Switch model or reasoning level from Telegram through safe continuation flows. | Mobile control can adjust execution strategy without tearing down the current session. |
101
+ | Model and thinking | Switch model or thinking level from Telegram through safe continuation flows. | Mobile control can adjust execution strategy without tearing down the current session. |
102
102
  | Compaction | Confirm `/compact`, show native active status during compaction, and preserve Telegram-owned turn semantics. | Context maintenance is visible and safe from the phone. |
103
103
  | Draft previews | Show Telegram's native `…typing` indicator whenever the connected instance is doing agent work, or enable Rich Draft previews for streamed answer text. | Local prompts, Telegram turns, and autonomous continuations remain visibly active while draft visibility stays independent from final rendering. |
104
- | Activity | Keep the default `quiet` answer-only surface, or select `verbose` for short-lived reasoning drafts and durable collapsed tool disclosures. | Technical activity stays bounded, redacted, target-fenced, and visually separate from semantic assistant answers. |
104
+ | Activity | Keep the default `quiet` answer-only surface, show only `thinking`, show only `tools`, or select `verbose` for both. Thinking headers report the current Pi thinking level instead of a generic completion state. | Persistent collapsed technical activity stays bounded, redacted, target-fenced, density-aware, and visually separate from semantic assistant answers. |
105
105
  | Assistant rendering | Choose Native Rich Markdown or legacy Markdown-to-HTML for final assistant replies. | Renderer compatibility is explicit instead of being conflated with draft previews. |
106
- | Bridge UI rendering | Render verbose reasoning through a draft-only Rich Thinking block, tool activity through ordinary expandable HTML messages, and menus, queue controls, status, settings, diagnostics, and sections through Telegram HTML/plain UI. | Harness-owned surfaces remain operationally predictable and visually distinct from model-authored answers. |
106
+ | Bridge UI rendering | Render thinking and tool activity through ordinary expandable HTML messages, and menus, queue controls, status, settings, diagnostics, and sections through Telegram HTML/plain UI. | Harness-owned surfaces remain operationally predictable and visually distinct from model-authored answers. |
107
107
  | Inbound files | Download inbound files to the Pi agent temp directory with size limits. | Screenshots, PDFs, datasets, and artifacts enter Pi as inspectable local files. |
108
108
  | Outbound artifacts | Return generated files through `telegram_attach` during active turns or explicit direct delivery. | Agents send real artifacts as files, not pasted blobs. |
109
109
  | Voice input | Route audio through configured command-template handlers, programmatic handlers, or STT providers. | Voice notes become usable prompt context. |
@@ -172,7 +172,7 @@ Messages sent while Pi is busy become queued turns. Priority lanes support contr
172
172
 
173
173
  ### Native Rich Markdown
174
174
 
175
- Rich Markdown is the default model-answer membrane. Complete assistant and guest model replies use Telegram's native Rich Message APIs. In `verbose` activity mode, bridge-owned reasoning uses an ephemeral Rich `Thinking` draft while completed tools use ordinary HTML messages with standard expandable blockquotes and never Rich Messages; menus, status rows, queue controls, settings, diagnostics, and other operational UI retain explicit Telegram HTML/plain rendering. Three Settings controls keep the layers separate: `Draft previews` toggles streamed answer drafts, `Activity` chooses `quiet` or `verbose` technical activity, and `Assistant rendering` chooses final-answer delivery (`rich` Native Rich Markdown or `html` legacy Markdown-to-HTML).
175
+ Rich Markdown is the default model-answer membrane. Complete assistant and guest model replies use Telegram's native Rich Message APIs. Activity thinking and completed tools use persistent ordinary HTML messages with standard expandable blockquotes and never Rich Messages; `thinking`, `tools`, and `verbose` select the visible classes, while menus, status rows, queue controls, settings, diagnostics, and other operational UI retain explicit Telegram HTML/plain rendering. Three Settings controls keep the layers separate: `Draft previews` toggles streamed answer drafts, `Activity` chooses `quiet` or `verbose` technical activity, and `Assistant rendering` chooses final-answer delivery (`rich` Native Rich Markdown or `html` legacy Markdown-to-HTML).
176
176
 
177
177
  ### Files And Artifacts
178
178
 
@@ -225,7 +225,7 @@ Companion extensions can integrate with Telegram without owning polling or trans
225
225
  - Add menu sections and settings surfaces.
226
226
  - Add compact status rows.
227
227
  - Deliver target-aware operational views and chat actions from companion code.
228
- - Observe normalized assistant, reasoning, tool, compaction, and settlement activity without blocking Pi.
228
+ - Observe normalized assistant, thinking, tool, compaction, and settlement activity without blocking Pi.
229
229
  - Handle update/callback namespaces.
230
230
  - Provide inbound preprocessing handlers.
231
231
  - Provide outbound voice synthesis.
package/docs/activity.md CHANGED
@@ -291,7 +291,7 @@ The implementation must cover:
291
291
 
292
292
  ## Core Verbosity And Consumer Policy
293
293
 
294
- The bridge now owns the minimal global `quiet`/`verbose` policy. Quiet is the default. Verbose streams available reasoning through an ephemeral Rich Thinking draft and emits bounded tool evidence through ordinary HTML expandable blockquotes without changing public assistant-segment projection or final replies.
294
+ The bridge owns a global `quiet`/`thinking`/`tools`/`verbose` policy. Quiet is the default, `thinking` and `tools` select one technical class, and `verbose` enables both. Available thinking and bounded tool evidence use persistent ordinary HTML messages with expandable blockquotes without changing public assistant-segment projection or final replies.
295
295
 
296
296
  The registration and delivery examples above remain the public building blocks for companion-specific policy:
297
297
 
@@ -315,7 +315,7 @@ Queue reactions are shortcut controls for waiting turns. Promotion reactions (`
315
315
 
316
316
  When `assistant.proactivePush` is enabled and this instance has exact direct or follower transport authority, completed public assistant text blocks from local/autonomous work are sent once and in source order to the instance's authorized target. Visible commentary/checkpoints and the final block use the configured Rich or HTML renderer. Proactive projection excludes reasoning, tool traffic, token deltas, local prompt text, Telegram-owned turns, and stale generations. Each admitted block remains fenced to its exact target, profile/token stamp, leader epoch or follower registration generation, and session generation; non-idempotent acknowledgement ambiguity never authorizes replay.
317
317
 
318
- `assistant.activity` is an independent bridge-owned projection over normalized Activity events. Omitted or invalid values resolve to `quiet`, which emits no reasoning or tool traffic. `verbose` uses bounded ephemeral Rich Thinking drafts for provider-exposed reasoning and ordinary HTML messages with standard expandable blockquotes for completed executed tools; tool output never uses Rich Messages. It captures the exact target and transport stamp at activity admission, serializes updates, preserves tool-start order, closes coalescing across assistant/reasoning boundaries, redacts and truncates evidence, bounds retained reasoning/update memory plus draft frames and message/tool size, and never replays a possibly committed send. Session generations own independent queues, so replacement drops queued old work without waiting on an old call. Both proactive prose and active-turn final delivery wait for the admitted activity queue inside their extension-owned delivery tasks, preserving technical-before-semantic ordering without delaying Pi lifecycle completion. Settlement, replacement, disconnect, failure, or stale authority clears local ownership without persisting reasoning.
318
+ `assistant.activity` is an independent bridge-owned projection over normalized Activity events. Omitted or invalid values resolve to `quiet`, which emits no thinking or tool traffic; `thinking` and `tools` select one technical class, while `verbose` enables both. Provider-exposed thinking and completed executed tools use persistent ordinary HTML messages with standard expandable blockquotes and never use Rich Messages. Thinking uses a `🧠` header carrying the current Pi thinking level and a bounded redacted latest-text window; tools use `🛠` headers and bounded redacted execution evidence. The projection captures the exact target and transport stamp at activity admission, serializes updates, preserves tool-start order, closes coalescing across assistant/thinking boundaries, bounds retained text/update memory plus edit frames and message/tool size, and never replays a possibly committed send. Session generations own independent queues, so replacement drops queued old work without waiting on an old call. Both proactive prose and active-turn final delivery wait for the admitted activity queue inside their extension-owned delivery tasks, preserving technical-before-semantic ordering without delaying Pi lifecycle completion. Settlement, replacement, disconnect, failure, or stale authority clears only local ownership; already-sent activity messages remain in chat.
319
319
 
320
320
  Telegram prompt guidance is context- and authority-aware. Only an exact direct owner or live registered follower exposes the three pi-telegram model tools, their active-tool metadata, and the compact local bridge suffix. Disconnect or authority loss removes those surfaces for subsequent requests without touching foreign tools; reconnect/recovery restores only the pi-telegram subset that was active before suspension, including across same-process reload. Telegram-originated turns receive a compact pointer to `telegram_help` plus dynamic prompt blocks such as `[voice] delivery: automatic voice`; full voice/button/direct-delivery/Threaded Mode syntax stays in the help tool rather than every system prompt.
321
321
 
package/docs/outbound.md CHANGED
@@ -12,26 +12,26 @@ Proactive projection defaults on. With `assistant.proactivePush` omitted or set
12
12
 
13
13
  Proactive blocks use `assistant.rendering` independently of voice policy. Rich mode sends native Rich Markdown and HTML mode keeps the established HTML renderer; proactive projection does not synthesize voice or attach queued files merely because Rich rendering is active. The queue revalidates exact target, profile/token transport generation, leader epoch or follower registration generation, and session generation before each send. Telegram-owned turns remain on their ordinary reply path, and `commit-unknown` never permits proactive replay.
14
14
 
15
- ## Verbose Technical Activity
15
+ ## Technical Activity
16
16
 
17
- `assistant.activity` defaults to `quiet`. In `verbose`, the bridge consumes the same normalized Activity stream without mixing technical UI into assistant Markdown:
17
+ `assistant.activity` defaults to `quiet` and accepts four modes: `quiet`, `thinking`, `tools`, and `verbose`. `thinking` shows only provider-exposed thinking, `tools` shows only completed executed tools, and `verbose` shows both without mixing technical UI into assistant Markdown.
18
18
 
19
- - Provider-exposed reasoning deltas update a bounded ephemeral `sendRichMessageDraft` containing one `Thinking` block. Inline Markdown bold and code markers are projected to native Rich Text so their delimiters do not appear literally; unmatched streaming delimiters remain plain text until a later complete draft. The draft is fenced to its captured chat/thread and transport generation; settlement, cancellation, replacement, disconnect, or authority loss drops local ownership. It is never converted into a persisted reasoning message, and providers that expose no reasoning produce none.
19
+ - Provider-exposed thinking updates one persistent ordinary HTML message. Its `🧠 thinking: <level>` header reports the current Pi thinking level, such as `high`, above a standard Telegram `<blockquote expandable>` containing a bounded redacted latest-text window. The bridge sends the message once, edits it only as thinking grows, and leaves the disclosure in chat; it never replaces useful density metadata with a generic completion state or uses Rich drafts/Rich Messages. Providers that expose no thinking produce none.
20
20
  - Completed executed tools use ordinary `sendMessage` HTML, never `sendRichMessage`. Each tool header renders as `🛠 <tool>: <status>`, with a stable two-space visual gap after the icon and the `running`, `done`, or `failed` status in monospace. One standard Telegram `<blockquote expandable>` then contains bounded redacted evidence in chronological order. JSON-style labels share a line with their serialized value opening, for example `"arguments": {`, `"update 1": {`, and `"result": {` or `"error": {`; arrays of object entries use the denser `[{ ... }, { ... }]` layout while retaining indented fields.
21
- - Consecutive tools coalesce by editing one message only while target, activity, generation, ordering boundary, tool count, and serialized-size bounds still match. Assistant or reasoning content closes the batch. A non-idempotent send with unknown commit state is never replayed; failed or ambiguous edits start no fallback send.
21
+ - Every thinking/tool `sendMessage` and `editMessageText` sets `link_preview_options.is_disabled: true`, so URL-like evidence never expands into a web preview. Consecutive tools coalesce by editing one message only while target, activity, generation, ordering boundary, tool count, and serialized-size bounds still match. Assistant or thinking content closes the batch. A non-idempotent send with unknown commit state is never replayed; failed or ambiguous edits start no fallback send.
22
22
 
23
- Reasoning retains only a bounded latest-text window, tool updates retain only a bounded latest-entry window, and a session reset abandons queued old-generation work without making the replacement session wait for an old transport call. Final-answer delivery waits for the admitted verbose activity queue inside the extension-owned background delivery task, so completed tool evidence cannot be overtaken by the semantic answer and Pi lifecycle completion remains non-blocking.
23
+ Thinking retains only a bounded latest-text window, tool updates retain only a bounded latest-entry window, and a session reset abandons queued old-generation work without making the replacement session wait for an old transport call. Final-answer delivery waits for the admitted activity queue inside the extension-owned background delivery task, so completed technical evidence cannot be overtaken by the semantic answer and Pi lifecycle completion remains non-blocking.
24
24
 
25
- Verbose activity is operational evidence, not part of the semantic answer stream. Final-answer rendering, voice policy, artifacts, and quiet behavior remain unchanged.
25
+ Technical activity is operational evidence, not part of the semantic answer stream. Final-answer rendering, voice policy, artifacts, and quiet behavior remain unchanged.
26
26
 
27
27
  ### Live Activity Smoke
28
28
 
29
29
  Exercise one classic chat and one Threaded Mode follower target on both Telegram mobile and Desktop:
30
30
 
31
- 1. Leave `Activity` on `quiet`; run a reasoning-capable request with two tools and confirm only normal preview/public/final output appears in established order.
32
- 2. Switch to `verbose`; confirm reasoning appears only as a temporary Thinking draft, two sequential tools become two independently collapsed disclosures in one message, and the final answer follows the completed tool UI.
31
+ 1. Leave `Activity` on `quiet`; run a thinking-capable request with two tools and confirm only normal preview/public/final output appears in established order.
32
+ 2. Exercise `thinking`, `tools`, and `verbose`; confirm persistent collapsed thinking appears only in the modes that include it, two sequential tools become two independently collapsed disclosures in one message only in the modes that include tools, and the final answer follows admitted technical UI.
33
33
  3. Produce oversized arguments, multiple updates, and oversized result/error output; confirm redaction/truncation markers, latest-update retention, and safe rollover to another message without flood or reordering.
34
- 4. Cancel during reasoning, fail a tool, replace the Pi session, and disconnect/reconnect transport; confirm reasoning never persists, stale activity does not cross generations, failure remains collapsed technical evidence, and subsequent work uses only the current target/authority.
34
+ 4. Cancel during thinking, fail a tool, replace the Pi session, and disconnect/reconnect transport; confirm already-sent thinking remains in chat, stale activity does not cross generations, failure remains collapsed technical evidence, and subsequent work uses only the current target/authority.
35
35
  5. Repeat through a registered follower and confirm every draft/send/edit stays in its assigned thread. Capture client/version, mode, target role, observed block behavior, and any Bot API/runtime diagnostic for each result.
36
36
 
37
37
  ## Standard
@@ -54,7 +54,7 @@ The optimization is deliberately narrow. HTML rendering, empty final text, multi
54
54
 
55
55
  This behavior does not generate media or alter voice policy. `telegram_attach` still represents an explicit assistant artifact decision, while `hidden`, `mirror`, and `always` continue to decide voice synthesis independently.
56
56
 
57
- Core assistant output accepts only the Markdown or HTML `InputRichMessage` forms. `InputRichBlockThinking` is reserved for ephemeral verbose reasoning drafts; durable tool evidence uses ordinary HTML messages and never Rich Message blocks. Reasoning drafts consume only lifecycle content actually exposed by the active provider and never synthesize unavailable private reasoning.
57
+ Core assistant output accepts only the Markdown or HTML `InputRichMessage` forms. Activity thinking and tool evidence use persistent ordinary HTML messages with expandable blockquotes and never Rich Message blocks. Thinking consumes only lifecycle content actually exposed by the active provider and never synthesizes unavailable private thinking.
58
58
 
59
59
  ### Guest Mode media boundary
60
60
 
@@ -95,7 +95,7 @@ interface TelegramConfig {
95
95
  draftPreviews?: boolean;
96
96
  rendering?: "rich" | "html";
97
97
  proactivePush?: boolean;
98
- activity?: "quiet" | "verbose";
98
+ activity?: "quiet" | "thinking" | "tools" | "verbose";
99
99
  timeInjection?: "hidden" | "always" | "interval";
100
100
  };
101
101
  voice?: {
@@ -119,7 +119,7 @@ Hidden/default semantics are represented by absence:
119
119
 
120
120
  - `threads.automaticCleanup` defaults to `true`; graceful Pi quit deletes the instance's bound Threaded Mode tab without prompting. Set it to `false`, or use `🧹 Thread cleanup` in Telegram Settings, to preserve the tab as a restart hint. Settings views and cleanup reload shared config before evaluating this switch, so another live Pi instance's update takes effect without restarting. Confirmed leader/follower teardown persists an exact target/runtime-generation cleanup intent before Telegram deletion; an interrupted attempt remains retryable by the current or successor leader under current authority and clears only after confirmed deletion. If a follower's graceful envelope is missed, the leader may create the same fenced cleanup only after its heartbeat is stale, the OS confirms the exact registered PID no longer exists, cleanup remains enabled, and no replacement registration can overtake deletion. Heartbeat loss alone, live/unknown process liveness, IPC failure, and auth failure remain non-destructive. Invalid-config recovery makes the setting unresolved and therefore skips destructive cleanup. Manual `/telegram-disconnect` keeps its confirmation and teardown behavior regardless of this setting.
121
121
  - `assistant.proactivePush` defaults to `true`; omit it to keep projection enabled, or set it explicitly to `false` to disable it. When enabled, each completed public assistant text block from local or autonomous work is projected to the authorized Telegram target once and in source order. This includes visible intermediate commentary/checkpoints and the final block. It excludes token deltas, hidden reasoning, tool calls/arguments/results, Telegram-owned turns, empty blocks, and stale authority. Projection uses the configured Rich or HTML assistant renderer and binds admitted work to the exact target, profile/token transport generation, direct leader epoch or follower registration generation, and session generation. The old top-level `proactivePush` key is ignored; move the setting manually under `assistant`.
122
- - `assistant.activity` accepts exactly `"quiet"` or `"verbose"` and resolves omitted or invalid values to `"quiet"`. Quiet preserves the answer-only behavior. Verbose adds provider-exposed reasoning as an ephemeral target-bound Rich `Thinking` draft. Completed tool activity uses ordinary HTML `sendMessage`/`editMessageText`, with each tool represented by a standard expandable blockquote containing bounded redacted arguments, retained updates, results, and errors; tool output never uses Rich Messages. Consecutive tools coalesce only inside the same ordered activity segment and bounded message. Legacy `assistant.activityVerbosity` is read only when `assistant.activity` is absent and is removed by the next Activity Settings write.
122
+ - `assistant.activity` accepts exactly `"quiet"`, `"thinking"`, `"tools"`, or `"verbose"` and resolves omitted or invalid values to `"quiet"`. `thinking` shows only provider-exposed thinking, `tools` shows only completed tool activity, and `verbose` shows both. Thinking and tools use persistent ordinary HTML `sendMessage`/`editMessageText` disclosures with standard expandable blockquotes; thinking carries a `🧠` header with the current Pi thinking level and bounded redacted text, while each tool contains bounded redacted arguments, retained updates, results, and errors. Activity output never uses Rich Messages and disables link previews on every send/edit. Consecutive tools coalesce only inside the same ordered activity segment and bounded message. Legacy `assistant.activityVerbosity` is read only when `assistant.activity` is absent and is removed by the next Activity Settings write.
123
123
  - Voice Reply `hidden`: no `voice.replyMode` key is persisted; legacy `manual` resolves to this silent default. `mirror` adds `[voice] delivery: automatic voice` only to voice/audio-input turns, while `always` adds the same effective line to every Telegram turn.
124
124
  - Agent activity status is not configurable in this release. Telegram uses native `sendChatAction(typing)` / product `...active` status as the only automatic in-chat work signal before the final reply.
125
125
  - `assistant.timeInjection` accepts `hidden`, `always`, or `interval` and defaults to `hidden`. Settings writes the selected value there, including `hidden`; the old `time.injectionMode` key is ignored and is not migrated. `time.interval` remains the optional interval duration in milliseconds.
package/docs/ui-style.md CHANGED
@@ -33,8 +33,9 @@ Use emoji as stable semantic markers, not decoration. Emoji carry transportable
33
33
  | `👄` | Voice reply policy | Voice reply settings row and detail card | Not a generic audio attachment marker. |
34
34
  | `🕒` | Time injection / wall-clock context | Time injection settings row and detail card | Clock-face marker with hands; not a generic duration/progress marker. |
35
35
  | `📌` | Proactive push / pinned behavior | Proactive push settings row and detail card | Not generic active/selected state. |
36
- | `🔬` | Activity / technical detail | Activity settings row and detail card | Chooses quiet versus verbose bridge activity; not a generic diagnostics marker. |
37
- | `🛠` | Executed tool activity | Collapsed verbose tool disclosure summaries | One marker per tool summary; tool result state remains text (`done`/`failed`). |
36
+ | `🔬` | Activity / technical detail | Activity settings row and detail card | Chooses quiet, thinking, tools, or verbose bridge activity; not a generic diagnostics marker. |
37
+ | `🧠` | Model thinking activity | Collapsed persistent thinking disclosure summaries | One marker per thinking message; header text reports the current thinking level such as `high`. |
38
+ | `🛠` | Executed tool activity | Collapsed tool disclosure summaries | One marker per tool summary; tool result state remains text (`done`/`failed`). |
38
39
  | `📎` | Attachment | Attachment summaries, queue rows for attachment-only turns | Not for thread binding. |
39
40
 
40
41
  ### Command And Control Actions
package/index.ts CHANGED
@@ -506,9 +506,8 @@ export default function (pi: Pi.ExtensionAPI) {
506
506
  const assistantOutputRuntime = assistantOutputBindingRuntime.runtime;
507
507
  activityVerbosityRuntime =
508
508
  ActivityVerbosity.createTelegramActivityVerbosityRuntime({
509
- isVerbose() {
510
- return configControls.getActivityVerbosity() === "verbose";
511
- },
509
+ getActivityMode: configControls.getActivityVerbosity,
510
+ getThinkingLevel,
512
511
  resolveTarget(event) {
513
512
  return event.target ?? proactivePushTargetGetter();
514
513
  },
@@ -516,7 +515,6 @@ export default function (pi: Pi.ExtensionAPI) {
516
515
  isAuthorityActive:
517
516
  assistantOutputBindingRuntime.authority.isAuthorityActive,
518
517
  sendMessage,
519
- sendRichMessageDraft,
520
518
  editMessageText: editTelegramMessageText,
521
519
  recordFailure(operation, event, error) {
522
520
  recordRuntimeEvent("activity", error, {
@@ -1,25 +1,24 @@
1
1
  /**
2
2
  * Bridge-owned Telegram activity verbosity projection
3
3
  * Zones: telegram activity, rich rendering, operational delivery
4
- * Owns ephemeral reasoning drafts and bounded durable tool disclosures; excludes activity normalization, assistant answer rendering, and transport authority policy
4
+ * Owns persistent bounded thinking and tool disclosures; excludes activity normalization, assistant answer rendering, and transport authority policy
5
5
  */
6
6
 
7
7
  import type { TelegramActivityEvent } from "./activity.ts";
8
8
  import { escapeHtml } from "./rendering.ts";
9
9
  import type {
10
10
  TelegramEditMessageTextBody,
11
- TelegramRichText,
12
11
  TelegramSendMessageBody,
13
- TelegramSendRichMessageDraftBody,
14
12
  TelegramSentMessage,
15
13
  } from "./telegram-api.ts";
16
14
  import type { TelegramTarget } from "./target.ts";
17
15
 
18
16
  export const TELEGRAM_TOOL_ACTIVITY_ICON = "🛠";
17
+ export const TELEGRAM_THINKING_ACTIVITY_ICON = "🧠";
19
18
  export const TELEGRAM_ACTIVITY_DETAIL_MAX_CHARS = 1_200;
20
19
  export const TELEGRAM_ACTIVITY_MESSAGE_MAX_CHARS = 3_900;
21
20
  export const TELEGRAM_ACTIVITY_MESSAGE_MAX_TOOLS = 6;
22
- export const TELEGRAM_REASONING_DRAFT_MAX_FRAMES = 24;
21
+ export const TELEGRAM_REASONING_MESSAGE_MAX_FRAMES = 24;
23
22
  export const TELEGRAM_REASONING_BUFFER_MAX_CHARS = 1_200;
24
23
  export const TELEGRAM_TOOL_UPDATE_MAX_ENTRIES = 4;
25
24
 
@@ -40,6 +39,11 @@ interface ToolMessage {
40
39
  target: TelegramTarget;
41
40
  }
42
41
 
42
+ interface ReasoningMessage {
43
+ messageId: number;
44
+ target: TelegramTarget;
45
+ }
46
+
43
47
  function targetEquals(left: TelegramTarget, right: TelegramTarget): boolean {
44
48
  return left.chatId === right.chatId && left.threadId === right.threadId;
45
49
  }
@@ -57,35 +61,6 @@ function redactActivityText(text: string): string {
57
61
  );
58
62
  }
59
63
 
60
- function renderReasoningRichText(text: string): TelegramRichText {
61
- const parts: TelegramRichText[] = [];
62
- let cursor = 0;
63
- while (cursor < text.length) {
64
- const codeStart = text.indexOf("`", cursor);
65
- const boldStart = text.indexOf("**", cursor);
66
- const starts = [codeStart, boldStart].filter((index) => index >= 0);
67
- if (starts.length === 0) {
68
- parts.push(text.slice(cursor));
69
- break;
70
- }
71
- const start = Math.min(...starts);
72
- if (start > cursor) parts.push(text.slice(cursor, start));
73
- const marker = start === codeStart ? "`" : "**";
74
- const end = text.indexOf(marker, start + marker.length);
75
- if (end < 0) {
76
- parts.push(text.slice(start));
77
- break;
78
- }
79
- parts.push({
80
- type: marker === "`" ? "code" : "bold",
81
- text: text.slice(start + marker.length, end),
82
- });
83
- cursor = end + marker.length;
84
- }
85
- if (parts.length === 0) return "";
86
- return parts.length === 1 ? parts[0]! : parts;
87
- }
88
-
89
64
  function formatActivityJson(value: unknown, depth = 0): string[] {
90
65
  const indent = " ".repeat(depth);
91
66
  if (Array.isArray(value)) {
@@ -206,13 +181,14 @@ function toolMessageSize(tools: readonly ToolActivity[]): number {
206
181
  return renderTelegramToolActivityHtml(tools).length;
207
182
  }
208
183
 
209
- function draftIdForActivity(activityId: string): number {
210
- let hash = 2166136261;
211
- for (const character of activityId) {
212
- hash ^= character.charCodeAt(0);
213
- hash = Math.imul(hash, 16777619);
214
- }
215
- return (hash >>> 0) || 1;
184
+ export function renderTelegramThinkingActivityHtml(
185
+ text: string,
186
+ thinkingLevel: string,
187
+ ): string {
188
+ return [
189
+ `<b>${TELEGRAM_THINKING_ACTIVITY_ICON}&#160; thinking:</b> <code>${escapeHtml(thinkingLevel)}</code>`,
190
+ `<blockquote expandable>${escapeHtml(text)}</blockquote>`,
191
+ ].join("\n");
216
192
  }
217
193
 
218
194
  export interface TelegramActivityVerbosityRuntime {
@@ -223,19 +199,17 @@ export interface TelegramActivityVerbosityRuntime {
223
199
  }
224
200
 
225
201
  export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
226
- isVerbose: () => boolean;
202
+ getActivityMode: () => "quiet" | "thinking" | "tools" | "verbose";
203
+ getThinkingLevel: () => string;
227
204
  resolveTarget: (event: TelegramActivityEvent) => TelegramTarget | undefined;
228
205
  captureAuthority: () => TAuthority;
229
206
  isAuthorityActive: (authority: TAuthority) => boolean;
230
207
  sendMessage: (body: TelegramSendMessageBody) => Promise<TelegramSentMessage>;
231
- sendRichMessageDraft: (
232
- body: TelegramSendRichMessageDraftBody,
233
- ) => Promise<boolean>;
234
208
  editMessageText: (
235
209
  body: TelegramEditMessageTextBody,
236
210
  ) => Promise<"edited" | "unchanged">;
237
211
  recordFailure?: (
238
- operation: "reasoning-draft" | "tool-send" | "tool-edit",
212
+ operation: "reasoning-send" | "reasoning-edit" | "tool-send" | "tool-edit",
239
213
  event: TelegramActivityEvent,
240
214
  error: unknown,
241
215
  ) => void;
@@ -248,8 +222,10 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
248
222
  let target: TelegramTarget | undefined;
249
223
  let reasoningBuffer = "";
250
224
  let reasoningChars = 0;
251
- let reasoningDraftFrames = 0;
252
- let lastReasoningDraftChars = 0;
225
+ let reasoningMessageFrames = 0;
226
+ let lastReasoningMessageChars = 0;
227
+ let reasoningMessage: ReasoningMessage | undefined;
228
+ let reasoningBlocked = false;
253
229
  let toolMessage: ToolMessage | undefined;
254
230
  const tools = new Map<string, ToolActivity>();
255
231
  const toolOrder: string[] = [];
@@ -260,8 +236,10 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
260
236
  target = undefined;
261
237
  reasoningBuffer = "";
262
238
  reasoningChars = 0;
263
- reasoningDraftFrames = 0;
264
- lastReasoningDraftChars = 0;
239
+ reasoningMessageFrames = 0;
240
+ lastReasoningMessageChars = 0;
241
+ reasoningMessage = undefined;
242
+ reasoningBlocked = false;
265
243
  toolMessage = undefined;
266
244
  tools.clear();
267
245
  toolOrder.length = 0;
@@ -269,7 +247,7 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
269
247
  const hasAuthority = (): boolean =>
270
248
  authority !== undefined && deps.isAuthorityActive(authority);
271
249
  const ensureActivity = (event: TelegramActivityEvent): boolean => {
272
- if (!deps.isVerbose()) return false;
250
+ if (deps.getActivityMode() === "quiet") return false;
273
251
  if (activityId === event.activityId) return hasAuthority();
274
252
  clearActivity();
275
253
  const resolvedTarget = deps.resolveTarget(event);
@@ -282,44 +260,67 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
282
260
  const closeToolBatch = () => {
283
261
  toolMessage = undefined;
284
262
  };
285
- const sendReasoningDraft = async (
263
+ const publishReasoning = async (
286
264
  event: TelegramActivityEvent,
287
265
  acceptedGeneration: number,
288
266
  ) => {
289
267
  if (
290
268
  generation !== acceptedGeneration ||
291
269
  !target ||
292
- !hasAuthority()
270
+ !hasAuthority() ||
271
+ reasoningBlocked
293
272
  ) {
294
273
  return;
295
274
  }
296
- const omitted = reasoningChars - reasoningBuffer.length;
297
- const text =
298
- omitted > 0
299
- ? `… [${omitted} earlier chars omitted]\n${reasoningBuffer}`
300
- : reasoningBuffer;
275
+ let retained = reasoningBuffer;
276
+ let body = "";
277
+ do {
278
+ const omitted = reasoningChars - retained.length;
279
+ const text = redactActivityText(
280
+ omitted > 0
281
+ ? `… [${omitted} earlier chars omitted]\n${retained}`
282
+ : retained,
283
+ );
284
+ body = renderTelegramThinkingActivityHtml(text, deps.getThinkingLevel());
285
+ if (body.length <= TELEGRAM_ACTIVITY_MESSAGE_MAX_CHARS) break;
286
+ retained = retained.slice(-Math.max(1, Math.floor(retained.length * 0.75)));
287
+ } while (retained.length > 1);
288
+ const canEdit =
289
+ reasoningMessage && targetEquals(reasoningMessage.target, target);
301
290
  try {
302
- await deps.sendRichMessageDraft({
303
- chat_id: target.chatId,
304
- ...(target.threadId === undefined
305
- ? {}
306
- : { message_thread_id: target.threadId }),
307
- draft_id: draftIdForActivity(event.activityId),
308
- rich_message: {
309
- blocks: [
310
- {
311
- type: "thinking",
312
- text: renderReasoningRichText(redactActivityText(text)),
313
- },
314
- ],
315
- skip_entity_detection: true,
316
- },
317
- });
291
+ if (canEdit && reasoningMessage) {
292
+ await deps.editMessageText({
293
+ chat_id: target.chatId,
294
+ message_id: reasoningMessage.messageId,
295
+ text: body,
296
+ parse_mode: "HTML",
297
+ link_preview_options: { is_disabled: true },
298
+ });
299
+ } else {
300
+ const sent = await deps.sendMessage({
301
+ chat_id: target.chatId,
302
+ ...(target.threadId === undefined
303
+ ? {}
304
+ : { message_thread_id: target.threadId }),
305
+ text: body,
306
+ parse_mode: "HTML",
307
+ link_preview_options: { is_disabled: true },
308
+ });
309
+ reasoningMessage = {
310
+ messageId: sent.message_id,
311
+ target: { ...target },
312
+ };
313
+ }
318
314
  if (generation !== acceptedGeneration) return;
319
- reasoningDraftFrames += 1;
320
- lastReasoningDraftChars = reasoningChars;
315
+ reasoningMessageFrames += 1;
316
+ lastReasoningMessageChars = reasoningChars;
321
317
  } catch (error) {
322
- deps.recordFailure?.("reasoning-draft", event, error);
318
+ deps.recordFailure?.(
319
+ canEdit ? "reasoning-edit" : "reasoning-send",
320
+ event,
321
+ error,
322
+ );
323
+ reasoningBlocked = true;
323
324
  }
324
325
  };
325
326
  const publishTool = async (
@@ -348,6 +349,7 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
348
349
  message_id: toolMessage.messageId,
349
350
  text: renderTelegramToolActivityHtml(nextTools),
350
351
  parse_mode: "HTML",
352
+ link_preview_options: { is_disabled: true },
351
353
  });
352
354
  if (generation !== acceptedGeneration) return;
353
355
  toolMessage.tools = nextTools;
@@ -360,6 +362,7 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
360
362
  : { message_thread_id: target.threadId }),
361
363
  text: renderTelegramToolActivityHtml([tool]),
362
364
  parse_mode: "HTML",
365
+ link_preview_options: { is_disabled: true },
363
366
  });
364
367
  if (generation !== acceptedGeneration) return;
365
368
  toolMessage = {
@@ -377,9 +380,17 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
377
380
  acceptedGeneration: number,
378
381
  ) => {
379
382
  if (!ensureActivity(event)) {
380
- if (activityId === event.activityId && !deps.isVerbose()) clearActivity();
383
+ if (
384
+ activityId === event.activityId &&
385
+ deps.getActivityMode() === "quiet"
386
+ ) {
387
+ clearActivity();
388
+ }
381
389
  return;
382
390
  }
391
+ const mode = deps.getActivityMode();
392
+ const showThinking = mode === "thinking" || mode === "verbose";
393
+ const showTools = mode === "tools" || mode === "verbose";
383
394
  if (
384
395
  event.type === "assistant-text-delta" ||
385
396
  event.type === "assistant-segment" ||
@@ -389,31 +400,45 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
389
400
  closeToolBatch();
390
401
  }
391
402
  if (event.type === "reasoning-delta") {
403
+ if (!showThinking) return;
392
404
  reasoningChars += event.delta.length;
393
405
  reasoningBuffer = `${reasoningBuffer}${event.delta}`.slice(
394
406
  -TELEGRAM_REASONING_BUFFER_MAX_CHARS,
395
407
  );
396
408
  if (
397
- reasoningDraftFrames < TELEGRAM_REASONING_DRAFT_MAX_FRAMES &&
398
- (reasoningDraftFrames === 0 ||
399
- reasoningChars - lastReasoningDraftChars >= 160)
409
+ reasoningMessageFrames < TELEGRAM_REASONING_MESSAGE_MAX_FRAMES &&
410
+ (reasoningMessageFrames === 0 ||
411
+ reasoningChars - lastReasoningMessageChars >= 160)
400
412
  ) {
401
- await sendReasoningDraft(event, acceptedGeneration);
413
+ await publishReasoning(event, acceptedGeneration);
402
414
  }
403
415
  return;
404
416
  }
405
417
  if (event.type === "reasoning-end") {
418
+ if (!showThinking) return;
419
+ if (reasoningChars === 0 && event.text) {
420
+ reasoningChars = event.text.length;
421
+ reasoningBuffer = event.text.slice(
422
+ -TELEGRAM_REASONING_BUFFER_MAX_CHARS,
423
+ );
424
+ }
406
425
  if (
407
- reasoningChars > lastReasoningDraftChars &&
408
- reasoningDraftFrames < TELEGRAM_REASONING_DRAFT_MAX_FRAMES
426
+ reasoningChars > 0 &&
427
+ reasoningChars > lastReasoningMessageChars &&
428
+ !reasoningBlocked
409
429
  ) {
410
- await sendReasoningDraft(event, acceptedGeneration);
430
+ await publishReasoning(event, acceptedGeneration);
411
431
  }
412
432
  reasoningBuffer = "";
413
433
  reasoningChars = 0;
434
+ reasoningMessageFrames = 0;
435
+ lastReasoningMessageChars = 0;
436
+ reasoningMessage = undefined;
437
+ reasoningBlocked = false;
414
438
  return;
415
439
  }
416
440
  if (event.type === "tool-start") {
441
+ if (!showTools) return;
417
442
  tools.set(event.toolCallId, {
418
443
  id: event.toolCallId,
419
444
  name: event.toolName,
@@ -426,6 +451,7 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
426
451
  return;
427
452
  }
428
453
  if (event.type === "tool-update") {
454
+ if (!showTools) return;
429
455
  const tool = tools.get(event.toolCallId);
430
456
  if (!tool) return;
431
457
  tool.updates.push(serializeActivityValue(event.update));
@@ -436,6 +462,7 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
436
462
  return;
437
463
  }
438
464
  if (event.type === "tool-end") {
465
+ if (!showTools) return;
439
466
  const tool = tools.get(event.toolCallId) ?? {
440
467
  id: event.toolCallId,
441
468
  name: event.toolName,
@@ -460,6 +487,13 @@ export function createTelegramActivityVerbosityRuntime<TAuthority>(deps: {
460
487
  return;
461
488
  }
462
489
  if (event.type === "agent-end" || event.type === "agent-settled") {
490
+ if (
491
+ reasoningMessage &&
492
+ reasoningChars > lastReasoningMessageChars &&
493
+ !reasoningBlocked
494
+ ) {
495
+ await publishReasoning(event, acceptedGeneration);
496
+ }
463
497
  clearActivity();
464
498
  }
465
499
  };
package/lib/config.ts CHANGED
@@ -54,7 +54,11 @@ export interface ResolvedTelegramTimeConfig {
54
54
  }
55
55
 
56
56
  export type TelegramAssistantRenderingMode = "rich" | "html";
57
- export type TelegramActivityVerbosity = "quiet" | "verbose";
57
+ export type TelegramActivityVerbosity =
58
+ | "quiet"
59
+ | "thinking"
60
+ | "tools"
61
+ | "verbose";
58
62
 
59
63
  export interface TelegramConfig {
60
64
  /** @deprecated persisted identity belongs in profiles.default; retained for effective/legacy views */
@@ -756,7 +760,14 @@ export function createTelegramActivityVerbosityGetter(
756
760
  return () => {
757
761
  const assistant = configStore.get().assistant;
758
762
  if (assistant?.activity !== undefined) {
759
- return assistant.activity === "verbose" ? "verbose" : "quiet";
763
+ if (
764
+ assistant.activity === "thinking" ||
765
+ assistant.activity === "tools" ||
766
+ assistant.activity === "verbose"
767
+ ) {
768
+ return assistant.activity;
769
+ }
770
+ return "quiet";
760
771
  }
761
772
  return assistant?.activityVerbosity === "verbose" ? "verbose" : "quiet";
762
773
  };
@@ -228,8 +228,10 @@ export function buildActivityVerbositySettingsText(
228
228
  "",
229
229
  "Choose how much technical model activity Telegram shows.",
230
230
  "",
231
- "<code>-</code> <code>quiet</code> (default): show public assistant output without reasoning or tool traffic.",
232
- "<code>-</code> <code>verbose</code>: add ephemeral available reasoning and durable collapsed tool details.",
231
+ "<code>-</code> <code>quiet</code> (default): show no thinking or tool traffic.",
232
+ "<code>-</code> <code>thinking</code>: show persistent collapsed thinking.",
233
+ "<code>-</code> <code>tools</code>: show persistent collapsed tool details.",
234
+ "<code>-</code> <code>verbose</code>: show both thinking and tools.",
233
235
  ].join("\n");
234
236
  }
235
237
 
@@ -459,7 +461,12 @@ export function buildAssistantRenderingSettingsReplyMarkup(
459
461
  export function buildActivityVerbositySettingsReplyMarkup(
460
462
  verbosity: TelegramActivityVerbosity,
461
463
  ): TelegramSettingsMenuReplyMarkup {
462
- const values: TelegramActivityVerbosity[] = ["quiet", "verbose"];
464
+ const values: TelegramActivityVerbosity[] = [
465
+ "quiet",
466
+ "thinking",
467
+ "tools",
468
+ "verbose",
469
+ ];
463
470
  return {
464
471
  inline_keyboard: [
465
472
  [{ text: "⬆️ Back", callback_data: "settings:list" }],
@@ -712,7 +719,12 @@ export async function handleTelegramSettingsMenuCallbackAction(
712
719
  }
713
720
  if (data.startsWith("settings:set:activity-verbosity:")) {
714
721
  const verbosity = data.slice("settings:set:activity-verbosity:".length);
715
- if (verbosity === "quiet" || verbosity === "verbose") {
722
+ if (
723
+ verbosity === "quiet" ||
724
+ verbosity === "thinking" ||
725
+ verbosity === "tools" ||
726
+ verbosity === "verbose"
727
+ ) {
716
728
  await deps.setActivityVerbosity(verbosity);
717
729
  await updateActivityVerbositySettingsMessage(deps);
718
730
  await deps.answerCallbackQuery(
@@ -204,10 +204,15 @@ export interface TelegramReplyParameters {
204
204
  message_thread_id?: number;
205
205
  }
206
206
 
207
+ export interface TelegramLinkPreviewOptions {
208
+ is_disabled?: boolean;
209
+ }
210
+
207
211
  export type TelegramSendMessageBody = Record<string, unknown> & {
208
212
  chat_id: number;
209
213
  text: string;
210
214
  parse_mode?: "HTML";
215
+ link_preview_options?: TelegramLinkPreviewOptions;
211
216
  reply_markup?: unknown;
212
217
  reply_parameters?: TelegramReplyParameters;
213
218
  };
@@ -327,6 +332,7 @@ export type TelegramEditMessageTextBody = Record<string, unknown> & {
327
332
  text?: string;
328
333
  rich_message?: TelegramInputRichMessage;
329
334
  parse_mode?: "HTML";
335
+ link_preview_options?: TelegramLinkPreviewOptions;
330
336
  reply_markup?: unknown;
331
337
  };
332
338
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-telegram",
3
- "version": "0.25.1",
3
+ "version": "0.25.3",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"