@llblab/pi-telegram 0.42.3 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/BACKLOG.md CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  _This file owns unresolved project work only. Completed behavior belongs in `CHANGELOG.md`; durable contracts belong in `AGENTS.md` and `/docs`._
4
4
 
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
+ - [ ] 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.
5
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.
6
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.
7
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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  > Each release keeps at most 8 outcome records of at most 512 characters.
4
4
 
5
+ ## 0.43.0: Native Button Blocks
6
+
7
+ - `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.
8
+ - `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.
9
+ - `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.
10
+
11
+ ## 0.42.4: Thread Recovery Hotfix
12
+
13
+ - `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.
14
+ - `Target Safety`: Rechecks cleanup ownership before close/delete and local retirement across restore, disconnect, and provisioning paths; a rebound target is not deleted, invalidated, or reserved by obsolete cleanup. Follower restore rechecks registration generation and expected target after IPC, store-load, and persistence waits.
15
+ - `Stale Delivery`: Direct replies, menus, activity, edits, and multipart sends capture exact stale-target authority; guarded invalidation rechecks generation, profile, binding, and snapshot revision at the synchronous durable commit without replaying failed sends or redirecting accepted work.
16
+ - `State Continuity`: Snapshot reads cannot overwrite bindings or cleanup intents admitted while disk I/O was pending; equivalent persisted records retain cleanup authority regardless of property order or omitted optional fields.
17
+
5
18
  ## 0.42.3: Agent Diagnostics Hotfix
6
19
 
7
20
  - `Agent Diagnostics`: Identifies `/telegram-status` as a Pi TUI command and routes agents without command access directly to the redacted diagnostic files instead of attempting a shell executable; runtime behavior and STT fallback remain unchanged.
package/README.md CHANGED
@@ -131,7 +131,7 @@ Enable the optional capabilities the bridge needs in the [@BotFather](https://t.
131
131
  | 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
132
  | Voice input | Route audio through configured command-template handlers, programmatic handlers, or STT providers. | Voice notes become usable prompt context. |
133
133
  | 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. |
134
+ | 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
135
  | 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
136
  | 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
137
  | 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 +222,7 @@ Voice notes, audio, images, PDFs, and other media can pass through configured in
222
222
 
223
223
  ### Buttons And Callbacks
224
224
 
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.
225
+ 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
226
 
227
227
  ### Threaded Mode And Multi-Instance Bus
228
228
 
package/docs/README.md CHANGED
@@ -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.
@@ -352,12 +352,14 @@ Final delivery attaches reply metadata only where requested. Reply parameters ap
352
352
 
353
353
  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
354
 
355
- Assistant-authored final-message actions use hidden top-level comments:
355
+ Assistant-authored final-message actions use hidden top-level comments, with an additional fenced wrapper for in-body buttons:
356
356
 
357
357
  - `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
358
  - `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
359
 
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.
360
+ 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.
361
+
362
+ 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
363
 
362
364
  Unknown callback data outside owned prefixes is forwarded as `[callback] <data>` only after built-in and extension handlers decline it.
363
365
 
@@ -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
 
@@ -272,7 +272,7 @@ Non-goal: group detection is not the control-plane model for this extension. Thr
272
272
 
273
273
  Remaining live-verification points:
274
274
 
275
- - Whether callback query messages always carry `message_thread_id` in private bot threads, or whether generated button callbacks must rely on stored message id -> target ownership.
275
+ - Callback query messages can be `InaccessibleMessage` without `message_thread_id`; reroute controls use stored source/chooser identity, and ordinary generated buttons retain their message-ownership routing. Client-visible Restore and cleanup still require live smoke evidence.
276
276
  - Whether message-reaction updates carry thread identity in the current Bot API shape. The reference exposes chat id and message id for reactions, so routing may need stored message ownership.
277
277
  - Live client evidence now covers the probe-confirmed single-artifact multipart Rich final through both direct leader and registered follower transport: an assigned follower Telegram turn produced one reply-anchored PNG plus final text without a duplicate upload or notice. Deterministic bus tests additionally cover target-scoped multipart authorization, envelope preservation, and replacement-generation fencing.
278
278
 
@@ -412,11 +412,23 @@ All files containing routing, chat ids, thread ids, or process details use priva
412
412
  - Destructive follower thread teardown belongs to confirmed `/telegram-disconnect`, graceful Pi quit, or confirmed reconciliation actions, not generic heartbeat pruning. Manual disconnect retains its destructive confirmation and clears restart ownership; quit deletes the tab without prompting when Thread cleanup is enabled (default) but preserves the owner slot independently so a same-directory restart can reclaim leadership. Confirmed leader/follower teardown first persists an exact target/runtime-generation cleanup intent. The active leader attempts deletion under its current epoch; interruption preserves the intent so that leader or a successor can replay it under current authority, and confirmed deletion removes the binding plus intent in the same persisted state transition. If the graceful request is missed, stale heartbeat plus OS-confirmed absence of the exact registered PID may authorize the same cleanup while enabled; this action serializes ahead of replacement registration. Disabled cleanup, silence, heartbeat expiry alone, IPC/auth failure, and live or unknown process liveness remain non-destructive. Incomplete cleanup preserves durable intent for retry. A promoted leader uses its current owned leader epoch even when the inherited record still carries a historical `manual-follower` owner label.
413
413
  - Explicit stale/deleted/offline observations invalidate reuse. Process absence affects reuse only through the enabled, exact-PID confirmed-dead cleanup path.
414
414
 
415
- ### Thread is deleted
415
+ ### Stale thread delivery
416
416
 
417
- - Target mapping becomes stale.
418
- - On next outbound failure or reconnect, leader records a diagnostic.
419
- - Depending on policy, recreate a thread or mark the instance as needing operator action.
417
+ Local regression evidence covers continuity and cleanup authority; operator-coordinated live Restore verification remains tracked in [BACKLOG.md](../BACKLOG.md).
418
+
419
+ - Direct replies, menus, activity, target-aware edits, and multipart transport capture the request target and local authority before sending. Exact typed HTTP 400 stale-thread evidence stages invalidation of only the matching unchanged binding. The thread store rechecks leader/session/profile authority, binding identity, snapshot revisions, and destination path at the synchronous owner-fenced rename; no staged invalidation enters the live projection before durable commit, and a rejected commit preserves newer state.
420
+ - Shared recovery marks topic, target-binding, and transport freshness suspect and schedules a diagnostic snapshot. Accepted local work and its active-turn target remain unchanged; a failed send is not replayed or redirected, and recovery does not create a replacement thread or probe on every send. Errors without a proven request target do not authorize invalidation.
421
+ - Reconnect and explicit Restore remain separate authority-bearing operations. A stale API response proves target failure, not who deleted or closed the thread.
422
+
423
+ ### Restore controls and cleanup
424
+
425
+ Operator-confirmed client flow: send ordinary text from the **All** tab; Telegram creates a new thread containing that text. Choose **Replace/restore thread…** and the existing Pi instance. Successful leader Restore binds and renames the new thread, dispatches the original message to the same Pi, and removes the old thread. The resulting prompt's thread-name label reflects the restored destination, not proof that the user typed in the old thread. A threadless `/start` is not equivalent to this ordinary-text flow.
426
+
427
+ The bounded pending reroute owns its original source target and the returned chooser message ID independently from remaining messages. Authenticated callbacks must match the stored chat/chooser and any supplied thread field. `InaccessibleMessage` may omit the thread field; a missing callback message, unknown chooser, conflicting identity, threadless source, or already-owned Restore source fails closed rather than forwarding to the old target. Restart or expiry without that pending identity does not authorize reconstruction from callback data alone. When the original input itself has no thread ID (including an All-tab `/start`), the chooser offers routing only, not Restore; old Restore callbacks explain that a plain message must first be sent in the destination thread. Client tab selection is not inferred from recent topic creation or from the chosen Pi instance.
428
+
429
+ After dispatch, cleanup retries retain source identity but never redispatch accepted messages. Confirmed typed HTTP 400 `message to delete not found` completes message deletion idempotently; permission and transient failures remain errors. Reroute cleanup rechecks current bindings, live targets, reservations, and pending provisions before close, before delete, and on retry. Other destructive cleanup origins use the shared synchronous target-protection policy: explicit retirement permits only its unchanged departing binding, persisted shutdown intent permits only its original pre-intent binding, and reservation/provision cleanup permits only the corresponding unchanged claim. Protection checks also guard post-API local invalidation, reservation, and disconnect completion. A newly protected target cancels remaining cleanup. Already-issued remote operations cannot be undone by a later local ownership change; checks prevent subsequent effects, not retroactive cancellation.
430
+
431
+ Follower Restore requires exact registration generation and expected old target both before and after awaited IPC acknowledgement/store loading. Completion also rechecks the restored target and generation after persistence before publishing status or acknowledging success. A mismatched, replaced, or same-target request cannot overwrite the current registration.
420
432
 
421
433
  ### Split brain
422
434
 
package/docs/outbound.md CHANGED
@@ -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
 
package/index.ts CHANGED
@@ -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>
@@ -400,6 +403,15 @@ export default function (pi: Pi.ExtensionAPI) {
400
403
  TelegramApi.createDefaultTelegramBridgeApiRuntime({
401
404
  getBotToken: configStore.getBotToken,
402
405
  recordRuntimeEvent,
406
+ captureRequestErrorHandler(body) {
407
+ return Sync.captureTelegramStaleTargetRequestRecovery(body, {
408
+ ...staleTopicApiErrorRecoveryDeps,
409
+ getCurrentLeaderEpoch,
410
+ getSessionGeneration: telegramSessionContextStore.getGeneration,
411
+ getProfileName: configStore.getActiveProfileName,
412
+ onRecovered: runtimeDiagnostics.scheduleSnapshotPersist,
413
+ });
414
+ },
403
415
  });
404
416
  const telegramBusFollowerClients =
405
417
  BusFollower.createTelegramBusFollowerClientRuntime<
package/lib/bindings.ts CHANGED
@@ -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,
@@ -390,9 +390,8 @@ export interface TelegramBusFollowerTargetReplacementHandlerDeps<TContext> {
390
390
  >;
391
391
  registrationState: Pick<
392
392
  TelegramBusFollowerRegistrationState,
393
- "getTarget" | "setRegistered"
394
- > &
395
- Partial<Pick<TelegramBusFollowerRegistrationState, "getGeneration">>;
393
+ "getTarget" | "setRegistered" | "getGeneration"
394
+ >;
396
395
  instanceId: string;
397
396
  getManualFollowerProfileKey: () => string;
398
397
  manualFollowerOwnerId: string;
@@ -471,6 +470,7 @@ export interface TelegramBusForwardedUpdateReceiverRuntimeDeps<TContext> {
471
470
  target: TelegramTarget & { threadId: number };
472
471
  oldTarget?: TelegramTarget & { threadId: number };
473
472
  reason: "thread-restore";
473
+ registrationGeneration: string;
474
474
  },
475
475
  ctx: TContext,
476
476
  ) => Promise<void> | void;
@@ -569,26 +569,35 @@ export function createTelegramBusFollowerTargetReplacementHandler<TContext>(
569
569
  > {
570
570
  const getNowMs = deps.getNowMs ?? Date.now;
571
571
  return async (input, ctx) => {
572
+ const assertCurrent = (expectedTarget = input.oldTarget): void => {
573
+ const target = deps.registrationState.getTarget();
574
+ if (!input.registrationGeneration ||
575
+ deps.registrationState.getGeneration() !== input.registrationGeneration ||
576
+ !input.oldTarget || !expectedTarget || target?.chatId !== expectedTarget.chatId ||
577
+ target.threadId !== expectedTarget.threadId ||
578
+ input.target.chatId !== input.oldTarget.chatId ||
579
+ input.target.threadId === input.oldTarget.threadId) {
580
+ throw new Error("Stale Telegram follower target replacement authority.");
581
+ }
582
+ };
583
+ assertCurrent();
572
584
  await deps.topicTargetStore.load();
585
+ assertCurrent();
573
586
  const nowMs = getNowMs();
574
587
  const currentRecord = Threads.findCurrentTelegramInstanceThreadRecord({
575
588
  records: deps.topicTargetStore.list(),
576
589
  instanceId: deps.instanceId,
577
- preferredTarget: input.oldTarget ?? deps.registrationState.getTarget(),
590
+ preferredTarget: input.oldTarget,
578
591
  });
579
- if (input.oldTarget) {
580
- deps.topicTargetStore.markStaleByTarget(
581
- input.oldTarget,
582
- "deleted",
583
- "Follower thread was replaced by thread restore.",
584
- );
585
- } else if (currentRecord) {
586
- deps.topicTargetStore.markStaleByTarget(
587
- currentRecord.target,
588
- "deleted",
589
- "Follower thread was replaced by thread restore.",
590
- );
592
+ if (currentRecord && (currentRecord.target.chatId !== input.oldTarget!.chatId ||
593
+ currentRecord.target.threadId !== input.oldTarget!.threadId)) {
594
+ throw new Error("Stale Telegram follower binding replacement target.");
591
595
  }
596
+ deps.topicTargetStore.markStaleByTarget(
597
+ input.oldTarget!,
598
+ "deleted",
599
+ "Follower thread was replaced by thread restore.",
600
+ );
592
601
  const profileKey =
593
602
  currentRecord?.profileKey ?? deps.getManualFollowerProfileKey();
594
603
  deps.topicTargetStore.upsert({
@@ -612,15 +621,16 @@ export function createTelegramBusFollowerTargetReplacementHandler<TContext>(
612
621
  deps.registrationState.setRegistered(true, input.target, {
613
622
  slot: currentRecord?.slot,
614
623
  threadName: currentRecord?.threadName,
615
- generation: deps.registrationState.getGeneration?.(),
624
+ generation: input.registrationGeneration,
616
625
  });
626
+ await deps.topicTargetStore.persist();
627
+ assertCurrent(input.target);
617
628
  deps.setSyncState(
618
629
  Sync.markTelegramSyncSliceFresh(deps.getSyncState(), "target-bindings", {
619
630
  nowMs,
620
631
  action: "follower-thread-restore",
621
632
  }),
622
633
  );
623
- await deps.topicTargetStore.persist();
624
634
  deps.updateStatus(ctx);
625
635
  deps.recordRuntimeEvent?.(
626
636
  "bus",
@@ -1992,6 +2002,7 @@ export function createTelegramBusForwardedUpdateReceiverRuntime<TContext>(
1992
2002
  target: envelope.target,
1993
2003
  ...(envelope.oldTarget ? { oldTarget: envelope.oldTarget } : {}),
1994
2004
  reason: envelope.reason,
2005
+ registrationGeneration,
1995
2006
  },
1996
2007
  ctx,
1997
2008
  );
package/lib/bus-leader.ts CHANGED
@@ -135,6 +135,7 @@ export interface TelegramBusFollowerTargetProvisionerDeps {
135
135
  export interface TelegramBusFollowerDisconnectHandlerDeps {
136
136
  topicTargetStore: Pick<
137
137
  Threads.TelegramTopicTargetStore,
138
+ | "list"
138
139
  | "markStaleByTarget"
139
140
  | "persist"
140
141
  | "upsertPendingCleanup"
@@ -726,6 +727,7 @@ export function createTelegramBusFollowerTargetProvisioner(
726
727
  ],
727
728
  }),
728
729
  {
730
+ isCleanupTargetProtected: Threads.createTelegramCleanupTargetProtection(deps.topicTargetStore),
729
731
  callApi: deps.callApi,
730
732
  markStaleByTarget(target, syncStatus, lastSyncError) {
731
733
  return deps.topicTargetStore.markStaleByTarget(
@@ -805,16 +807,21 @@ function createTelegramBusFollowerCleanupHandler(
805
807
  target: { chatId: target.chatId, threadId: target.threadId },
806
808
  requestedAtMs: (deps.getNowMs ?? Date.now)(),
807
809
  };
810
+ const departingRecord = deps.topicTargetStore.list().find((record) => record.instanceId === follower.instanceId &&
811
+ record.target.chatId === target.chatId && record.target.threadId === target.threadId);
812
+ const isCleanupTargetProtected = Threads.createTelegramCleanupTargetProtection(deps.topicTargetStore, departingRecord);
808
813
  deps.topicTargetStore.upsertPendingCleanup(intent);
809
814
  await deps.topicTargetStore.persist();
815
+ const cleanupPlan = ThreadReconciler.planThreadReconciliation({
816
+ nowMs: (deps.getNowMs ?? Date.now)(),
817
+ currentLeaderEpoch: leaderEpoch,
818
+ records: [],
819
+ pendingCleanups: [intent],
820
+ });
810
821
  const cleanup = await ThreadReconciler.applyThreadReconciliationPlan(
811
- ThreadReconciler.planThreadReconciliation({
812
- nowMs: (deps.getNowMs ?? Date.now)(),
813
- currentLeaderEpoch: leaderEpoch,
814
- records: [],
815
- pendingCleanups: [intent],
816
- }),
822
+ cleanupPlan,
817
823
  {
824
+ isCleanupTargetProtected,
818
825
  callApi: deps.callApi,
819
826
  markStaleByTarget: deps.topicTargetStore.markStaleByTarget,
820
827
  removeCleanupIntentById: deps.topicTargetStore.removePendingCleanup,
@@ -823,6 +830,7 @@ function createTelegramBusFollowerCleanupHandler(
823
830
  recordRuntimeEvent: deps.recordRuntimeEvent,
824
831
  },
825
832
  );
833
+ if (cleanupPlan.actions.some((action) => isCleanupTargetProtected(action.target, action))) return;
826
834
  if (cleanup.incompleteActions?.length) {
827
835
  throw new Error(
828
836
  "Telegram follower thread deletion was not confirmed; reconnect the leader to retry cleanup.",
@@ -916,6 +924,7 @@ export function createTelegramBusLeaderTargetProvisioner<TContext>(
916
924
  });
917
925
  deps.recordThreadReconciliationPlan?.(pendingCleanupPlan);
918
926
  const cleanupPorts = {
927
+ isCleanupTargetProtected: Threads.createTelegramCleanupTargetProtection(deps.topicTargetStore),
919
928
  callApi: deps.callApi,
920
929
  markStaleByTarget: deps.topicTargetStore.markStaleByTarget,
921
930
  removeCleanupIntentById: deps.topicTargetStore.removePendingCleanup,