@llblab/pi-kit 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/node_modules/@llblab/pi-telegram/BACKLOG.md +1 -0
  4. package/node_modules/@llblab/pi-telegram/CHANGELOG.md +11 -0
  5. package/node_modules/@llblab/pi-telegram/README.md +4 -2
  6. package/node_modules/@llblab/pi-telegram/docs/README.md +1 -1
  7. package/node_modules/@llblab/pi-telegram/docs/architecture.md +9 -5
  8. package/node_modules/@llblab/pi-telegram/docs/compact-matrix-literal.md +39 -11
  9. package/node_modules/@llblab/pi-telegram/docs/generative-apps.md +2 -2
  10. package/node_modules/@llblab/pi-telegram/docs/multi-instance-bus.md +1 -1
  11. package/node_modules/@llblab/pi-telegram/docs/outbound.md +6 -4
  12. package/node_modules/@llblab/pi-telegram/docs/public-api.md +1 -1
  13. package/node_modules/@llblab/pi-telegram/index.ts +12 -1
  14. package/node_modules/@llblab/pi-telegram/lib/bindings.ts +12 -3
  15. package/node_modules/@llblab/pi-telegram/lib/keyboard.ts +5 -3
  16. package/node_modules/@llblab/pi-telegram/lib/locks.ts +99 -16
  17. package/node_modules/@llblab/pi-telegram/lib/outbound-buttons.ts +72 -15
  18. package/node_modules/@llblab/pi-telegram/lib/outbound-markup.ts +81 -9
  19. package/node_modules/@llblab/pi-telegram/lib/outbound.ts +2 -0
  20. package/node_modules/@llblab/pi-telegram/lib/polling.ts +142 -30
  21. package/node_modules/@llblab/pi-telegram/lib/prompts.ts +8 -6
  22. package/node_modules/@llblab/pi-telegram/lib/queue.ts +4 -0
  23. package/node_modules/@llblab/pi-telegram/lib/replies.ts +1 -1
  24. package/node_modules/@llblab/pi-telegram/lib/status.ts +4 -0
  25. package/node_modules/@llblab/pi-telegram/lib/updates.ts +6 -0
  26. package/node_modules/@llblab/pi-telegram/package.json +1 -1
  27. package/node_modules/@llblab/pi-telegram/skills/generated-control-surface/SKILL.md +4 -2
  28. package/node_modules/@llblab/pi-telegram/skills/generated-control-surface/references/layout-and-state.md +4 -2
  29. package/node_modules/@llblab/pi-telegram/skills/generative-apps/SKILL.md +4 -3
  30. package/node_modules/@llblab/pi-telegram/skills/telegram-bridge/SKILL.md +19 -8
  31. package/node_modules/@llblab/pi-telegram/skills/telegram-bridge/references/diagnosis.md +2 -0
  32. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  All notable changes to `@llblab/pi-kit` are documented here.
4
4
 
5
+ ## 0.5.1 - 2026-09-06
6
+
7
+ - `Telegram Continuity Hotfix`: Advances the exact Telegram pin to `0.43.1`, bringing bounded persistent polling-conflict stand-down with accepted queue preservation, missing/null system-prompt normalization, and authority-fenced preview cleanup without changing the resource inventory.
8
+
9
+ ## 0.5.0 - 2026-09-05
10
+
11
+ - `Telegram Native Controls`: Advances the exact Telegram pin to `0.43.0`, bringing in-body button blocks, shared JSON/CML disabled controls, HTML footer fallback, and updated agent Skills while preserving package-owned implementations and the existing resource inventory.
12
+
5
13
  ## 0.4.0 - 2026-09-05
6
14
 
7
15
  - `Expanded Composition`: Adds exact published pins for Clean Room and opt-in State Flow alongside the portable LLBLAB Skills collection, exposing each package's own declared resources without duplicating source or runtime ownership.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Package links lead to the owning repositories for usage, documentation, issues,
15
15
  | [`@llblab/pi-codex-usage`](https://github.com/llblab/pi-codex-usage) | `0.9.4` | Compact Codex/Spark subscription-limit status |
16
16
  | [`@llblab/pi-grow-loop`](https://github.com/llblab/pi-grow-loop) | `0.7.4` | Visible continuation scheduling and bounded worker Skills |
17
17
  | [`@llblab/pi-state-flow`](https://github.com/llblab/pi-state-flow) | `0.3.0` | Opt-in validated state handoffs between agent runs |
18
- | [`@llblab/pi-telegram`](https://github.com/llblab/pi-telegram) | `0.42.4` | Telegram companion, queues, files, voice, controls, and Generative Apps guidance |
18
+ | [`@llblab/pi-telegram`](https://github.com/llblab/pi-telegram) | `0.43.1` | Telegram companion, queues, files, voice, controls, and Generative Apps guidance |
19
19
  | [`@llblab/skills`](https://github.com/llblab/skills) | `1.14.0` | Portable workflows for engineering, review, design, context maintenance, and other focused tasks |
20
20
 
21
21
  Versions are exact by design. An upstream release does not change an installed kit until this repository explicitly advances the dependency and publishes a new kit version. Runtime defects and package-specific feature requests belong in the linked repository; package selection and kit installation issues belong here.
@@ -4,6 +4,7 @@ _This file owns unresolved project work only. Completed behavior belongs in `CHA
4
4
 
5
5
  - [ ] `Live-thread continuity and recovery`: Make loss and restoration of a live thread truthful and safe without discarding accepted work or deleting a currently owned target; the initial cause of the observed stale-thread API failures remains unproven.
6
6
  - [ ] Complete the remaining operator-coordinated live smoke beyond the operator-confirmed successful leader Restore: verify follower Restore, inaccessible callbacks, already-absent chooser cleanup, direct stale-target diagnostics, and preservation of accepted local work/active-turn target. Use disposable test threads. The successful leader flow does not independently prove these failure paths or establish the initial stale-thread failure cause.
7
+ - [ ] `Native in-body controls live smoke`: Extend the operator-confirmed successful current-client smoke (singleton CML and mixed JSON/CML rows between paragraphs, ordinary prompt callbacks, labeled disabled control, separate footer callback, and HTML-mode footer fallback) to an independently identified second client, follower routing, blank disabled cells, and app-method dispatch/revision rejection. Do not infer coverage from the confirmed ordinary-button flow; in-body selection uses callback acknowledgement, not body recoloring.
7
8
  - [ ] `Operator-confirmed pairing`: Replace first-contact automatic ownership with an explicit pending request that the trusted Pi interface can allow or reject before `allowedUserId` is persisted or any Telegram prompt executes; retain manual preconfiguration, bound pending-request lifetime and multiplicity, fail closed across session/transport replacement, and cover unauthorized-first-contact races.
8
9
  - [ ] `Environment-backed bot tokens`: Let each profile store an exact Pi-native `$ENV_VAR` or `${ENV_VAR}` reference in `telegram.json` instead of copying the resolved secret; preserve the originating alias when `/telegram-setup` prefills from a supported environment variable, resolve only at validation/activation boundaries, fail closed with a redacted named-variable diagnostic when unresolved, retain literal-token compatibility, and cover named profiles, reload, persistence, status, and secret-redaction paths.
9
10
  - [ ] [`Inference bypass Generative Apps`](./docs/generative-apps.md): Let the agent install and bind one managed JavaScript app owner for a generated-prompt prefix so deterministic controls can bypass model inference without creating another button grammar.
@@ -2,6 +2,17 @@
2
2
 
3
3
  > Each release keeps at most 8 outcome records of at most 512 characters.
4
4
 
5
+ ## 0.43.1: Transport And Preview Continuity
6
+
7
+ - `Conflict Stand-Down`: Stops transport after ten consecutive competing getUpdates conflicts, including ownership checks, heartbeat, monitoring, and bus teardown. Releases only the exact local lock and revokes direct authority even if release fails, while preserving accepted local queue work. A persistent terminal status and one diagnostic distinguish lost ownership from a competing external client; cancelled reconnects and stale admission cannot supersede current lifecycle work.
8
+ - `Prompt And Preview Continuity`: Treats absent/null host system prompts as empty while retaining Telegram guidance, clears completed text from preview state after successful delivery, and rejects stale session/transport completions before they can clear a replacement preview. Receipt-conflict diagnostics now include the receipt and source update ids; durable handoff verification remains fail-closed.
9
+
10
+ ## 0.43.0: Native Button Blocks
11
+
12
+ - `In-Body Controls`: Renders standalone `telegram_button` fences as native button rows between paragraphs using the same singleton/mixed JSON/CML grammar and callback ownership as footer comments. Invalid/incomplete blocks register nothing, previews hide action payloads, literal examples remain inert, and HTML mode moves controls to the footer. In-body clicks acknowledge without recoloring; operator-confirmed current-client smoke passed; cross-client/follower checks remain pending.
13
+ - `Bot API Reference`: Corrects the local `sendRichMessageDraft` table against Bot API 10.3 with generation-stop parameters and draft replacement semantics, updates affected Skill indexes, and checks parity of stop-control documentation across both draft methods. Runtime generation controls are unchanged.
14
+ - `Disabled Controls`: Adds boolean JSON disabled state and the fourth CML button atom (`1`/`true` disables, `0`/`false` enables), including label-only `{Next|||1}` and blank `{|||1}` cells with no prompt or selected style. Disabled buttons stay visible without callback registration, prompt admission, or app invocation; shared keyboard types, Generative Apps, and agent Skills follow the same contract.
15
+
5
16
  ## 0.42.4: Thread Recovery Hotfix
6
17
 
7
18
  - `Thread Restore`: Retains validated source and chooser identity when callback messages omit thread metadata, hides Restore in threadless/All choosers and explains how to supply a destination, rejects conflicting Restore instead of forwarding to the old target, and treats confirmed already-deleted chooser cleanup as complete without redispatch.
@@ -59,6 +59,8 @@ The connected Pi instance owns Telegram polling. Use `/telegram-connect <name>`
59
59
 
60
60
  After an unclean computer shutdown, `/telegram-connect` detects truncated or structurally invalid temporary ownership/routing files, quarantines only the damaged files under `tmp/telegram/recovery/`, and retries once. A journal snapshot removed by older broad temp cleanup is rebuilt when its complete segment history proves an empty result, while a revisionless snapshot is repaired from the first surviving segment's exact predecessor when the reconstructed tail validates. Otherwise the snapshot and segments are quarantined as recovery evidence, a fresh journal is published, and startup continues with an informational diagnostic instead of requiring manual JSON repair. Saved `telegram.json` configuration and runtime diagnostics remain intact. Recovery never replaces a verifiable live owner; if safe automatic recovery cannot complete, the command gives one explicit Pi-restart instruction instead of requiring deletion of the whole `tmp/` directory.
61
61
 
62
+ Persistent competing `getUpdates` clients cause a bounded transport stand-down rather than endless retries. Accepted local work remains queued/executable, but Telegram delivery stops. Inspect `/telegram-status --debug`, stop the competing client, then reconnect. See [Runtime Ownership](./docs/architecture.md#runtime-ownership).
63
+
62
64
  ### 4. Pair your Telegram account
63
65
 
64
66
  Open the bot DM and send:
@@ -131,7 +133,7 @@ Enable the optional capabilities the bridge needs in the [@BotFather](https://t.
131
133
  | Outbound artifacts | Return generated files through `telegram_attach` during active turns or explicit direct delivery. | Agents send real artifacts as files, not pasted blobs. |
132
134
  | Voice input | Route audio through configured command-template handlers, programmatic handlers, or STT providers. | Voice notes become usable prompt context. |
133
135
  | Voice output | Choose `manual`, `mirror`, or `always`; active automatic turns carry one compact `[voice] delivery: automatic voice` line, while explicit `telegram_voice` remains available. | Voice policy stays dynamic and model-legible without duplicating the full action contract in every prompt. |
134
- | Buttons | Turn top-level `telegram_button` comments into inline buttons. | Assistant-authored choices become native Telegram interactions. |
136
+ | Buttons | Use `telegram_button` comments for footer buttons or fenced blocks for native button rows between paragraphs. | Assistant-authored choices become native Telegram interactions. |
135
137
  | Generative Apps | Install or explicitly replace a reviewed `.mjs` application whose generated JSON button view may mix direct `app::method` actions with ordinary model prompts. | Repeated games, controls, tutors, and adapters compile routine interaction without losing selective model interpretation, explanation, or adaptation. |
136
138
  | Callback routing | Route known callbacks to the owner extension and unknown callbacks back into Pi. | Companion extensions can build UI without polling Telegram themselves. |
137
139
  | Threaded Mode | Run one leader plus visible follower Pi instances through named private-chat threads. | One bot can host a local multi-instance Pi organism without hidden process spawning. |
@@ -222,7 +224,7 @@ Voice notes, audio, images, PDFs, and other media can pass through configured in
222
224
 
223
225
  ### Buttons And Callbacks
224
226
 
225
- Assistant replies can include top-level hidden `telegram_button` comments containing a JSON object, adaptive JSON/CML matrix, or positional Compact Matrix Literal (CML). One adaptive matrix may mix named JSON objects with positional CML cells; separators are optional and one trailing comma is tolerated, including inside JSON objects. Top-level cells become full-width rows while nested rows group one or more buttons horizontally without an artificial parser-level width cap; generated surfaces default to five columns and use six to eight only for short position-bearing labels. CML uses `{value}`, `{label|prompt}`, `{|prompt}`, or the corresponding three-atom form with `selected_style` set to `primary`, `success`, or `danger`; omitting the first atom leaves the existing prompt-as-label fallback in charge, while the optional style still requires a non-empty prompt. It trims atom boundaries, preserves non-structural text literally, and decodes only `\|`, `\}`, and `\\`. Prefer one matrix comment for multiple buttons. Buttons use `label` plus `prompt`, or the compact `value` key when both are identical. The bridge strips every assistant-authored HTML comment from Telegram previews and final replies regardless of Markdown position or owning extension, while only recognized top-level comments activate buttons or voice; comment-only output sends no text message and the Pi terminal transcript remains unchanged. It renders valid inline buttons and routes callbacks back into Pi as queued prompts or extension-owned callback actions. Button-only replies receive the standard `☑️ **Choose an option:**` heading as automatic visible fallback text. Once a generated prompt button is accepted, only that exact button switches to its optional `selected_style` (`primary` blue by default, `success` green, or `danger` red) without altering its agent-authored label or emoji; every style still queues the selected prompt.
227
+ Assistant replies can place controls between paragraphs using standalone triple-backtick `telegram_button` blocks, or keep them in the footer using top-level hidden `telegram_button` comments. Both wrappers accept singleton cells and mixed JSON/CML matrices. Native in-body rows allow up to eight buttons; HTML compatibility moves these rows to the footer. In-body clicks acknowledge without recoloring the Rich body, while footer selection styles remain unchanged. Hidden comments accept a JSON object, adaptive JSON/CML matrix, or positional Compact Matrix Literal (CML). One adaptive matrix may mix named JSON objects with positional CML cells; separators are optional and one trailing comma is tolerated, including inside JSON objects. Top-level cells become full-width rows while nested rows group one or more buttons horizontally without an artificial parser-level width cap; generated surfaces default to five columns and use six to eight only for short position-bearing labels. CML uses `{value}`, `{label|prompt}`, `{|prompt}`, or the corresponding three-atom form with `selected_style` set to `primary`, `success`, or `danger`; omitting the first atom leaves the existing prompt-as-label fallback in charge, while the optional style still requires a non-empty prompt. A fourth atom adds disabled state: `{|Next||1}` or `{|Next||true}` disables, `0` or `false` enables (exact lowercase), and omission stays enabled; the third atom may be empty in this form. JSON uses boolean `disabled`. Disabled controls require no prompt or selected style: `{Next|||1}` shows only a label, while `{|||1}` is a blank disabled cell. Disabled controls remain visible without registering callbacks or invoking prompts/app methods. It trims atom boundaries, preserves non-structural text literally, and decodes only `\|`, `\}`, and `\\`. Prefer one matrix comment for multiple buttons. Buttons use `label` plus `prompt`, or the compact `value` key when both are identical. The bridge strips every assistant-authored HTML comment from Telegram previews and final replies regardless of Markdown position or owning extension, while only recognized top-level comments activate buttons or voice; comment-only output sends no text message and the Pi terminal transcript remains unchanged. It renders valid inline buttons and routes callbacks back into Pi as queued prompts or extension-owned callback actions. Button-only replies receive the standard `☑️ **Choose an option:**` heading as automatic visible fallback text. Once a generated prompt button is accepted, only that exact button switches to its optional `selected_style` (`primary` blue by default, `success` green, or `danger` red) without altering its agent-authored label or emoji; every style still queues the selected prompt.
226
228
 
227
229
  ### Threaded Mode And Multi-Instance Bus
228
230
 
@@ -15,7 +15,7 @@ Living index of project documentation in `/docs`.
15
15
  - [command-templates.md](./command-templates.md) — Portable command-template standard core
16
16
  - [inbound.md](./inbound.md) — Local `pi-telegram` inbound text/media handler bus, programmatic inbound handlers, registered STT provider fallbacks, legacy `attachmentHandlers` compatibility, placeholders, and fallbacks
17
17
  - [outbound.md](./outbound.md) — Local `pi-telegram` outbound-handler config, text/voice/button behavior, single-artifact Rich results, voice synthesis provider fallback priority, artifact outputs, and callback routing
18
- - [compact-matrix-literal.md](./compact-matrix-literal.md) — Adaptive Button Literal / CML v3 standard for strict JSON objects, positional cells, optional element commas, mixed bounded-depth matrices, atomic parsing, and renderer-owned width policy
18
+ - [compact-matrix-literal.md](./compact-matrix-literal.md) — Adaptive Button Literal / CML v4 standard for strict JSON objects, positional cells with disabled state, optional element commas, mixed bounded-depth matrices, atomic parsing, and renderer-owned width policy
19
19
  - [generative-apps.md](./generative-apps.md) — Generative Apps runtime and wire contract for managed `.mjs` identity, inference-bypass bindings, persistent state timelines, bounded adapters, replacement, and lifecycle; agent operation lives in the bundled `generative-apps` Skill
20
20
  - [callback-namespaces.md](./callback-namespaces.md) — Shared Telegram `callback_data` namespace standard for layered extensions
21
21
  - [updates.md](./updates.md) — Update classification and runtime handler registry that lets layered extensions observe and consume Telegram updates without owning their own polling connection
@@ -80,7 +80,7 @@ The repository uses a **Flat Domain DAG**:
80
80
  - `preview` / `replies` / `rendering`: throttled native Rich Markdown draft delivery, native final reply delivery, reply parameters, transport-limit chunking, and remaining Telegram HTML rendering for bridge-owned UI/compatibility surfaces.
81
81
  - `delivery`: public extension operational-view delivery, active-turn/instance/aggregate/authorized target policy, logical chunk handles, per-target ordering, runtime generation fencing, and the process-local runtime membrane. Its bridge adapter composes the established UI/compat reply renderer with narrow bus-aware Telegram API and ownership ports; it never exposes bot clients or Pi contexts.
82
82
  - `activity`: public normalized Pi lifecycle registration, activity/source identity, assistant segment and reasoning normalization, executed-tool events, non-blocking per-handler queues, delivery contexts, compatibility adapters, and shutdown fencing. The same domain extends assistant-output observation for connected companion projection: eligible completed local/autonomous public segments retain source order and deduplicate event identity. `bindings` assembles observation, authority, sender, and failure-projection ports; routing owns exact delivery authority, outbound composes established transformations and reply delivery, and Bot API domains implement transport. No separate proactive state-machine domain exists.
83
- - `outbound-markup`: top-level assistant action comment parsing, attribute parsing, voice reply planning, and preview/delivery stripping.
83
+ - `outbound-markup`: top-level assistant action comment/fence parsing, shared JSON/CML grammar, attribute parsing, voice reply planning, and preview/delivery stripping.
84
84
  - `outbound`: outbound text transformations, voice/button artifact delivery, and generated callback actions.
85
85
  - `generative-apps`: managed deterministic application identity, canonical installation and explicit replacement, content-addressed module loading, state timelines, cross-process transition serialization, bounded executable-plus-argv adaptation, `telegram_bind`, and pre-model-queue `app::method` invocation. It does not own Telegram transport, arbitrary shell execution, or the external application adapted by one Generative App.
86
86
  - `outbound-attachments`: `telegram_attach`, queued outbound files, stat/limit checks, ordinary photo/document delivery, and narrow single-artifact Rich Message planning/sending for probe-confirmed photo/video/audio formats. It owns known-failure fallback eligibility and ambiguous-send no-replay classification through structural error contracts without importing Bot API helpers.
@@ -92,7 +92,7 @@ The repository uses a **Flat Domain DAG**:
92
92
 
93
93
  Pi is the primary and only officially supported host. `pi-telegram` may still accept narrow, host-neutral representation differences at its existing Pi-facing boundary when they preserve native Pi behavior and do not create a second runtime policy layer:
94
94
 
95
- - `prompts` preserves either Pi's plain system-prompt string or an ordered block array supplied by a compatible host, appending Telegram guidance without collapsing host-owned blocks.
95
+ - `prompts` preserves either Pi's plain system-prompt string or an ordered block array supplied by a compatible host, appending Telegram guidance without collapsing host-owned blocks. An absent/null host system prompt is treated as empty, including the disconnected metadata-stripping path.
96
96
  - `pi` normalizes settings-manager construction that is either synchronous or asynchronous, then adapts either Pi's legacy enabled-model methods or a generic `get` / `set` settings service before model-menu reads and scoped-model persistence use it. Hosts without an explicit reload method rely on fresh asynchronous construction; durable writes still require `flush`.
97
97
  - `lifecycle` continues to require Pi's semantic `agent_settled` boundary. It does not infer terminal settlement from host-specific `agent_end`, retry, or stop events; a compatibility shim must reproduce that contract before it can safely support activity identity and unrecovered-error finalization.
98
98
 
@@ -135,6 +135,8 @@ Telegram configuration lives in `~/.pi/agent/telegram.json`. Bot/session identit
135
135
  - `/telegram-connect` acquires or moves the active profile's owner slot before polling starts. `/telegram-disconnect` keeps its destructive confirmation, then stops polling and releases only that exact slot. In Threaded Mode it tears down the disconnecting instance's bound Telegram thread: leaders delete their own thread directly, and followers send an authenticated exact-generation disconnect envelope and wait for confirmed leader cleanup before unregistering. Graceful Pi `quit` always preserves the owner slot as restart intent, allowing a reopened same-`cwd` session to reclaim the stale lease. When `threads.automaticCleanup` is enabled (the default), quit also deletes the bound Telegram tab without releasing that restart intent; disabling it preserves the tab through replacement-style suspension. Failed automatic cleanup records diagnostics and falls back to safe suspension so remaining lifecycle cleanup still runs.
136
136
  - Session start schedules polling resume asynchronously only when the owner slot already points at the current `pid`/`cwd`, or when a stale same-`cwd` owner can be safely replaced after process restart. Startup and `/resume` do not wait on leader election, Bot API probes, poller handoff, or thread reconciliation before restoring the Pi session.
137
137
  - The polling owner alone bounds `getUpdates`: each request derives its cancellation budget from Telegram's declared long-poll timeout plus 10 seconds of transport grace (10 seconds for the zero-timeout initial sync and 40 seconds for the normal 30-second poll). The request-local controller inherits poller cancellation, rejects its owner at the budget, and fences any late transport result. Ordinary Bot API and media operations do not receive speculative blanket deadlines. Existing caller signals remain authoritative through API retry waits, only retry-safe methods replay explicit retryable responses, and non-idempotent sends preserve commit-unknown evidence instead of risking duplicate mutation.
138
+ - Ten consecutive `getUpdates` conflict responses, including initial cursor sync, terminate polling with `persistent-conflict`; a successful response or a different error resets the count. The controller detaches its inner promise before notifying the locked lifecycle, avoiding teardown waiting on itself. That lifecycle stops ownership checks, lease refresh, capability monitoring, typing, and classic or bus transport (including leader health, pruning, and IPC), withdraws local direct authority, and transactionally releases only its exact lock. A failed durable release leaves local authority revoked; explicit reacquisition mints a fresh epoch. Accepted queue receipts and local Pi dispatch survive. One terminal diagnostic distinguishes lost local ownership from a competing client despite an apparently owned lock and reports cleanup failures; ordinary status refreshes retain generic `error` until transport recovers. Remove the competing client, then use `/telegram-connect`; no automatic retry continues after the terminal threshold.
139
+ - Manual and automatic polling starts share a lifecycle generation. A later suspend, disconnect, persistent-conflict stop, or accepted start invalidates older startup continuations; reconnect captures its generation before waiting for transport teardown and rechecks it before acquiring ownership and after awaited startup work. Obsolete completion or failure cannot report a successful connection or roll back a replacement. Admission rejects stale/unauthorized contexts before advancing its own startup generation, so a rejected call cannot cancel valid in-flight initialization. After awaited bus startup, thread-aware completion checks its generation before starting leader health or changing fallback/startup-option state; teardown clears health independently of the current mode flag. Startup probes, capability-monitor transitions, and observed-target transitions share an orchestration lifecycle fence and check it inside their effect-owning helpers after awaited queries, persistence, or transport work. Monitor stop also invalidates pending observations. These checks suppress subsequent state changes, fallback, health, and status effects; already-issued API/persistence calls retain their own transport/storage fencing.
138
140
  - `pollingActive` reports only whether this runtime still owns an unresolved polling lifecycle; it is not health evidence. A separate observable state records `starting`, `long-poll`, `persisting-journal`, `persisting-offset`, `retrying`, or `stopped`, together with phase start, current update id, last successful response time/count, and terminal stop reason. This distinguishes a stuck HTTP poll from downstream update work without a wall-clock stale heuristic.
139
141
  - Built-in read-only menu commands return after required local mutation and schedule context-fenced rendering and command synchronization independently, so those effects cannot withhold the next inbound offset.
140
142
  - Pi `print`/`json` run modes stay passive. Inherited child sessions that share `telegram.json` but do not own the exact `pid`/`cwd` slot must not poll or call `getUpdates` unless the operator force-takes ownership.
@@ -339,7 +341,7 @@ Assistant delivery guarantees:
339
341
  - Quoted rich replies use Telegram `rich_message` blocks as the prompt-context source when available, so `[reply]` context receives rendered plain text instead of raw `InputRichMessage.markdown` fallback text. Replied media runs through the same inbound handlers and voice transcription providers as current-message media, with provenance-scoped `[outputs|from:…]` appended inside the reply block.
340
342
  - Long native Markdown replies are split only at Telegram Rich Message transport limits; oversized fenced code, display-math, and fully wrapped inline-formatting blocks are rewrapped per chunk so persisted Rich Markdown chunks remain structurally valid.
341
343
  - When Draft previews are enabled, streaming previews pass structurally closed assistant Markdown prefixes through to `sendRichMessageDraft` with ownership checks, voice suppression, and serialized flushes. Unclosed inline spans, links, fenced code, comments, and display-math blocks are held back until a safe boundary exists. Draft failures are recorded and the failing frame is skipped instead of degrading to raw plain-message previews, because partial Markdown can be invalid while the final message remains valid.
342
- - Preview flushes are serialized so older edits cannot race newer drafts; final delivery waits for active draft flushes and does not perform a post-final draft-clear call.
344
+ - Preview flushes are serialized so older edits cannot race newer drafts; final delivery waits for active draft flushes and does not perform a post-final draft-clear call. Successful final text delivery clears the local pending preview text only while the captured session and transport remain active, so a late delivery or Rich-attachment cleanup cannot erase replacement preview state.
343
345
 
344
346
  UI/compat rendering guarantees:
345
347
 
@@ -352,12 +354,14 @@ Final delivery attaches reply metadata only where requested. Reply parameters ap
352
354
 
353
355
  Outbound files staged during an active Telegram turn are delivered after that turn completes. They use `telegram_attach`, are checked atomically per tool call, and use configurable size limits before photo/document upload. When no Telegram turn is active, `telegram_attach` sends files immediately to the paired/default chat, an assigned follower thread, or an explicit `chat_id` plus optional `thread_id`; `telegram_message` provides direct local/TUI Markdown text delivery for explicit user requests and runs the same `telegram_button` markup planner so buttons attach to that text message. Direct local/TUI delivery is singleton-controlled: classic mode requires this Pi instance to own `/telegram-connect`, while Threaded Mode followers must be registered and route through the leader-owned transport. Already accepted active-turn reply/attachment delivery remains session-local.
354
356
 
355
- Assistant-authored final-message actions use hidden top-level comments:
357
+ Assistant-authored final-message actions use hidden top-level comments, with an additional fenced wrapper for in-body buttons:
356
358
 
357
359
  - `telegram_voice` accepts one positional compact action cell or JSON object and creates one voice artifact through configured outbound handlers, programmatic voice handlers, or registered synthesis providers.
358
360
  - `telegram_button` accepts a JSON object, adaptive JSON/CML matrix, or positional Compact Matrix Literal. Named JSON objects and positional cells may coexist, with commas optional only between completed matrix or row elements. Each top-level cell creates one full-width row, while a nested row groups buttons horizontally without an artificial parser-width cap; every callback enqueues its configured prompt text as a normal Telegram prompt turn. The JSON-first grammar, positional trim/escape rules, atomic rejection, and renderer-owned width policy are specified in [Adaptive Button Literal](./compact-matrix-literal.md).
359
361
 
360
- Action recognition remains restricted to top-level column-zero comments so nested examples cannot trigger voice, buttons, or callbacks. The Telegram surface independently strips every complete assistant-authored HTML comment from previews and final delivery regardless of Markdown position or comment owner; an unclosed comment is withheld through the remaining tail, and a comment-only result sends no text message. Pi's terminal transcript and model context remain unchanged.
362
+ Standalone column-zero triple-backtick `telegram_button` blocks reuse the same cell/matrix grammar and callback store, compiling to native Rich Markdown button rows between paragraphs. Rendering validates each complete block before registering any callbacks, escapes label text, preserves disabled cells, and leaves larger enclosing fences literal. Previews hide complete and unfinished action fences. HTML mode projects those controls into the footer. In-body callbacks acknowledge without rewriting the Rich message; selected-style highlighting remains footer-only.
363
+
364
+ Action recognition remains restricted to top-level column-zero comments and exact-name button fences so nested examples cannot trigger voice, buttons, or callbacks. The Telegram surface independently strips every complete assistant-authored HTML comment from previews and final delivery regardless of Markdown position or comment owner; an unclosed comment is withheld through the remaining tail, and a comment-only result sends no text message. Pi's terminal transcript and model context remain unchanged.
361
365
 
362
366
  Unknown callback data outside owned prefixes is forwarded as `[callback] <data>` only after built-in and extension handlers decline it.
363
367
 
@@ -1,6 +1,6 @@
1
1
  # Adaptive Button Literal
2
2
 
3
- > Status: Portable CML v3 button standard; `pi-telegram` also reuses its positional-cell mechanics for compact voice actions.
3
+ > Status: Portable CML v4 button standard; `pi-telegram` also reuses its positional-cell mechanics for compact voice actions.
4
4
 
5
5
  Adaptive Button Literal is one bounded-depth matrix grammar over a shared button AST. It accepts strict JSON button objects, positional Compact Matrix Literal (CML) cells, or both in the same matrix and row. Commas between completed matrix or row elements are optional, so producers can progressively compress representation without changing runtime meaning.
6
6
 
@@ -8,7 +8,7 @@ Adaptive Button Literal is one bounded-depth matrix grammar over a shared button
8
8
  full named JSON → comma-optional adjacency → mixed named/positional cells → compact CML
9
9
  ```
10
10
 
11
- The compact form is not JSON: `{label|prompt|variant}` assigns meaning by position. The formats share semantics and topology, not syntax.
11
+ The compact form is not JSON: `{label|prompt|selected_style|disabled}` assigns meaning by position. The formats share semantics and topology, not syntax.
12
12
 
13
13
  ## Goals
14
14
 
@@ -23,7 +23,7 @@ The compact form is not JSON: `{label|prompt|variant}` assigns meaning by positi
23
23
  Every accepted payload normalizes to a non-empty ordered list of non-empty rows:
24
24
 
25
25
  ```text
26
- Cell = { label?: string, prompt?: string, value?: string, selected_style?: string }
26
+ Cell = { label?: string, prompt?: string, value?: string, selected_style?: string, disabled?: boolean }
27
27
  Rows = Cell[][]
28
28
  ```
29
29
 
@@ -58,7 +58,7 @@ A two-atom cell separates label and prompt:
58
58
  {Pause|music::pause}
59
59
  ```
60
60
 
61
- Only the first label position may be empty. Prompt-only `{|e2}` is equivalent to JSON `{"prompt":"e2"}`: the existing button fallback uses `e2` as both visible text and queued prompt without requiring a separately authored label.
61
+ The first label position may be empty. Prompt-only `{|e2}` is equivalent to JSON `{"prompt":"e2"}`: the existing button fallback uses `e2` as both visible text and queued prompt without requiring a separately authored label.
62
62
 
63
63
  A three-atom cell adds the selected style and retains the same optional-label form:
64
64
 
@@ -67,7 +67,18 @@ A three-atom cell adds the selected style and retains the same optional-label fo
67
67
  {|e2|success}
68
68
  ```
69
69
 
70
- The prompt and style atoms remain required. The style atom is accepted only as `primary`, `success`, or `danger`.
70
+ In a three-atom cell, the prompt and style remain required; style accepts only `primary`, `success`, or `danger`.
71
+
72
+ A four-atom cell adds disabled state:
73
+
74
+ ```text
75
+ {Next|||1}
76
+ {|||1}
77
+ {Next|counter::next|success|1}
78
+ {Next|counter::next||0}
79
+ ```
80
+
81
+ The fourth atom accepts `1` or `true` (disabled), and `0` or `false` (enabled), with exact lowercase spelling; omitting the fourth position keeps the button enabled. The third atom may be empty in this form to retain the default selected style. Disabled cells may omit the prompt, label, and selected style: `{Next|||1}` is a label-only control and `{|||1}` is a blank disabled cell. Enabled CML cells still require a prompt. Telegram requires a `text` field, so its renderer sends a non-breaking space (`U+00A0`) for a blank disabled cell; the notation itself does not invent a label or action. Client rendering of blank cells requires live verification. JSON uses a boolean `disabled`; other value types are invalid. Disabled cells remain visible in their original row but register no action and carry no callback data.
71
82
 
72
83
  ## Adaptive Grammar
73
84
 
@@ -83,6 +94,8 @@ boundary := ws [","] ws
83
94
  positional-cell := "{" atom "}"
84
95
  | "{" [atom] "|" atom "}"
85
96
  | "{" [atom] "|" atom "|" atom "}"
97
+ | "{" [atom] "|" atom "|" [atom] "|" ("0" | "false") "}"
98
+ | "{" [atom] "|" [atom] "|" [atom] "|" ("1" | "true") "}"
86
99
  atom := atom-unit+
87
100
  atom-unit := ordinary | "\|" | "\}" | "\\"
88
101
  ws := *(SP | HTAB | CR | LF)
@@ -117,7 +130,7 @@ A conforming parser:
117
130
  3. Tries one complete strict JSON object, then bounded trailing-comma recovery, at each cell boundary before positional interpretation.
118
131
  4. Keeps JSON-shaped named objects on the JSON path when validation fails instead of exposing their source as positional text.
119
132
  5. Accepts at most one comma between elements or immediately before a closing row or matrix delimiter, while rejecting leading, repeated, or property-level omitted commas.
120
- 6. Rejects empty matrices, rows, one-atom cells, prompts, styles, and nesting deeper than one row; only the first label position may be empty in a two- or three-atom button cell.
133
+ 6. Rejects empty matrices, rows, one-atom cells, enabled-cell prompts, and nesting deeper than one row. The label may be empty in multi-atom cells; the style may additionally be empty in four-atom cells. Disabled four-atom cells may omit all first three atoms. Rejects unknown styles, invalid disabled values, and more than four button atoms.
121
134
  7. Decodes only `\|`, `\}`, and `\\` in positional cells.
122
135
  8. Extracts the first complete valid payload from a tolerant comment envelope and ignores unrelated text or isolated unmatched matrix brackets around it.
123
136
  9. Returns no partial rows or cells from a balanced malformed candidate.
@@ -127,17 +140,32 @@ Malformed JSON-looking input receives no generic recovery. It is accepted only i
127
140
 
128
141
  ## Telegram Profiles
129
142
 
130
- For `telegram_button` comments:
143
+ For `telegram_button` hidden comments and fenced blocks:
131
144
 
132
145
  - JSON `value` keeps its existing label/prompt fallback semantics.
133
146
  - Positional `{value}` is equivalent to JSON `{"value":"value"}`; a lone JSON `label` or `prompt` has the same both-fields shorthand semantics.
134
147
  - Positional `{|prompt}` is equivalent to JSON `{"prompt":"prompt"}` and therefore uses the prompt as both visible text and queued prompt.
135
148
  - Positional `{label|prompt}` is equivalent to JSON `{"label":"label","prompt":"prompt"}`.
136
149
  - Positional `{label|prompt|selected_style}` and `{|prompt|selected_style}` are equivalent to their corresponding JSON objects.
150
+ - Positional `{label|prompt|selected_style|1}` is equivalent to JSON `{"label":"label","prompt":"prompt","selected_style":"selected_style","disabled":true}` with a valid selected style; `{|prompt||1}` is equivalent to `{"prompt":"prompt","disabled":true}`. Fourth-position `0` or `false` matches `disabled: false`; `true` is equivalent to `1`.
151
+ - `{label|||1}` matches JSON `{"label":"label","disabled":true}`; `{|||1}` matches `{"disabled":true}`. Disabled cells require no prompt and do not retain action or selected-style semantics.
152
+ - Disabled buttons serialize as `{ text, disabled: {} }`, without `callback_data`; they neither enqueue prompts nor invoke bound app methods. Enabled controls keep existing selection and callback behavior.
137
153
  - Top-level cells become full-width rows.
138
154
  - Nested rows become horizontal keyboard rows.
139
155
  - Invalid payloads are stripped with their recognized action comment and register no callbacks.
140
156
 
157
+ The wrapper selects placement without changing cell semantics. A hidden `telegram_button` HTML comment builds the footer keyboard. A standalone column-zero fenced block opened by exactly three backticks plus `telegram_button` renders rows between paragraphs in Native Rich Markdown. A singleton JSON/CML object needs no array in either wrapper. Fenced content must be one complete payload without trailing envelope text. Larger outer fences and ordinary code blocks remain literal examples; unclosed action fences are withheld. Native Rich rows support at most eight buttons and must fit one message chunk; these are renderer constraints, not grammar limits. HTML compatibility places fenced controls in the footer. See [Outbound](./outbound.md) for delivery and callback behavior.
158
+
159
+ ````markdown
160
+ Description.
161
+
162
+ ```telegram_button
163
+ [{Details|Explain this section.}[{Choose|Choose this option.}{Unavailable|||true}]]
164
+ ```
165
+
166
+ Next paragraph.
167
+ ````
168
+
141
169
  For `telegram_voice`, one positional cell maps `{text}`, `{text|lang}`, or `{text|lang|rate}` to one voice artifact. JSON object cells remain available for named fields, escaping, and multiline text. Voice comments do not accept matrix or row composition.
142
170
 
143
171
  Example:
@@ -157,7 +185,7 @@ The grammar imposes no visual row-width maximum. Renderer and interaction policy
157
185
  Accepted classes include:
158
186
 
159
187
  - Strict JSON objects and matrices.
160
- - Positional singleton, two-atom, prompt-only `{|prompt}`, and styled cells.
188
+ - Positional singleton, two-atom, prompt-only `{|prompt}`, styled, and four-atom disabled-state cells.
161
189
  - Matrices and rows with commas, without commas, or a mixture of boundaries.
162
190
  - Named JSON and positional cells mixed in one matrix or row.
163
191
  - Literal commas inside positional atoms and strict JSON strings.
@@ -166,12 +194,12 @@ Accepted classes include:
166
194
 
167
195
  Rejected classes include:
168
196
 
169
- - Empty payloads, matrices, rows, one-atom cells, prompts, or style atoms; an empty label is valid only as the first position of a two- or three-atom button cell.
197
+ - Empty payloads, matrices, rows, one-atom cells, enabled-cell prompts, or three-atom styles; disabled four-atom cells may omit the first three atoms but not the disabled flag.
170
198
  - Leading or repeated element commas.
171
199
  - Missing commas between properties inside a JSON object.
172
200
  - Deeper row nesting.
173
201
  - Missing, crossed, or mismatched delimiters.
174
- - A third positional separator, unknown style, unknown escape, or trailing backslash.
202
+ - A fourth positional separator, unknown style, invalid disabled flag, unknown escape, or trailing backslash.
175
203
  - Internal control characters.
176
204
  - Valid JSON that fails the existing JSON action schema.
177
205
 
@@ -179,4 +207,4 @@ Every rejected case proves zero callback registration.
179
207
 
180
208
  ## Versioning
181
209
 
182
- This document defines CML v3. V3 extends the v2 positional grammar with strict JSON object cells, mixed representation, optional element-boundary commas, and prompt-only button cells that preserve the established JSON fallback semantics. It does not make JSON object internals permissive and does not add deeper structures. Future versions must preserve strict-JSON-first routing, bounded depth, atomic rejection, and an explicit discriminator for any new meaning at a security or ownership boundary.
210
+ This document defines CML v4. V4 adds a fourth button atom for disabled state, permits an empty third atom in that form, and makes labels and prompts optional for disabled cells. Existing one-, two-, and three-atom button cells, JSON/CML mixing, optional element-boundary commas, and prompt-only fallback semantics remain unchanged. Voice cells retain their three-atom maximum. JSON object internals and nesting depth remain unchanged. Future versions must preserve strict-JSON-first routing, bounded depth, atomic rejection, and an explicit discriminator for any new meaning at a security or ownership boundary.
@@ -49,7 +49,7 @@ An app name is a unique lowercase ASCII identifier accepted by the runtime's pat
49
49
 
50
50
  ## Inference-Bypass Syntax
51
51
 
52
- Compact Matrix Literal and full JSON buttons keep their existing `label + prompt` contract. A bound action is encoded entirely in the prompt string:
52
+ Compact Matrix Literal and full JSON buttons keep their existing `label + prompt` contract. App output may use hidden `telegram_button` comments for footer controls or standalone triple-backtick `telegram_button` blocks between paragraphs; both singleton cells and mixed matrices retain the same generation/revision-bound routing. In-body controls acknowledge clicks without recoloring the message; HTML compatibility moves them to the footer. A bound action is encoded entirely in the prompt string:
53
53
 
54
54
  ```ebnf
55
55
  bound-action = app "::" method [ "(" json-value ")" ]
@@ -83,7 +83,7 @@ Equivalent JSON:
83
83
  ]
84
84
  ```
85
85
 
86
- `app` is not a button property. Both representations normalize to the same prompt string, and routing happens afterward.
86
+ `app` is not a button property. Both representations normalize to the same prompt string, and routing happens afterward. The shared [button grammar](./compact-matrix-literal.md) also supports disabled controls: `{Call|||1}` or JSON `{"label":"Call","disabled":true}`. A disabled cell needs no method prompt or selected style; `{|||1}` is an intentional blank disabled cell. These remain visible but register no callback or bound action. App methods must still validate current state when invoked through an enabled control or another supported entrypoint; disabled presentation is not an authorization boundary.
87
87
 
88
88
  The double colon is the inference-bypass operator: it routes a generated prompt control to a registered deterministic owner before Pi queue admission. Native extension callbacks retain their existing single-colon grammar:
89
89
 
@@ -434,7 +434,7 @@ Follower Restore requires exact registration generation and expected old target
434
434
 
435
435
  - Two leaders calling `getUpdates` is the main safety failure.
436
436
  - Lock heartbeat/takeover must be atomic enough to prevent this under normal local concurrency.
437
- - If Telegram returns API conflict behavior, record diagnostics and force one leader to step down.
437
+ - Persistent competing `getUpdates` clients trigger a full transport stand-down even when the local lock still appears owned; the stopped runtime preserves accepted local work and releases only its exact ownership. See [Runtime Ownership](./architecture.md#runtime-ownership) for the threshold, diagnostic, and reconnect contract.
438
438
 
439
439
  ## Security Boundaries
440
440
 
@@ -155,12 +155,14 @@ I can continue.
155
155
 
156
156
  Rules:
157
157
 
158
- - The payload may be a JSON object, adaptive JSON/CML matrix, or positional [Compact Matrix Literal](./compact-matrix-literal.md). Named JSON objects and positional cells may coexist in one matrix or row. Commas are optional between completed elements, and one trailing comma before a closing delimiter is tolerated; JSON object validation likewise tolerates trailing commas but does not invent missing values, property names, or internal separators. CML uses `{value}`, `{label|prompt}`, `{|prompt}`, or the corresponding three-atom form with `selected_style`; the optional third atom requires a non-empty prompt and accepts only `primary`, `success`, or `danger`. It trims every atom, preserves non-structural printable text, and decodes only `\|`, `\}`, and `\\`.
158
+ - The payload may be a JSON object, adaptive JSON/CML matrix, or positional [Compact Matrix Literal](./compact-matrix-literal.md). Named JSON objects and positional cells may coexist in one matrix or row. Commas are optional between completed elements, and one trailing comma before a closing delimiter is tolerated; JSON object validation likewise tolerates trailing commas but does not invent missing values, property names, or internal separators. CML uses `{value}`, `{label|prompt}`, `{|prompt}`, or the corresponding three-atom form with `selected_style`; the optional third atom requires a non-empty prompt and accepts only `primary`, `success`, or `danger`. A fourth atom accepts `1` or `true` (disabled), and `0` or `false` (enabled), with exact lowercase spelling, permitting an empty style atom in this form: `{|Next||1}`. An omitted fourth position stays enabled. JSON uses boolean `disabled`; legacy attributes accept `disabled="true"` or `disabled="false"`. Invalid disabled values reject the candidate matrix atomically. Disabled cells require no prompt or selected style: `{Next|||1}` is label-only and `{|||1}` is blank, equivalent to JSON `{"label":"Next","disabled":true}` and `{"disabled":true}`. They retain their row and label, serialize as `{ text, disabled: {} }` (non-breaking-space text for a blank cell), and register no callback, prompt, or bound app action. It trims every atom, preserves non-structural printable text, and decodes only `\|`, `\}`, and `\\`.
159
159
  - Use `label` plus `prompt`, or the compact `value` key when both strings are identical. If only `label`, only `prompt`, one-field `{value}`, or prompt-only `{|prompt}` is present, that string supplies both visible label and queued prompt. An explicit counterpart takes precedence over `value`. Use JSON with `\n` escapes for multiline prompts.
160
160
  - The opening marker must start at column zero on a top-level line outside fenced code, quotes, lists, and indented examples; otherwise it does not activate a button action and is still removed from the Telegram surface.
161
- - Prefer one matrix comment for multiple buttons. Each top-level JSON object or CML cell becomes one full-width inline-keyboard row in source order; a nested row groups one or more buttons horizontally. The parser imposes no artificial per-row width cap; empty rows, malformed cells, unknown/trailing CML escapes, a third unescaped CML separator, empty prompt/style atoms, empty one-atom cells, unknown selected styles, and deeper nesting are rejected atomically. Only the first label position may be empty in a two- or three-atom button cell. Generated surfaces default to five columns and expand to six through eight only for short position-bearing labels. Repeated singular comments remain valid.
161
+ - Prefer one matrix comment for multiple buttons. Each top-level JSON object or CML cell becomes one full-width inline-keyboard row in source order; a nested row groups one or more buttons horizontally. The parser imposes no artificial per-row width cap; empty rows, malformed cells, unknown/trailing CML escapes, a fourth unescaped CML separator, empty enabled-cell prompts or three-atom styles, invalid disabled flags, empty one-atom cells, unknown selected styles, and deeper nesting are rejected atomically. Multi-atom cells may omit the label; four-atom cells may additionally omit the selected style, and disabled cells may omit the prompt. Generated surfaces default to five columns and expand to six through eight only for short position-bearing labels. Repeated singular comments remain valid.
162
162
  - Button actions are stored in memory with short `callback_data`; Telegram never sees the full prompt in the button payload.
163
- - After Telegram accepts a generated button callback as a queued prompt, the bridge changes that exact button to its configured selection style without changing agent-authored text or emoji. Set `selected_style` to `primary` (blue), `success` (green), or `danger` (red); omitted or invalid values fall back to `primary`. The style never suppresses queue admission. Other choices stay visually unchanged and remain available; the callback acknowledgement remains the fallback on clients that do not render button styles.
163
+ - Standalone column-zero fences opened by exactly three backticks and `telegram_button` use the same singleton/matrix JSON/CML grammar. Complete valid blocks become native `<tg-button-row>` elements in `InputRichMessage.markdown`, at their original positions. Each row supports at most eight buttons and must fit a Rich Message chunk; validation precedes callback registration for the entire block. Labels are escaped, prompts never enter the native markup, and disabled cells have no callback. Missing closures, trailing payload garbage, and invalid blocks produce no controls. Other language names and enclosing code examples stay literal. Draft previews withhold complete and unfinished action fences without registering actions. HTML compatibility projects fenced rows into the bottom keyboard before comment-authored footer rows; source ordering within each group is retained.
164
+ - In-body controls share prompt/app dispatch, TTL, generation/revision checks, and sent-message target ownership with footer controls. Their acknowledgement is the selection feedback; `selected_style` does not recolor the Rich body. No callback-triggered body rewrite is introduced, preventing a stale click from overwriting newer app output. The operator confirmed the post-reload current-client smoke: singleton CML and mixed JSON/CML in-body rows, their ordinary prompt callbacks, a labeled disabled control, and the separate footer callback work as intended. Client type was not recorded. The operator also confirmed that HTML mode projects the in-body groups into the bottom keyboard as intended. Second-client coverage, follower routing, blank cells, and app-method dispatch/revision rejection remain live-gated. Bot API evidence: `InputRichBlockButtons` / Rich Markdown `tg-button-row` and `RichMessageButton` use ordinary `callback_data` and support disabled controls.
165
+ - After Telegram accepts a generated footer button callback as a queued prompt, the bridge changes that exact button to its configured selection style without changing agent-authored text or emoji. Set `selected_style` to `primary` (blue), `success` (green), or `danger` (red); omitted or invalid values fall back to `primary`. The style never suppresses queue admission. Other choices stay visually unchanged and remain available; the callback acknowledgement remains the fallback on clients that do not render button styles.
164
166
  - When generated button markup is the entire assistant reply, the bridge supplies the standard `☑️ **Choose an option:**` heading as visible message text so Telegram has a message to which it can attach the inline keyboard.
165
167
 
166
168
  Do not emit inline comments after visible text, standalone button actions, or tool calls for ordinary Telegram-turn buttons. The agent writes Markdown plus hidden comments; the bridge strips comments and attaches Telegram `reply_markup` after `agent_end`. For local/TUI-originated direct sends, put the same Markdown and `telegram_button` comments in `telegram_message(text)`.
@@ -176,7 +178,7 @@ The extension injects prompt guidance by context:
176
178
  - For Telegram-originated turns, the compact note routes the agent to `telegram-bridge`, which owns voice/button/direct-delivery/Threaded Mode/formatting/debug guidance.
177
179
  - For Telegram-originated turns, write the full technical answer as normal Markdown.
178
180
  - Add `telegram_voice` with positional CML by default or JSON when multiline content, named fields, or escaping requires it. A companion summary is optional, no specific summary format is required.
179
- - Add `telegram_button` with a JSON object, JSON matrix, or positional CML. Prefer one matrix for multiple controls. Use `label` plus `prompt`, or `value` when they are identical; `selected_style` is optional. A button-only reply may omit parent text because the bridge supplies `☑️ **Choose an option:**` automatically.
181
+ - Add `telegram_button` with a JSON object, JSON matrix, or positional CML. Use a hidden comment for footer placement or a standalone triple-backtick `telegram_button` block for placement between paragraphs. Prefer one matrix for multiple controls. Use `label` plus `prompt`, or `value` when they are identical; `selected_style` and boolean `disabled` are optional. Keep at least one useful enabled action on an interactive surface. A button-only reply may omit parent text because the bridge supplies `☑️ **Choose an option:**` automatically.
180
182
  - For ordinary Telegram-turn replies, do not call transport tools for voice or buttons; the bridge owns delivery, while registered voice synthesis providers own TTS and OGG/Opus conversion. For explicit local/TUI direct sends, `telegram_message` may include top-level `telegram_button` comments in its Markdown text because those buttons are attached to that text message.
181
183
  - Prefer meaningful visible parent text when it adds context; for a button-only answer, rely on the bridge's automatic `☑️ **Choose an option:**` fallback rather than manufacturing duplicate text.
182
184
 
@@ -68,7 +68,7 @@ Every assistant-authored HTML comment is transport-private on Telegram: previews
68
68
  - `telegram_message(text, chat_id?, thread_id?)` sends a direct Telegram Markdown message when this Pi instance owns `/telegram-connect` or is registered with the multi-instance bus. During an active Telegram turn, omitted targeting and an explicit target equal to that turn are rejected so the ordinary final-reply path remains the sole current-target response; an explicit different chat/thread target remains allowed for requested cross-target delivery. Outside active turns, paired/default local/TUI delivery remains unchanged. Top-level `telegram_button` comments inside `text` are parsed with the same planner used for normal replies and attached to that message; buttons are never standalone Telegram messages.
69
69
  - The bundled `telegram-bridge` Skill owns action syntax, target routing, Threaded Mode, formatting, Generative App operation, and profile-specific debugging guidance. The regular prompt routes applicable turns to that Skill. `telegram_attach`, `telegram_bind`, and `telegram_message` remain registered but are model-active only while this instance owns direct transport or holds a live follower registration; disconnect/loss suppresses their schemas and prompt metadata, and recovery restores only the operator's previously active pi-telegram subset.
70
70
  - `telegram_voice` hidden comments request Telegram-native voice delivery through `{text}`, `{text|lang}`, `{text|lang|rate}`, or a JSON object. JSON is the fallback for multiline content, named fields, or escaping; equivalent `text` or `value` supplies the spoken payload, with explicit `text` taking precedence.
71
- - `telegram_button` hidden comments create inline buttons whose taps enqueue prompts. One marker accepts a JSON object, adaptive JSON/CML matrix, or positional [Compact Matrix Literal](./compact-matrix-literal.md). Named JSON objects and positional cells may coexist in one matrix or row; separators are optional and one trailing comma is tolerated at matrix, row, and JSON-object boundaries. Top-level cells become full-width rows, while nested rows group one or more buttons horizontally without an artificial parser-width cap. CML uses `{value}`, `{label|prompt}`, prompt-only `{|prompt}`, or the corresponding three-atom form with `selected_style`; an omitted label uses the existing prompt-as-label fallback, and the optional third atom requires a non-empty prompt and accepts only `primary`, `success`, or `danger`. It trims atom boundaries and supports only the minimal escapes `\|`, `\}`, and `\\`. Prefer one matrix comment for multiple buttons. Use JSON `label` plus `prompt`, or `value` when both strings are identical. Action markers are colon-free; colon-prefixed payloads are rejected. Use top-level column-zero comments outside code, quotes, lists, and indented examples; do not emit standalone button actions.
71
+ - `telegram_button` hidden comments create footer buttons; standalone column-zero triple-backtick `telegram_button` blocks create button rows between paragraphs in Native Rich Markdown. Both accept the same singleton or mixed JSON/CML matrix and share prompt/app routing. Native rows allow at most eight buttons and must fit one Rich Message chunk; invalid or incomplete blocks register nothing. Drafts hide action fences. HTML compatibility projects fenced controls into the footer. In-body clicks acknowledge without recoloring the Rich body; selected-style highlighting remains footer-only. One marker accepts a JSON object, adaptive JSON/CML matrix, or positional [Compact Matrix Literal](./compact-matrix-literal.md). Named JSON objects and positional cells may coexist in one matrix or row; separators are optional and one trailing comma is tolerated at matrix, row, and JSON-object boundaries. Top-level cells become full-width rows, while nested rows group one or more buttons horizontally without an artificial parser-width cap. CML uses `{value}`, `{label|prompt}`, prompt-only `{|prompt}`, or the corresponding three-atom form with `selected_style`; an omitted label uses the existing prompt-as-label fallback, and the optional third atom requires a non-empty prompt and accepts only `primary`, `success`, or `danger`. A fourth atom accepts `1` or `true` (disabled), and `0` or `false` (enabled), with exact lowercase spelling; an omitted fourth position stays enabled, and the third atom may be empty in this form (`{|Next||1}`). JSON uses boolean `disabled`. Disabled cells need no prompt or selected style: `{Next|||1}` is label-only and `{|||1}` is blank (JSON `{"label":"Next","disabled":true}` and `{"disabled":true}`). The Telegram renderer supplies a non-breaking space only when the label is empty. Disabled cells stay visible but carry `disabled: {}` instead of callback data and register no prompt or bound action; invalid disabled values reject the candidate matrix. It trims atom boundaries and supports only the minimal escapes `\|`, `\}`, and `\\`. Prefer one matrix comment for multiple buttons. Use JSON `label` plus `prompt`, or `value` when both strings are identical. Action markers are colon-free; colon-prefixed payloads are rejected. Use top-level column-zero action wrappers, outside quotes, lists, or enclosing code examples. Ordinary code fences and larger outer fences preserve literal examples; bare JSON/CML in prose never activates.
72
72
 
73
73
  Prompt guidance is context-aware: local/TUI prompts see only explicit direct-delivery guidance, while Telegram-originated turns receive the full action-comment syntax and phone-width output contract.
74
74
 
@@ -245,7 +245,10 @@ export default function (pi: Pi.ExtensionAPI) {
245
245
  Config.createTelegramProactivePushChatIdGetter(proactivePushTargetGetter);
246
246
  const buttonActionStore = Outbound.createTelegramButtonActionStore();
247
247
  const planGenerativeAppOutput =
248
- Outbound.createTelegramOutboundReplyPlanner(buttonActionStore);
248
+ Outbound.createTelegramOutboundReplyPlanner(
249
+ buttonActionStore,
250
+ configControls.getAssistantRenderingMode,
251
+ );
249
252
  const pendingModelSwitchStore =
250
253
  Model.createPendingModelSwitchStore<
251
254
  Model.ScopedTelegramModel<ActivePiModel>
@@ -1031,6 +1034,12 @@ export default function (pi: Pi.ExtensionAPI) {
1031
1034
  Pi.ExtensionContext
1032
1035
  >({
1033
1036
  state: pollingControllerState,
1037
+ canStart(ctx) {
1038
+ return telegramSessionContextStore.isCurrent(ctx) && lockRuntime.owns(ctx);
1039
+ },
1040
+ onPersistentConflict(ctx, count): Promise<void> {
1041
+ return lockedPollingRuntime.onPersistentConflict(ctx, count);
1042
+ },
1034
1043
  getConfig: configStore.get,
1035
1044
  hasBotToken: configStore.hasBotToken,
1036
1045
  deleteWebhook,
@@ -1202,8 +1211,10 @@ export default function (pi: Pi.ExtensionAPI) {
1202
1211
  const threadAwarePollingPorts = telegramThreadCapabilityRuntime.pollingPorts;
1203
1212
  const lockedPollingRuntime = Locks.createTelegramLockedPollingRuntime({
1204
1213
  lock: lockRuntime,
1214
+ transportMonitor: telegramThreadCapabilityMonitor,
1205
1215
  hasBotToken: configStore.hasBotToken,
1206
1216
  canStartPolling: Pi.canStartPollingInExtensionContext,
1217
+ isContextCurrent: telegramSessionContextStore.isCurrent,
1207
1218
  formatStartBlockedMessage: Pi.formatPollingStartBlockedByRunMode,
1208
1219
  startPolling: threadAwarePollingPorts.startPolling,
1209
1220
  stopPolling: threadAwarePollingPorts.stopPolling,
@@ -518,7 +518,10 @@ export function registerTelegramCommandsAndTools({
518
518
  GenerativeApps.registerTelegramBindTool(pi, {
519
519
  agentDir,
520
520
  getActiveTurn: activeTurnRuntime.get,
521
- planOutput: OutboundHandlers.createTelegramOutboundReplyPlanner(buttonActionStore),
521
+ planOutput: OutboundHandlers.createTelegramOutboundReplyPlanner(
522
+ buttonActionStore,
523
+ Config.createTelegramConfigControls(configStore).getAssistantRenderingMode,
524
+ ),
522
525
  sendMarkdownReply,
523
526
  recordRuntimeEvent,
524
527
  });
@@ -538,7 +541,10 @@ export function registerTelegramCommandsAndTools({
538
541
  routeAgentMessage,
539
542
  canSendDirect,
540
543
  planMessage:
541
- OutboundHandlers.createTelegramOutboundReplyPlanner(buttonActionStore),
544
+ OutboundHandlers.createTelegramOutboundReplyPlanner(
545
+ buttonActionStore,
546
+ Config.createTelegramConfigControls(configStore).getAssistantRenderingMode,
547
+ ),
542
548
  sendMarkdownMessage: (chatId, markdown, options) =>
543
549
  sendMarkdownReply(chatId, undefined, markdown, options),
544
550
  recordRuntimeEvent,
@@ -854,7 +860,10 @@ export function registerTelegramLifecycleRuntimeHooks({
854
860
  });
855
861
  };
856
862
  const outboundReplyPlanner =
857
- OutboundHandlers.createTelegramOutboundReplyPlanner(buttonActionStore);
863
+ OutboundHandlers.createTelegramOutboundReplyPlanner(
864
+ buttonActionStore,
865
+ getAssistantRenderingMode,
866
+ );
858
867
  const voiceReplySenderDeps = {
859
868
  execCommand: CommandTemplates.execCommandTemplate,
860
869
  sendMultipart: callMultipart,
@@ -9,11 +9,13 @@ export type TelegramInlineKeyboardButtonStyle =
9
9
  | "success"
10
10
  | "primary";
11
11
 
12
- export interface TelegramInlineKeyboardButton {
12
+ export type TelegramInlineKeyboardButton = {
13
13
  text: string;
14
- callback_data: string;
15
14
  style?: TelegramInlineKeyboardButtonStyle;
16
- }
15
+ } & (
16
+ | { callback_data: string; disabled?: never }
17
+ | { disabled: Record<string, never>; callback_data?: never }
18
+ );
17
19
 
18
20
  export interface TelegramInlineKeyboardMarkup {
19
21
  inline_keyboard: TelegramInlineKeyboardButton[][];