# Changelog

## 0.7.2: Split Text Coalescing Hotfix

- `[Text Coalescing]` Telegram text messages that look like automatic splits of one near-limit human message are now short-debounced and forwarded to π as one prompt, using a conservative 3600-character near-limit threshold. Commands, bot messages, media groups, captions, non-contiguous messages, and normal short follow-ups bypass coalescing. Impact: long pasted logs/prompts are less likely to arrive as separate π turns when Telegram chunks them.
- `[Runtime Tests]` The media-group runtime regression now waits for the real debounce instead of mixing fake timers with the polling loop, and the reaction-priority runtime test flushes pending microtasks before ending the active turn. Impact: CI should stop failing on timing-only races around delayed dispatch and queued reaction mutations.
- `[Callback Namespaces]` Current status-screen navigation callbacks now use the canonical `menu:` namespace (`menu:model`, `menu:thinking`, `menu:queue`). `status:` remains reserved as an owned legacy prefix but is no longer emitted by current UI. Impact: new inline menu callbacks align with the unified app-menu model while old `status:` payloads still cannot leak to external fallback handlers.
- `[Package]` Bumped package metadata to `0.7.2` through npm and kept the lockfile in sync.

## 0.7.1: Layered Callback Interop

- `[Callback Interop]` Unknown Telegram inline-button callback data that does not belong to pi-telegram-owned prefixes (`tgbtn:`, `menu:`, `model:`, `thinking:`, `status:`, `queue:`) is now forwarded to π as `[callback] <data>` after assistant-button, queue-menu, and app-menu handlers decline it. `docs/callback-namespaces.md` defines the shared callback namespace standard for layered extensions. Impact: layered π extensions can namespace and handle their own Telegram inline buttons without polling the same bot or forking pi-telegram.
- `[Prompt Templates]` Prompt-template aliases stay visible only inside `/start` and are no longer registered in the Telegram bot command menu. Impact: reusable π workflows remain discoverable without making Telegram's global command menu noisy.
- `[Package]` Bumped package metadata to `0.7.1` through npm and kept the lockfile in sync.

## 0.7.0: Unified App Menu & Command Template Hardening

- `[Commands]` Visible Telegram bot command menu now exposes `/start`, `/compact`, `/next`, `/continue`, `/abort`, and `/stop`; `/help`, `/status`, `/model`, `/thinking`, and `/queue` remain hidden compatibility shortcuts. `/start`, `/help`, and `/status` open one unified app menu containing command help, status rows, and inline controls. Command emoji are centralized as fixed adornments in the commands domain and reused by matching menu buttons (`🤖` model, `🧠` thinking); `/next` uses `⏩` and `/continue` uses `▶️`. `/continue` enqueues a priority Telegram-owned `continue` prompt instead of forcing the next queued item or requiring π to be idle. Impact: the visible command surface is cleaner while existing operator muscle memory still works and skills can react to queued `continue` prompts.
- `[Application Menu]` `/start` opens command help plus status rows and the inline application menu; `/queue` opens the queue section directly, the status menu Queue button shows the current queued-item count, all submenus keep Back/Main menu navigation in the top row, and queued items are listed in dispatch order with numeric labels plus `⚡`/`📎` markers. Queue menu message text uses the same HTML heading style as the other inline menus; empty queue menus render bold message text with only the Main menu navigation button instead of a disabled empty-state button. Item submenus support Back, priority toggle, and Cancel, and stale item clicks refresh the live list. Impact: queued Telegram work is inspectable and mutable from the menu control surface without relying only on reactions.
- `[Prompt Templates]` `/start` now shows a separate block for π prompt-template commands, and the Telegram bot command menu registers Telegram-safe prompt-template aliases such as `fix-tests` → `/fix_tests` when they do not conflict with built-in bridge commands or hidden shortcuts. Sending `/template_name args` from Telegram expands the matching π prompt-template file before queueing the turn. Impact: reusable π workflows are available from Telegram without duplicating prompt text manually.
- `[Keyboard]` Shared Telegram inline-keyboard reply-markup structure was extracted to `keyboard`, while `menu` owns application-control button semantics and `outbound-handlers` owns assistant-authored button semantics. Impact: inline UI domains share one Bot API shape without centralizing feature behavior.
- `[Domain DAG]` Source-module opening comments now include `Zones:` tags for cross-cutting responsibility areas such as Telegram transport, π agent lifecycle, TUI, and shared utilities. Impact: flat files keep folder-like orientation without adding directory nesting.
- `[Menu Refactor]` Queue-menu UI moved from `menu.ts` into the flat `menu-queue` domain while core queue mechanics remain in `queue`; model-menu state, scoped model pages, callback planning, and model-menu rendering moved into the flat `menu-model` domain while core model semantics remain in `model`; thinking-menu text, markup, callbacks, and rendering moved into the flat `menu-thinking` domain; status-menu payloads, callbacks, and rendering moved into the flat `menu-status` domain. Impact: `menu.ts` is smaller and queue/model/thinking/status control surfaces have dedicated UI boundaries without adding folders or changing Telegram behavior.
- `[Menu]` Busy-state messages now mention `/abort`, `/next`, and `/stop`; submenu main navigation uses top-row `⬆️ Main menu`; thinking-menu text is a compact bold heading because the selected level is already marked in the buttons; model-menu scope and pagination controls now sit at the top under Main menu, and the pagination indicator opens a compact `<b>Choose a page:</b>` picker with numbered page buttons.
- `[Queue Reactions]` Priority reactions now accept `👍`, `⚡️`, `❤️`, and `🕊`; removal reactions now accept `👎`, `👻`, `💔`, and `💩`. Impact: users can use more default Telegram reactions for queue control while keeping the same priority/removal semantics.
- `[Config]` `telegram.json` persistence now writes through a private temp file and atomic rename before restoring `0600` permissions. Impact: concurrent setup/status reload paths and interrupted writes no longer expose readers to a truncated JSON file.
- `[Status]` Main-menu status output now renders `Status: idle|active|pending|unknown` as a normal status row instead of a standalone heading; TUI status-bar `active` uses the `warning` color token.
- `[Reply Dedup]` Only the first agent message in a turn replies to the triggering prompt; subsequent messages skip `reply_to_message_id`. Impact: stacked reply headers no longer waste vertical viewport space—the first message anchors the thread and the rest deliver as independent messages. Implemented at the transport level in `buildTelegramReplyParameters` so preview delivery, voice upload, and all text paths are caught uniformly. Reset on `agent_start` via `lifecycle.ts`.
- `[Command Template]` Default timeout of 30s (`DEFAULT_COMMAND_TIMEOUT_MS`) is now exported and enforced; handler invocations may omit explicit `timeout` where the default is sufficient.
- `[Command Template]` `critical` field standardised: when `true`, leaf failure aborts the entire root composition. `attachment-handlers.ts` and `outbound-handlers.ts` composition loops implement fail-open default (continue on non-critical failure) with critical re-throw gating. Impact: the TTS pipeline (edge-tts → ffmpeg) can mark ffmpeg as critical and abort cleanly.
- `[Docs]` Handler documentation and README examples now rely on default command timeouts and keep config examples minimal; critical-step guidance remains where needed.
- `[Typing Safety]` Typing-loop send failures now update the live status through the prompt-dispatch context and still record diagnostics. Impact: transient typing failures are visible without relying only on `/telegram-status`.
- `[Type Safety]` Preview reply markup now flows through generic preview controller/runtime and agent-end finalization contracts instead of `any`. Impact: assistant-authored buttons keep their concrete inline-keyboard type through preview finalization without narrowing future preview transports.
- `[Tests]` 416 passing (was 402 before prompt-template command coverage): reply dedup, critical composition gating, queue controls, queued `/continue`, unified app menu/status rows, menu-domain splits, queue-menu navigation order, preview reply-markup typing, prompt-template command expansion, and transport-level reply-parameter dedup are all covered.

## 0.6.3: Outbound Action Syntax & Prompt Guidance

- `[Outbound Buttons]` `telegram_button: Label` now creates a label-only button whose callback prompt equals the label. Impact: button shorthand now matches the `telegram_voice: Text` inline style and leaves one canonical label-only syntax.
- `[Outbound Actions]` `telegram_voice text="..."` and `telegram_button label=... prompt="..."` now provide explicit one-line action forms. Impact: agents can keep short voice and button actions on one line without relying on body blocks.
- `[Outbound Parsing]` Hidden action bodies now stay attached to their action heads within the parser recovery window. Impact: hidden prompt and TTS bodies stay out of Telegram-visible messages.
- `[Prompt Guidance]` Telegram prompt injection is now organized by inbound context, visible output, and native outbound actions, with explicit one-line vs body `telegram_button` syntax. Impact: agents get the same operational rules with less duplicated guidance and more consistent action markup.
- `[Architecture]` Entrypoint wiring now names inbound routing, queue session lifecycle, agent lifecycle hooks, outbound reply collaborators, and repeated pi context ports before registration. Impact: `index.ts` remains the composition root while the final hook/polling registration blocks are easier to scan.
- `[Config]` Missing `telegram.json` is now handled with an explicit existence check before reading. Impact: first-run config loading keeps the empty-config fallback without using read failures as control flow.

## 0.6.2: Reload-Stale Queue Dispatch Hotfix

- `[Queue Dispatch]` Deferred post-agent-end queue dispatch is now session-bound and canceled on session shutdown. Impact: `/reload` and session replacement can no longer leave old queue timers calling stale `ExtensionContext` methods such as `ctx.isIdle()`.
- `[Typing Safety]` Typing-loop transport failures now go only to runtime diagnostics instead of updating status through an interval-captured context. Impact: typing errors remain visible in diagnostics without retaining live `ExtensionContext` in timer error paths.
- `[Lock Watcher Safety]` Ownership-loss watchers now retain only the snapshotted lock identity and stop polling without a captured live context. Impact: singleton takeover cleanup no longer needs stale-prone status refreshes from watcher callbacks.
- `[Media Group Safety]` Media-group debounce timers now flush through controller state instead of closure-capturing the inbound context. Impact: album coalescing keeps the same behavior while reducing stale-context retention in timer callbacks.

## 0.6.1: Outbound Action & Command Timeout Hardening

- `[Command Template Runtime]` Timed-out command templates now escalate from `SIGTERM` to `SIGKILL` when the child process does not exit. Impact: attachment and outbound-handler pipelines no longer hang forever on commands that ignore graceful termination.
- `[Outbound Buttons]` `telegram_button` blocks may now omit the body when the callback prompt should equal the label. Impact: concise buttons such as `<!-- telegram_button label="OK" -->` work without duplicating the prompt text.
- `[Outbound Comment Parsing]` Top-level outbound comments are now recognized again after fenced code blocks closed by Markdown-valid indented or longer fences. Impact: code examples stay literal while later `telegram_voice` and `telegram_button` blocks still execute correctly.
- `[Command Template Docs]` The command-template contract now explicitly documents the strict 0.6.x shape: use `timeout`, and keep `args` as a string array of placeholder declarations. Impact: legacy `timeoutMs` and string-form `args` are not presented as supported compatibility paths.

## 0.6.0: Command Templates & Assistant-Authored Outbound Actions

- `[Outbound Actions]` Assistant replies now use hidden `telegram_voice` and `telegram_button` blocks as Telegram-native action markup. Impact: text stays in the normal Markdown answer, voice block bodies become native OGG/Opus `sendVoice` messages, and button bodies become normal queued Telegram prompt turns without agent-side transport tool calls.
- `[Outbound Semantics]` Outbound behavior is now owned by the unified `outbound-handlers` domain. Impact: voice artifacts, per-block language/rate attributes, independent multi-voice delivery, singular one-block-one-button callbacks, top-level-only comment stripping, artifact upload, and prompt reply metadata are planned and delivered as one post-`agent_end` response surface while code examples stay literal.
- `[Command Template Standard]` Command-backed handlers now share a compact shell-free template contract: no `command` field, `template` as string or `template: [...]`, `args` as declarations only, defaults via `defaults` or `{name=default}`, top-level `timeout` wrapping composed sequences, stdout-to-stdin composition piping, and `output` defaulting to `"stdout"` while allowing artifact selectors such as `"ogg"`. Impact: inbound attachment preprocessing and outbound artifact generation use the same portable automation model without provider-specific fields or shell evaluation.
- `[Handler Boundaries]` Inbound preprocessing now lives in `attachment-handlers`, outbound generated actions live in `outbound-handlers`, and reusable template mechanics live in `command-templates`. Impact: file names, mirrored tests, and docs match the actual domains instead of broad `handlers`, standalone voice, or grouped button mini-DSL boundaries.
- `[Docs]` Handler examples now use portable `/path/to/stt`, `/path/to/tts`, and `/path/to/tool` placeholders and dense command-template documentation. Impact: release docs describe what operators configure without leaking host-local skill paths or repeating the same template rules across documents.

## 0.5.2: Telegram Reply Context

- `[Telegram Replies]` Normal Telegram prompts now include quoted Telegram `reply_to_message` text/caption as a bounded `[reply]` context block. Impact: replying to an earlier Telegram message gives the agent the quoted context instead of only the new message text. Inspired by external PR #4 from @maphim.
- `[Command Safety]` Slash-command parsing still uses only the new message text/caption, and reply context is injected only while building or editing queued prompt turns. Impact: replying with `/status`, `/model`, `/stop`, and other commands still executes the command instead of becoming a normal prompt.
- `[Docs & Tests]` Updated README, architecture/context notes, package metadata, and media/turn regressions for reply-context forwarding, truncation, queued edits, and command-safe raw text extraction. Impact: the feature is documented and covered without weakening the existing queue/command split.

## 0.5.1: Stop Queue Reset Hotfix

- `[Queue Safety]` Telegram `/stop` now clears all waiting Telegram queue items, resets pending model-switch/abort-history preservation state, and then aborts the active run when possible. Impact: queued priority/default/control turns can no longer leave the bridge stopped after an abort; the next Telegram message starts from a clean queue like a fresh TUI prompt.
- `[Docs & Tests]` Updated README, architecture notes, agent context, and queue/runtime/command regressions for the new stop/reset contract. Impact: the hotfix behavior is documented and covered by the high-risk stop plus queue path.

## 0.5.0: Command Templates, Domain Boundaries & Queue UX

- `[Queue UX]` Telegram `/status` and `/model` now execute immediately, post-agent-end queue dispatch retries after pi settles idle state, and the status bar shows specific busy labels (`active`, `dispatching`, `queued`, `tool running`, `model`). Reaction priority remains local and applies to text, voice, file, image, and media-group turns without introducing pi steering semantics. Impact: controls do not get stuck behind generation, queued work no longer needs a later Telegram update to unstick, and attachment turns keep predictable ordering.
- `[Attachment Handlers]` Inbound preprocessing now uses portable `template` configs with `args`/`defaults` and ordered fallback chains, documented in `docs/command-templates.md` and `docs/attachment-handlers.md`. Impact: voice/STT primary-fallback setups work from `telegram.json` without coupling pi-telegram to private auto-tool registry internals.
- `[Domain Boundaries]` Removed the broad `registration` domain and moved registration surfaces to owners: attachments register `telegram_attach`, commands register pi `/telegram-*` commands, lifecycle registers hooks, and prompts own Telegram-specific system prompt injection. Impact: entrypoint wiring is clearer and each registration surface has focused tests.
- `[telegram_attach]` The outbound attachment tool now lives in the attachments domain with outbound limits, queueing failure events, and pi-friendly tool-result formatting. Impact: outbound file delivery behavior is owned by the same domain that queues and sends Telegram attachments.
- `[Docs & Validation]` Updated README, docs, architecture/context maps, backlog, focused coverage, and removed vendored repository-local agent skills in favor of global validation tooling. Impact: user-facing docs, validation, and package-adjacent repo contents match the 0.5.0 code shape without stale skill copies.

## 0.4.0: Singleton Locks & Attachment Handlers

- `[Locks]` Added the shared `locks.json` singleton ownership standard and documented it in `docs/locks.md`. Telegram polling ownership now lives under `@llblab/pi-telegram` in `~/.pi/agent/locks.json`, while `telegram.json` remains pure bot/user configuration. `/telegram-connect` acquires the lock, replaces stale locks, or moves live external owners here through an interactive confirmation; `/telegram-disconnect` releases it. Session initialization reads ownership state, active owners stop local polling when `locks.json` no longer points at their own `pid`/`cwd`, session replacement via `/new` suspends polling/watchers without touching explicit ownership before resuming in the new session, and a reopened pi process resumes a stale same-`cwd` lock automatically. Impact: runtime locks can be reset or moved without deleting Telegram configuration, finding the previous pi instance, or crashing on stale extension contexts.
- `[Attachment Handlers]` Added `telegram.json` inbound attachment handlers with MIME/type matching, safe command placeholder substitution, compact `[attachments] <directory>` plus `[outputs]` prompt sections, and quiet omission of empty or failed handler output. Impact: common flows such as Telegram voice transcription can happen before the agent sees the turn while keeping source attachment paths visible.
- `[Refactor]` Extracted inbound route composition from `index.ts` into `/lib/routing.ts`, keeping paired update execution, callback menus, command-or-prompt dispatch, media grouping, prompt enqueueing, queued edits, and attachment-handler turn building behind one cohesive route wiring boundary. Impact: the entrypoint stays smaller while high-risk Telegram update flow remains covered by runtime and invariant tests.

## 0.3.0: Modular Runtime, Queue Controls, Diagnostics

### Runtime Architecture

- `[Flat Domain DAG]` The extension now uses `index.ts` as the single composition root over flat, acyclic `/lib` domains. API transport, persisted config/pairing, model control, queue/lifecycle, runtime state, commands, menu UI, polling, previews, replies, rendering, media, turns, attachments, updates, setup, status, pi SDK adapters, and registration each have explicit ownership. Impact: bridge behavior is easier to locate without introducing a second entrypoint or shared bucket modules.
- `[Composition Root]` `index.ts` now focuses on live pi/Telegram ports, session-local state, and cross-domain wiring. Stable defaults and local adapters for rendering, preview limits, preview reply metadata, attachment limits, Telegram prompt prefixes, prompt suffixes, command control items, bot command registration, API runtime construction, polling controllers, prompt dispatch, reply delivery, setup prompts, queue/session lifecycle, agent hooks, and tool hooks live in their owning domains. Impact: the entrypoint is smaller and reads as orchestration instead of carrying domain behavior.
- `[Type Boundaries]` Concrete Bot API transport shapes live in `api`, queued/active turn contracts live in `queue`, persisted session state lives in `config`, media download metadata lives in `media`, model selection contracts live in `model`, and domain constants stay with their owners. Narrow structural view contracts are used where a domain only needs a projection. Impact: public module interfaces are cleaner and accidental cross-domain coupling is reduced.
- `[Runtime State]` `runtime` owns only session-local coordination primitives: queue/control/priority counters, lifecycle flags, setup guards, abort handler storage, typing-loop timers, prompt-dispatch lifecycle binding, and agent-end reset sequencing. Preview state, queue planning, command behavior, rendering, and API transport stay outside `runtime`. Impact: mutable bridge state is centralized without becoming a general-purpose behavior bucket.

### Queue, Lifecycle, And Controls

- `[Queue Core]` `queue` owns prompt/control item contracts, explicit control/priority/default lane admission rules, queue stores, active-turn state, queue mutation, dispatch readiness, prompt enqueueing, control enqueueing, session start/shutdown sequencing, and agent/tool lifecycle hooks. Impact: scheduling rules, active-turn binding, abort preservation, compaction guards, and dispatch safety are enforced in one place.
- `[Command Admission]` `/stop`, `/compact`, `/help`, and `/start` execute immediately, while `/status`, `/model`, and model-switch continuation prompts enter the control lane ahead of normal prompts. Priority reactions promote waiting prompts into the priority lane without bypassing control actions. Asynchronous control-item execution is serialized so new prompts or controls cannot dispatch while a queued `/status` or `/model` action is still settling. Impact: Telegram controls stay responsive while normal messages remain predictably ordered.
- `[Model Control]` `model` owns model identity, thinking levels, scoped model pattern parsing/resolution/sorting, current-model state, in-flight model-switch state, restart eligibility, delayed abort decisions, continuation prompt construction, and model-switch controller runtime binding. Impact: model selection, scoped menus, and in-flight restart behavior have one cohesive home.
- `[Commands And Menus]` `commands` owns slash-command parsing, command metadata, command-message targets, command execution modes, control-queue adapters, bot command registration, and stop/compact/status/model/help side effects. The Telegram bot command menu no longer exposes `/debug`; diagnostics live in pi-side `/telegram-status` and the pi TUI. `menu` owns inline status/model/thinking UI state, model-menu caching, callback routing, callback planning, render payloads, and menu message updates. Impact: Telegram controls can be tested without reading the full runtime composition.

### Telegram Delivery, Rendering, And Files

- `[Rendering]` `rendering` owns Telegram HTML Markdown scanning, escaping, preview snapshots, raw HTML chunking, long-message splitting, table/list formatting, grapheme/display-width-aware table padding for emoji and wide Unicode text, nested quote flattening, link safety, task-list handling, and literal code preservation. Impact: Telegram output stays readable on narrow clients while avoiding malformed HTML and broken code blocks.
- `[Registration]` The Telegram before-agent prompt suffix now reminds the assistant to prefer narrow table columns because Telegram is often read on phone-width screens where wide monospace tables become unreadable. Impact: Telegram-originated tabular answers are more likely to fit mobile chats before renderer-level formatting is applied.
- `[Preview And Replies]` `preview` owns streaming preview lifecycle, draft/editable-message transport choices, flush scheduling, preview finalization, and assistant-message hooks, while defaulting preview reply metadata through the `replies` helper instead of threading it through `index.ts`. `replies` owns final rendered-message delivery, reply parameters, assistant-message extraction, plain/Markdown replies, interactive message delivery, and split-message reply metadata. Impact: rich previews, final replies, errors, attachment notices, and uploads are tied to the source Telegram prompt when possible and degrade safely when Telegram cannot attach the reply.
- `[Files And Attachments]` `api` owns Bot API calls, retries, runtime error recording, temp-dir cleanup, inbound file limits, lazy bot-token clients, chat actions, and file downloads. `media` owns inbound text/media extraction, file-info normalization, media-group debounce, and download assembly. `attachments` owns outbound attachment queueing, atomic multi-file staging, stat checks, outbound limits, photo/document classification, and queued attachment sending. Impact: inbound downloads and outbound uploads are size-limited by default, large files fail predictably without leaving partial attachment batches staged, and outbound artifacts flow through `telegram_attach`.
- `[Config And Setup]` `config` owns `telegram.json`, bot-token/allowed-user state, single-user authorization, and first-user pairing. `setup` owns token prompting, stored-token/env fallback selection, validation, and guarded setup orchestration. Impact: pairing and setup behavior stays consistent across `/telegram-setup`, `/telegram-connect`, `/start`, and update routing.

### Observability, Packaging, And Validation

- `[Status And Diagnostics]` `/telegram-status` now reports bridge diagnostics as grouped line-by-line pi notification sections separated by blank lines, ending with the redacted recent runtime/API event ring after connection, polling, execution, and queue state such as active turn, queue depth, queue lanes, compaction, active tool count, and pending model-switch state. Transport/API failures, polling/update failures, prompt dispatch failures, control action failures, typing failures, compaction failures, setup failures, session lifecycle failures, and attachment queue/delivery failures are recorded in the ring, while benign unchanged edit responses and empty draft-clear attempts do not pollute it. Impact: operators can diagnose bridge stalls and transport/runtime failures after the fact without exposing a Telegram-side debug command.
- `[Package Contents]` The npm package uses an explicit allowlist and keeps the tracked lockfile. Impact: published tarballs exclude tests and internal context files while preserving predictable release contents.
- `[Validation]` The project now ships typecheck, test, audit, package dry-run, and combined `validate` scripts plus GitHub Actions validation. Regression coverage spans rendering fixtures, queue/runtime/session behavior, command admission, lane contracts, invalid-lane rejection, setup, registration, replies, polling, updates, attachments, media, config, model resolution, preview timers, and extension-runtime flows. Impact: release checks catch type errors, dependency issues, package-content drift, rendering regressions, queue/lifecycle races, and architecture-boundary drift before publishing.
- `[Architecture Guards]` Invariant tests enforce an acyclic local import graph, ban `lib/constants.ts` and `lib/types.ts`, keep empty interface-extension shells collapsed into clearer type aliases, centralize direct pi SDK imports, keep `index.ts` source code free of direct Node runtime imports, local helper declarations, local arrow adapters, direct `process.env`, and direct `pi.*` receiver access, keep `runtime` and structural leaf domains isolated, guard menu/model, API/config, media/update/API, and attachment/queue/media/API boundaries, and require project TypeScript files to keep responsibility headers. Impact: the Flat Domain DAG shape and file-boundary documentation stay protected as domains continue to evolve.
- `[Refactor]` Reopened compression/decomposition/refactor/consistency passes tightened menu-domain message render/send plumbing, compressed repeated menu/media/attachment/runtime/API/model/queue test harness shapes, extracted shared runtime context, model-context, dispatch-event, Telegram config, deferred-response, API-response, rich-response, prompt-block, fetch-method, API response/client/fetch-restore, runtime fetch/model, model-test, queue-model, queue prompt/control/item-type, registration active-turn, menu-model, and pi API test fixtures, migrated runtime integration tests onto those fixtures, replaced ad hoc structural casts with owning-domain or test-local helpers where practical, and removed avoidable test casts from attachment, polling, update, model, reply, menu, pi-adapter, and registration suites. Impact: the codebase stays easier to extend without changing Telegram runtime behavior.

## 0.2.x: Fork Genesis

- `[Turns]` Preserved existing attachment-path blocks and aborted-turn history context when a still-queued Telegram message is edited. Impact: caption edits no longer make queued prompts lose their downloaded file references or prior-message context.
- `[Polling]` Persisted Telegram long-poll offsets only after each update is handled successfully. Impact: a handler failure no longer marks an unprocessed Telegram update as consumed, reducing the chance of silently dropping inbound messages.
- `[Telegram API]` Added HTTP-status-aware Bot API response parsing, malformed-success handling, retry/backoff for 429 and 5xx Bot API responses, streaming Telegram downloads with size-limit checks, file-backed multipart upload blobs, partial-download cleanup on limit failures, startup cleanup for stale Telegram temp files, and UUID-based sanitized temp filenames. Impact: Telegram transport failures now report clearer status/description details, transient Telegram throttling/server failures get retried automatically, oversized inbound files are rejected before or during download, outbound multipart sends avoid preloading files into memory, partial and stale temp files are removed, and downloaded files are less prone to timestamp collisions or unsafe local names.
- `[Rendering]` Escaped generated HTML attributes separately, sanitized code-fence language classes, and chunked raw HTML-mode output below Telegram length limits with balanced tag reopening across raw HTML chunks. Impact: generated Telegram HTML is harder to malformed through link or fence metadata and long raw-HTML replies no longer exceed Telegram's message size limit or break active tags across chunk boundaries.
- `[Preview]` Serialized overlapping preview flushes through a single in-flight flush chain. Impact: rapid streaming updates no longer allow concurrent Telegram edit calls to overwrite newer preview text with stale snapshots.
- `[Polling]` Added a bounded poisoned-update policy for repeatedly failing Telegram updates. Impact: one malformed or consistently failing update can no longer stall the long-poll loop forever; after the retry threshold, the bridge records and advances past it.
- `[Menu]` Added short-lived model-menu input caching plus TTL/LRU cleanup for stored inline menu state. Impact: repeated `/status` and `/model` interactions do less settings/model-registry work, while old Telegram inline keyboards expire predictably instead of accumulating for the whole session.
- `[Updates]` Routed Telegram `edited_message` updates separately from new messages and applied edits to matching queued turns. Impact: editing a still-queued Telegram message updates the pending prompt instead of enqueueing a duplicate turn.
- `[Refactor]` Moved shared Telegram Bot API transport shapes out of `index.ts` into `lib/types.ts`. Impact: the entrypoint is smaller and future runtime extraction can reuse one type boundary instead of keeping local duplicate interfaces.
- `[Refactor]` Moved Telegram media-group debounce and pending-group removal into the existing media domain with mirrored tests. Impact: album coalescing and reaction/delete cleanup are easier to validate without reading the full extension entrypoint, while avoiding an unnecessary extra domain file.
- `[Refactor]` Extracted Telegram slash-command parsing and command-action routing into `lib/commands.ts` with mirrored tests, and moved queued-turn text replacement for edited messages into the turn domain. Impact: command normalization/execution planning and queued edit mutations are reusable, while the entrypoint keeps less local runtime state logic.
- `[Rendering]` Hardened link rendering so absolute links stay clickable, markdown-heavy link labels reduce to plain clickable labels, tooltip titles are ignored safely, balanced-parenthesis URLs stay intact, and unsupported link forms degrade without broken anchors. Impact: Telegram replies now keep more links usable while avoiding malformed output for relative, reference-style, or footnote-like link syntax.
- `[Preview]` Evolved rich streaming from first-chunk snapshots to stable-block previews with a conservative plain tail fallback, while preserving original blank-line spacing between rendered blocks and keeping headings visually separated from following blocks. Impact: closed top-level Markdown blocks now stream as rich Telegram HTML before finalization, incomplete fences, quotes, lists, and other trailing work remain readable without producing broken rich formatting, preview/final block spacing no longer collapses extra empty lines, and headings no longer visually merge into following code blocks when source Markdown omits a blank line.
- `[Refactor]` Split preview concerns so runtime transport and finalization live in the preview domain while preview snapshot derivation lives in the rendering domain. Impact: rich streaming can evolve independently from final reply delivery while keeping preview appearance decisions closer to the Telegram renderer.
- `[Streaming]` Switched Telegram previews from plain draft-first text to rich first-chunk message editing, so formatting appears during generation instead of only after finalization. Impact: users now see richer streamed output earlier, while final replies still replace the preview with fully rendered Telegram HTML.
- `[Rendering]` Preserved leading indentation on the first Markdown line, kept numeric markers for ordered task lists in both preview and final Telegram rendering, and stopped reinterpreting standalone `[x]` or `[ ]` prose as inline checkboxes. Impact: nested content no longer flattens when a message starts with indentation, numbered checklists keep their ordered semantics, and literal checklist-like prose stays literal.
- `[Queue UI]` Marked liked high-priority queued Telegram turns with `⬆` in the pi status-bar queue preview. Impact: operators can now distinguish reaction-promoted turns from normal queued prompts at a glance.
- `[Docs]` Added short responsibility header comments to every project `.ts` file. Impact: file boundaries are easier to understand while navigating the growing `/lib` split.
- `[Naming]` Renamed extracted domain modules and mirrored regression suites to use repo-scoped bare domain filenames such as `api.ts`, `queue.ts`, and `queue.test.ts` instead of repeating `telegram-*` in every path. Impact: the internal topology is easier to scan and stays aligned with the repository-level Telegram scope.
- `[Controls]` Expanded Telegram session controls with a richer `/status` view, inline model selection, and thinking-level controls, and fixed the callback-selection path so idle model and thinking picks apply immediately instead of only becoming visible after a later Telegram interaction. Impact: more bridge configuration can be managed directly from Telegram with more predictable immediate feedback.
- `[Queue]` Upgraded Telegram turn queueing with previews, reaction-driven prioritization/removal, media-group handling, aborted-turn history preservation, and safer dispatch gating. Impact: follow-up handling is more transparent and less prone to lifecycle races.
- `[Rendering]` Added Telegram-oriented Markdown rendering and hardened reply streaming/chunking behavior, including narrower monospace Markdown table output without outer side borders, monospace list markers for unordered and ordered lists, and flattened nested quote indentation inside a single Telegram blockquote. Impact: formatted replies render more reliably while preserving literal code blocks and using width more efficiently on narrow Telegram clients.
- `[Runtime]` Hardened attachment delivery, polling/runtime behavior, Telegram session integration, preview-finalization and reply-transport routing into the replies domain, lazy Telegram API client routing into the Telegram API domain, turn-building extraction into its own domain, menu/model-resolution plus menu-state, pure menu-page derivation, pure menu render-payload builders, menu-message runtime, callback parsing, callback entry handling, callback mutation helpers, full model-callback planning and execution, and interface-polished callback effect ports into the menu domain, direct execute-from-update routing into the updates domain, model-switch restart glue extraction into the model-switch domain, and tool/command/lifecycle-hook registration extraction into a dedicated registration domain. Impact: the bridge is more robust as a daily Telegram frontend for pi.
- `[Metadata]` Updated package repository metadata to point at the `llblab/pi-telegram` fork and renamed the npm package to `@llblab/pi-telegram` with public scoped publish settings. Impact: published package links no longer send users to stale upstream coordinates and the package can be published under the fork-owned npm scope.
- `[Validation]` Added lightweight regression tests for Telegram Markdown rendering, queue/runtime/agent-loop/session/control/dispatch, replies, polling, updates, attachments, registration, turns, menu, and Telegram API/media/config helpers, including quote/list, table, link/code, mixed-link/code chunking, mixed-block chunk transitions, long multi-block, long-quote, long inline-formatting chunk boundaries, list-code-quote-prose chunk transitions, narrower monospace table rendering without outer side borders, monospace unordered and ordered list markers, flattened nested quote indentation inside one Telegram blockquote, inbound poll/pair/dispatch runtime cases, preview finalization, aborted-turn history carry-over, queued-status/model-after-agent-end sequencing, compaction gating, media-group debounce dispatch, direct menu callback planning and execution, pure menu-page derivation, pure menu render-payload builders, reaction-driven reprioritization/removal, immediate in-flight model-switch continuation, delayed abort-after-tool-completion, lazy Telegram API client routing, turn-building, and scoped-model resolution. Impact: key renderer and queue invariants now have repeatable automated coverage across the known high-risk bridge paths.
- `[Model Switching]` Enabled `/model` during an active Telegram-owned run by applying the new model and continuing on the new model automatically, delaying the abort until the current tool finishes when needed. Impact: Telegram can now approximate pi's manual stop-switch-continue workflow with fewer mid-tool aborts.
- `[Queue Core]` Introduced queued item kinds and explicit queue-lane ordering semantics so prompt turns and synthetic control actions share one ordering model, then regrouped the extracted helpers into flatter domain-oriented `/lib` modules such as queue, replies, polling, updates, attachments, turns, menu, Telegram API, and registration while keeping `index.ts` as the entrypoint. Prompt items now stay queued until `agent_start` consumes the dispatched turn, which restores correct active-turn binding for previews and final delivery. Impact: the bridge now has a clearer foundation for scheduling async extension operations alongside Telegram prompts without losing a single obvious runtime entry file.
- `[Registration]` Moved extension tool, command, and lifecycle-hook binding into the registration domain and added registration-focused regression coverage. Impact: extension wiring is easier to reason about and test without dragging full runtime state into every registration change.
- `[Control Queue]` Moved `/status` and `/model` command handling onto high-priority control queue items. Impact: control actions can wait safely behind the current run while still jumping ahead of normal queued prompts.
- `[Setup]` `/telegram-setup` now shows the stored bot token first, otherwise prefills from common Telegram bot environment variables before falling back to the placeholder, using an actual prefilled editor when a real default exists. Impact: repeat setup respects local saved state while first-run and secret-managed setup stay fast.
