@llblab/pi-telegram 0.22.1 → 0.23.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/docs/locks.md CHANGED
@@ -58,13 +58,13 @@ During a user-initiated start/connect event, an extension should:
58
58
  1. Read its lock entry
59
59
  2. If `pid` is stale, replace the entry
60
60
  3. If `pid` and `cwd` match the current pi instance, refresh or keep the entry
61
- 4. If a live polling owner exists, ask interactively whether to move singleton ownership here
61
+ 4. If a live external owner exists, ask interactively whether to move singleton ownership here
62
62
 
63
63
  ## Acquisition timing
64
64
 
65
65
  Lock writes must be caused by an explicit user-initiated runtime event, such as a start/connect command or a confirmed takeover prompt.
66
66
 
67
- Extension initialization and session-start hooks may read `locks.json`, update local status, install ownership watchers, and resume local work when the existing lock already points at the current `pid`/`cwd`. After a full process restart, a session-start hook may replace a stale lock from the same `cwd` to restore explicitly requested ownership. They must not create ownership from an inactive lock, take over a live polling owner, or replace a stale lock from another directory by themselves. Such locks should stay visible as state until the user runs the start/connect command. Session replacement should suspend local runtime work and ownership watchers without releasing the lock, so the next session in the same `pid`/`cwd` can resume from explicit ownership.
67
+ Extension initialization and session-start hooks may read `locks.json`, update local status, install ownership watchers, and resume local work when the existing lock already points at the current `pid`/`cwd`. After a full process restart, a session-start hook may replace a stale lock from the same `cwd` to restore explicitly requested ownership. They must not create ownership from an inactive lock, take over a live external owner, or replace a stale lock from another directory by themselves. Such locks should stay visible as state until the user runs the start/connect command. Session replacement should suspend local runtime work and ownership watchers without releasing the lock, so the next session in the same `pid`/`cwd` can resume from explicit ownership.
68
68
 
69
69
  ## Optional fields
70
70
 
@@ -98,16 +98,16 @@ Singleton extensions with footer/status presence should expose quiet but explici
98
98
  - `on` when this pi instance owns the runtime but has no pending runtime detail to show
99
99
  - `[16:32:39]` when the runtime owns scheduled work and can show the next countdown
100
100
 
101
- Extensions may prefix those states with their own compact name, such as `wakeup off` or `telegram on`.
101
+ Extensions may prefix active states with their own compact name, such as `telegram on` or `wakeup [00:10:00]`. Quiet idle states may be hidden when status-line width is more valuable than an explicit off marker.
102
102
 
103
103
  ## Interactive takeover
104
104
 
105
105
  Start/connect commands should make singleton moves easy:
106
106
 
107
107
  1. If no live owner exists, take ownership without an extra prompt
108
- 2. If a live polling owner exists, ask whether to move singleton ownership to this pi instance
108
+ 2. If a live external owner exists, ask whether to move singleton ownership to this pi instance
109
109
  3. On confirmation, write the current `{ "pid": ..., "cwd": ... }` to this extension's key in `locks.json`
110
- 4. The previous owner must notice that `locks.json` no longer points at its own `pid`/`cwd` and stop singleton-owned work such as polling/watchers without deleting the new lock or unrelated session-local queues
110
+ 4. The previous owner must notice that `locks.json` no longer points at its own `pid`/`cwd` and stop local runtime work without deleting the new lock
111
111
 
112
112
  Takeover prompts should use the extension name as the dialog title, then the question, a blank line, and source/target lines:
113
113
 
@@ -121,7 +121,7 @@ to: /new
121
121
 
122
122
  Avoid repeating the extension name in the body. Color is encouraged: extension title/name accent, question warning, `from:`/`to:` muted.
123
123
 
124
- The previous owner may use `fs.watch`, mtime polling, or an existing status/timer tick. Long-lived watchers should compare against a snapshotted `pid`/`cwd` identity rather than a live pi context object, because session replacement such as `/new` makes captured contexts stale. The important contract is graceful singleton-runtime shutdown after ownership mismatch while session-local state that does not require polling remains owned by its original instance.
124
+ The previous owner may use `fs.watch`, mtime polling, or an existing status/timer tick. Long-lived watchers should compare against a snapshotted `pid`/`cwd` identity rather than a live pi context object, because session replacement such as `/new` makes captured contexts stale. The important contract is graceful local shutdown after ownership mismatch.
125
125
 
126
126
  ## Reset
127
127
 
@@ -129,21 +129,27 @@ Delete `~/.pi/agent/locks.json` to reset singleton runtime ownership for all par
129
129
 
130
130
  ## Atomicity
131
131
 
132
- Every ownership mutation runs inside a short cross-process transaction acquired through an atomically published guard directory. The transaction covers the complete registry read/check/write sequence, so concurrent processes cannot both win an ordinary acquisition or stale-overwrite unrelated extension/profile keys. The registry payload itself still commits through same-directory temp-file replacement.
132
+ `locks.json` is one shared registry, so preserving unrelated keys in memory is not sufficient. Every writer must serialize the complete cross-process read/check/write transaction through the same guard. Otherwise two extensions can read the same snapshot, update different keys, and publish snapshots that erase one another.
133
133
 
134
- A guard starts as a private staged directory containing one fully written private `owner.<generation>.json` with the process PID, acquisition time, and matching collision-resistant generation. Renaming that non-empty directory to the stable per-resource transaction path publishes the complete guard atomically; an existing non-empty destination prevents another contender from replacing it. The generation-specific filename acts as the filesystem identity check: a delayed recoverer can rename only the exact owner path it observed, so replacement publication makes the stale source disappear instead of letting the old contender claim new metadata. Filename/payload generation disagreement fails closed. A crashed transaction owner therefore leaves verifiable metadata that a later process recovers only when the recorded PID is no longer alive.
134
+ The canonical guard path is:
135
135
 
136
- Directory recovery first atomically renames the observed generation-specific owner file to a claimant-specific marker inside the still-occupied guard. Other contenders either observe the live claimant or, if it crashes, atomically take over that marker; the stable guard path never becomes free before one exact recoverer owns the transition. The claimant retries transient whole-guard rename failures and restores the previous exact marker on exhaustion. Process-global active-claim tracking also distinguishes a still-running reclaim from inactive same-process debris if restoration fails, so later acquisition does not require process exit. After the guard moves away, the claimant competes normally to publish a replacement. If cleanup of an abandoned adjacent recovery guard then fails, the process releases the exact replacement it just published before propagating the cleanup error, so failure cannot leave new live ownership stranded. Complete regular-file guards left by `0.22.0` use a separate directory recovery guard; abandoned directory recovery guards use the same internal-claim protocol, while abandoned legacy recovery files convert under a recoverable migration guard.
137
-
138
- Release first compares the exact owner token, then atomically renames the stable guard away before recursively removing its directory and metadata. The stable transaction path therefore never exposes partial recursive cleanup as available ownership. New writers create only directory guards. Malformed directories, unsupported filesystem nodes, unverifiable owners, and failed atomic publication remain fail-closed after bounded contention rather than risking concurrent mutation.
136
+ ```text
137
+ ~/.pi/agent/locks.json.transaction
138
+ ```
139
139
 
140
- Transactional reads treat only a missing registry as empty. Read, parse, and shape failures abort without replacing the existing file or erasing unrelated ownership keys.
140
+ All participating extensions must follow one compatible protocol:
141
141
 
142
- Each runtime retains the profile key plus exact owner identity it acquired. New leaders receive a collision-resistant epoch independent from heartbeat timestamps and a monotonic same-process runtime generation. Refresh, release, and thread-state snapshot publication commit only while the profile key, PID, cwd, instance id, epoch, and runtime generation still match. Snapshot rename runs inside the same lock-registry transaction guard as its final owner check. Forced replacement additionally requires the exact previously observed owner; same-process lifecycle handoff permits only a newer runtime generation to replace an older one. A delayed old runtime cannot reverse that transition, publish prepared thread state, or reinterpret its retained owner token under another profile key.
142
+ - Acquire the guard before every ownership acquisition, refresh, release, takeover, or other registry mutation.
143
+ - Publish fully initialized private owner metadata atomically. A portable implementation may stage a non-empty directory containing `owner.<generation>.json`, require filename/payload generation agreement, and rename that directory into the stable guard path.
144
+ - Do not depend on hard links or platform-specific advisory locks; the protocol must work on Linux, macOS, native Windows, and Android/Termux filesystems supported by Pi.
145
+ - Read and validate the latest complete registry only after guard acquisition, change only the owned extension key, and preserve every unrelated key from that guarded snapshot.
146
+ - Publish the JSON payload through a same-directory temporary file and atomic rename. Atomic payload replacement prevents torn JSON but does not replace transaction serialization.
147
+ - Release only the exact acquired owner by atomically renaming the stable guard away before cleanup. Stale recovery must prove the observed owner process is dead and must fence delayed recovery against replacement-owner ABA races.
148
+ - Fail closed on malformed owner metadata, malformed registry state, unverifiable generations, contention timeout, or unsupported atomic filesystem behavior.
143
149
 
144
- Direct Bot API authority follows this exact ownership check. Accepted local queue work may continue through Pi after ownership moves, but stale preview/final/menu/file mutations fail closed instead of bypassing the replacement transport owner. Follower recovery retries registration while the exact external owner remains live and promotes only after an election transaction confirms that the observed owner still remains stale or that no owner appeared after an inactive observation; IPC unreachability alone never authorizes takeover. Simultaneous election losers re-register with the winner using their carried exact thread target.
150
+ Lock-free reads remain appropriate for status display when readers tolerate an old-or-new complete snapshot. Any decision that mutates shared ownership must re-read and validate under the transaction.
145
151
 
146
- The ownership heartbeat starts immediately after acquisition, before binding handoff or slow leader startup. It remains active through provisioning/server/polling startup; startup errors release the exact acquired lock after cleanup, and ownership loss during startup stops the partial runtime and returns failure rather than announcing leadership. Topic provisioning also stamps the acquired epoch and rechecks it before and after every persistence and Bot API boundary, including `epoch → undefined` loss.
152
+ Cross-writer safety is compositional: every writer targeting the same registry must participate in the protocol. One compliant writer cannot guarantee lost-update safety against another writer that bypasses the shared transaction.
147
153
 
148
154
  ## Migration
149
155
 
@@ -153,9 +153,9 @@ Leader election is heartbeat-gated and lock-backed:
153
153
  2. If no leader exists, acquire leadership and start polling.
154
154
  3. If a live leader exists, register as follower.
155
155
  4. If the leader heartbeat is stale, attempt an atomic leadership takeover; ordinary `/telegram-connect` on a follower is not a leadership move while the leader is live.
156
- 5. If several followers detect stale leadership, atomic compare/write lock acquisition ensures only one becomes leader.
156
+ 5. Heartbeat acknowledgements carry the authenticated live follower-slot roster. If several followers detect stale leadership, the lowest observed live slot attempts promotion immediately; higher slots defer one bounded election grace and re-check the lock. Atomic compare/write acquisition remains the final ownership authority, and a missing lower-slot follower cannot block a higher survivor beyond that grace.
157
157
 
158
- Followers first try to re-register after leader reload or unknown-heartbeat responses, carrying their last known target, slot, and thread name so the new leader can reuse the same binding. After the grace window they promote only when the exact observed leader lease has become stale or inactive; an unavailable IPC endpoint never authorizes replacing a still-live owner. If the exact live target is absent from persisted bindings, the leader recovers it instead of creating another Telegram thread and keeps its carried slot only when that slot is free. Every successful reuse refreshes the binding timestamp. The leader does not restore persisted followers into the live registry speculatively: after a bounded re-registration grace window it removes older follower records that still lack a live bus owner from current `state.json`, while preserving a recently refreshed binding across the brief registry gap caused by follower session replacement and never deleting Telegram tabs. This preserves real thread bindings through transient reload gaps without allowing historical records or competing pollers to masquerade as live state.
158
+ Followers first try to re-register after leader reload or unknown-heartbeat responses, carrying their last known target, slot, and thread name so the new leader can reuse the same binding. After the grace window they promote only when the exact observed leader lease has become stale or inactive; an unavailable IPC endpoint never authorizes replacing a still-live owner. If the exact carried target is absent from persisted bindings, the leader first runs the same synchronous visibility probe: success recovers it instead of creating another Telegram thread, explicit stale evidence provisions a replacement, and ambiguous failure rejects registration. An ambiguous absent-target probe persists only non-routable `probe-required` restoration evidence, so targetless retries and leader reloads must probe that exact target again instead of activating it or provisioning a speculative replacement. A carried slot survives only when that slot remains free. Every successful reuse refreshes the binding timestamp. The leader never restores persisted followers into the live registry speculatively. Absent follower records remain durable restart hints until explicit stale, deleted, offline, or reconciliation evidence invalidates them; only fresh authenticated registration creates live routing authority. This preserves real thread bindings through reload and process-absence gaps without allowing historical records or competing pollers to masquerade as live state.
159
159
 
160
160
  ## Leader/Follower Communication
161
161
 
@@ -189,7 +189,7 @@ Manual smoke checklist:
189
189
  3. Start Pi in a second Windows terminal and run `/telegram-connect`; verify it registers as follower rather than offering takeover, creates/uses its assigned thread, terminal status shows `<ThreadName> Follower` while idle, and a follower prompt flips it to `<ThreadName> Active` while work is running.
190
190
  4. From the follower thread, send a prompt that requests inline buttons; tap a button and verify the follow-up prompt queues in the follower instance.
191
191
  5. From the follower thread, request a voice reply and/or attachment; verify upload routes through the leader transport into the follower thread.
192
- 6. Close the follower terminal; verify heartbeat pruning, disconnected notice, and cleanup behavior match Unix-like behavior.
192
+ 6. Close the follower terminal without an explicit disconnect; verify heartbeat pruning remains silent and preserves the follower tab/binding for recovery, matching Unix-like behavior. Then reconnect and run `/telegram-disconnect`; verify the leader confirms deletion of that follower's current tab before local polling stops.
193
193
  7. Reload the leader and verify status/debug output does not expose raw pipe internals except in explicit diagnostics.
194
194
 
195
195
  If any step fails, capture `telegram-status --debug`, `tmp/telegram/state.json`, `tmp/telegram/logs.jsonl`, and, after a reload, `tmp/telegram/logs._prev.jsonl`. Debug status prints local leader/follower endpoints with their active transport kind (`pipe` or `socket`), while the runtime log records request-scoped transport failures with envelope kind, request id, retry attempt, endpoint, and classified IPC error. Reloads preserve the prior JSONL log as `logs._prev.jsonl` so the evidence that caused the reload is not immediately overwritten.
@@ -215,7 +215,7 @@ In Telegram private-chat Threaded Mode:
215
215
  - `All` is an aggregate view, not a process launcher. Explicit new instances use live Pi follower registration: the operator starts Pi in a terminal and runs `/telegram-connect`; owner-created empty threads are observed but not treated as a Pi instance until the user chooses a route or restore action.
216
216
  - The leader proactively creates or reclaims its own thread on startup/activation when Threaded Mode is available, so the visible leader has the same two-way binding as followers.
217
217
  - **Unbound thread detection**: when the owner writes in an unknown `message_thread_id`, the bridge checks effective Threaded Mode state. If the current leader has no active bound thread, that new thread is reclaimed for the leader and the prompt is served locally. Otherwise the bridge preserves the prompt in that Telegram thread and shows a target-thread chooser; explicit routing may later close/delete only extra confirmed source threads through `thread-reconciler`.
218
- - Unknown later threads and threadless prompt messages are not silently routed to the leader and never launch hidden Pi processes. The default and only operator path for a new visible instance is starting a visible second Pi process and letting it register as follower through `/telegram-connect`. Manual follower registration creates a fresh visible thread unless the same explicit binding identity already has a live binding; old offline/failed records may point at closed/deleted Telegram tabs and are not silently claimed.
218
+ - Unknown later threads and threadless prompt messages are not silently routed to the leader and never launch hidden Pi processes. The default and only operator path for a new visible instance is starting a visible second Pi process and letting it register as follower through `/telegram-connect`. A manual follower with the same stable binding identity reclaims its current persisted thread across process restart; only an authenticated live registration becomes routing authority. Explicit stale/deleted observations invalidate that restoration hint before a fresh thread is provisioned.
219
219
  - Thread lifecycle service messages (`forum_topic_created`, `forum_topic_closed`, `forum_topic_reopened`, deletion/stale send errors) update observations and binding state. Closed/deleted leader or follower threads can be reclaimed or recreated deliberately. Leader startup also probes reused own threads with a non-visible chat action; if Telegram reports the thread closed/deleted, the binding is marked stale and a fresh leader thread is created. Unknown `forum_topic_created` service events are observation-only and are not destructive cleanup proof.
220
220
  - Bidirectional binding is a core UX requirement, not an implementation detail: Pi instances actively advertise/remember their thread identity, while the bot observes Telegram-client thread state and reflects it back into instance state. This keeps the system responsive, recognizable, and controllable even when the operator closes tabs, writes from `All`, or a follower later becomes leader.
221
221
 
@@ -224,16 +224,16 @@ In Telegram private-chat Threaded Mode:
224
224
  - The private bot DM becomes the operator's multi-instance dashboard.
225
225
  - Each live bound instance gets one visible thread.
226
226
  - Each instance has a durable single-letter slot (`A`-`Z`) assigned by the extension and a bridge-authored `threadName`.
227
- - New slots advance through the alphabet and wrap after `Z` only to a free slot, intentionally capping concurrent visible instances to the alphabet without duplicating occupied letters. The compact `bot.lastSlot` cursor persists while its binding remains live/recovering, including true `Z → A` wraparound. When post-grace follower compaction removes the cursor's binding, that same reconciliation pass realigns it to the newest-created remaining live binding; pending provisions and reservations still block collisions. Other explicit thread deletion paths may preserve the cursor to continue ring sequence.
228
- - A follower that later becomes leader keeps its existing slot and thread name; leadership changes are transport role changes, not identity resets.
227
+ - New slots advance through the alphabet and wrap after `Z` only to a free slot, intentionally capping concurrent visible instances to the alphabet without duplicating occupied letters. The compact `bot.lastSlot` cursor persists while its binding remains live or recoverable, including true `Z → A` wraparound. Pending provisions, reservations, and retained restart bindings occupy their slots until explicit stale/deleted evidence invalidates them.
228
+ - A follower that later becomes leader keeps its existing slot and thread name; leadership changes are transport role changes, not identity resets. Immediately after follower promotion succeeds, the new leader retains a short-lived process-local handoff bound to its exact Telegram profile owner key and refreshes it before session replacement. The replacement session consumes it only after acquiring leader authority, converts any surviving manual-follower record for that target into the current leader binding, persists the target/slot/name, and only then runs ordinary topic provisioning; this handoff is restoration evidence, never live routing authority.
229
229
  - Instance-thread names are short and recognizable. Default provisioning chooses one baked 4-6 letter single-word Latin thread name from the assigned slot's five-name palette using provisioning timestamp entropy and creates the Telegram thread with that title immediately. The slot remains internal ordering metadata and is not redundantly included in the thread name. Bare slot titles are fallback/legacy state only; do not prompt agents to self-name and do not expose a rename tool. Existing human-named threads are preserved across reloads and leadership changes when they remain the current live binding. If reload creates a new runtime instance while the previous leader thread is still alive, the new leader should take the next free slot instead of reusing the old slot immediately.
230
230
  - A thread-local `/start` opens that instance's menu.
231
231
  - Prompts typed in a thread route to the owning instance.
232
232
  - Replies, previews, files, voice, and buttons stay in that thread.
233
233
  - Queue controls and reactions affect only that instance target.
234
234
  - Telegram's native `…typing` indicator for real agent work is sent to that instance thread and mirrored to `All`; `All` is the aggregate surface and should show activity when any bound instance is running a Telegram turn, local prompt, or autonomous continuation. Terminal `Active` remains Telegram-turn-specific. Startup/connect/reload/recovery must not send activity by themselves.
235
- - If the instance disconnects, the leader can post/update a compact status: `Instance offline`.
236
- - If the same live binding identity returns, it can reclaim the thread and post a compact reconnect status.
235
+ - Generic heartbeat pruning remains silent and preserves the thread as a restart hint; it does not post an `Instance offline` notice.
236
+ - If the same binding identity returns, authenticated registration can reclaim the thread after the required visibility proof.
237
237
 
238
238
  ## Bot API Evidence For Private-Chat Threaded Mode
239
239
 
@@ -252,7 +252,7 @@ Remaining live-verification points:
252
252
 
253
253
  - 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.
254
254
  - 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.
255
- - Whether every rich draft/final/upload/chat-action path behaves identically in Telegram clients when `message_thread_id` is supplied.
255
+ - 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.
256
256
 
257
257
  Implemented behavior stays evidence-gated: when Telegram client or Bot API behavior differs from the contract above, capture a minimized fixture or documented client caveat before changing routing.
258
258
 
@@ -349,7 +349,7 @@ Current state under the agent dir:
349
349
  - `tmp/telegram/state.json`: volatile extension+bot observable/debug snapshot, not routing authority. It writes `source: "snapshot"` and `writtenAtMs` so consumers do not confuse it with an authoritative database. Every process on one Telegram profile reads this shared path, but only the active transport lock owner may persist it; followers become writers only after promotion. Status-only persistence refreshes disk-backed bindings before serialization so an already-loaded stale view cannot erase newer leader records. It mirrors `/telegram-status`-style projections: top-level `bot` stores bot-wide capability state such as `threadMode: "unknown" | "enabled" | "disabled"`, `runtime` identifies leader/follower role and process status, `liveRoster` mirrors followers/current targets/reservations, `diagnostics` mirrors status/debug signals, `threads` stores current routeable bindings, `bot.lastSlot` stores the compact slot cursor used when all current threads are gone, and `reservations` records short-lived slot collision guards.
350
350
  - Local bus endpoints: Unix-like platforms expose stable `tmp/telegram/bus.sock` and `tmp/telegram/followers/*` symlinks backed by private generation sockets; native Windows uses deterministic named pipes under `\\.\pipe\pi-telegram-...`. These are transient IPC endpoints, not durable routing state.
351
351
 
352
- The bridge must not keep a durable `telegram-targets.json` history. Stale/offline/failed thread entries are reconciliation observations, not reusable source-of-truth state; persisting them increases collision risk. `sync` is event-driven assumption reconciliation, not full Telegram bot-state mirroring, because Bot API does not expose a complete topic/thread listing surface. `state.json` therefore exists for extension+bot observability, diagnostics, startup hints, and explaining reconciliation decisions; live bus/runtime state remains authoritative for routing and provisioning. Non-current routeable thread bindings are pruned during load/persist; old session records must not be retained just to compute the next slot because `bot.lastSlot` is the only durable cursor. Previous-process leader bindings are treated as occupied TTL-bounded reservations until Telegram confirms deletion: reload/startup may close/delete/probe the old thread, known reservations are retried proactively on leader startup, and if Telegram still accepts the old thread id, the new leader should provision the next free slot (`B`, `C`, …) rather than creating a duplicate same-letter tab or blocking startup on Telegram UI convergence. Routing must use live current threads/follower registry, never reservations. The bus leader provisions its own thread during bus startup/connect and provisions follower threads on `follower.register`; registered followers also live in the leader's in-memory registry and communicate over the local bus socket. The live follower registry can resolve a follower by exact `{ chatId, threadId? }`; the leader uses that target ownership to forward message and edited-message updates to followers, and the follower receiver accepts those updates in addition to callbacks and reactions. Terminal status and `[telegram|thread:name]` resolve the matching current-instance identity through the same target-aware path, preferring registered local metadata over stale shared bindings. Media album grouping and split-text coalescing keys include the thread target, queue reaction mutations can scope by chat/thread to avoid cross-target message-id collisions, active-turn target is exposed for lifecycle cleanup and local direct-tool defaults, transport reply dedup is chat/thread-scoped, stored menu state is keyed by chat/message so callback state lookup cannot collide across chats, and generated button turns plus section prompt/open actions preserve the callback thread target. `telegram_message` and immediate `telegram_attach` delivery can also carry an explicit `thread_id` with `chat_id`; when a follower is registered, their default direct-tool target is the assigned thread target and the bus-aware API runtime routes the send through the leader instead of calling Bot API transport locally.
352
+ The bridge must not keep a separate durable `telegram-targets.json` history. `state.json` retains current stable manual-follower bindings as restart hints, but they never authorize routing without a matching authenticated live registration. Stale/offline/failed observations are not reusable delivery authority. `sync` remains event-driven assumption reconciliation rather than a full Telegram bot-state mirror because Bot API exposes no complete thread listing surface. Non-current routeable thread bindings are pruned during load/persist; old session records must not be retained just to compute the next slot because `bot.lastSlot` is the only durable cursor. Previous-process leader bindings are treated as occupied TTL-bounded reservations until Telegram confirms deletion: reload/startup may close/delete/probe the old thread, known reservations are retried proactively on leader startup, and if Telegram still accepts the old thread id, the new leader should provision the next free slot (`B`, `C`, …) rather than creating a duplicate same-letter tab or blocking startup on Telegram UI convergence. Routing must use live current threads/follower registry, never reservations. The bus leader provisions its own thread during bus startup/connect and provisions follower threads on `follower.register`; registered followers also live in the leader's in-memory registry and communicate over the local bus socket. The live follower registry can resolve a follower by exact `{ chatId, threadId? }`; the leader uses that target ownership to forward message and edited-message updates to followers, and the follower receiver accepts those updates in addition to callbacks and reactions. Terminal status and `[telegram|thread:name]` resolve the matching current-instance identity through the same target-aware path, preferring registered local metadata over stale shared bindings. Media album grouping and split-text coalescing keys include the thread target, queue reaction mutations can scope by chat/thread to avoid cross-target message-id collisions, active-turn target is exposed for lifecycle cleanup and local direct-tool defaults, transport reply dedup is chat/thread-scoped, stored menu state is keyed by chat/message so callback state lookup cannot collide across chats, and generated button turns plus section prompt/open actions preserve the callback thread target. `telegram_message` and immediate `telegram_attach` delivery can also carry an explicit `thread_id` with `chat_id`; when a follower is registered, their default direct-tool target is the assigned thread target and the bus-aware API runtime routes the send through the leader instead of calling Bot API transport locally.
353
353
 
354
354
  All files containing routing, chat ids, thread ids, or process details use private permissions and represent current state rather than historical target caches.
355
355
 
@@ -373,11 +373,12 @@ All files containing routing, chat ids, thread ids, or process details use priva
373
373
  - Leader prunes the follower from the live registry after missed heartbeats, but heartbeat pruning is only immediate liveness bookkeeping.
374
374
  - A missed heartbeat does not delete, close, mark offline, or send a disconnected notice for the follower's Telegram thread binding because the common cause may be leader reload, IPC handoff, or transient reconnect rather than a dead follower.
375
375
  - Followers treat rejected/missing heartbeat acknowledgements as registration loss: retain the last known target locally, clear registered truth, try to re-register with the current leader, wait a short leader-reload grace window, and retry. They promote only after the exact leader lease becomes stale or inactive; a live owner with an unreachable endpoint leaves the follower disconnected/retrying rather than creating a competing poller.
376
- - After leader reload grace expires, persisted manual-follower records without a matching live registry owner leave current `state.json`; this compaction is non-destructive and does not close/delete the Telegram thread.
377
- - Every successful follower registration/re-registration sends a compact connected notice in the assigned thread so recovery and reconnection are visible during live testing without confusing heartbeat suspicion with real disconnect.
376
+ - Persisted current manual-follower bindings survive process absence as restoration hints, but cannot receive inbound or outbound work until the replacement follower authenticates and registers with a fresh generation.
377
+ - Freshly provisioned follower registration sends a compact connected notice in the assigned thread. Cross-session restoration sends the same notice once as a visibility probe: success surfaces the reused tab, explicit stale-topic rejection provisions a monotonic replacement before registration succeeds, and ambiguous/non-stale failure records diagnostics and rejects registration without replay or speculative replacement.
378
+ - Registration requires a present generation, and explicit disconnect requires that same exact live generation. Leader-side registration and disconnect mutations serialize per durable follower profile across old and replacement runtime instance IDs, so a replacement registration cannot overtake awaited destructive cleanup and an old disconnect cannot remove its successor's routing authority.
378
379
  - Successful forwarded updates and follower-originated API calls refresh liveness, so active followers are not pruned only because the interval heartbeat tick lagged.
379
- - Destructive follower thread teardown belongs to explicit `/telegram-disconnect` or confirmed reconciliation actions, not generic heartbeat pruning.
380
- - Historical offline thread entries are not retained as reusable source of truth.
380
+ - Destructive follower thread teardown belongs to explicit `/telegram-disconnect` or confirmed reconciliation actions, not generic heartbeat pruning. A registered follower sends an authenticated request fenced by its exact registration generation; the active leader closes and deletes that follower's exact topic, marks its durable binding offline, removes live routing authority, and acknowledges completion before the follower stops. Cleanup counts as confirmed only after successful deletion or explicit already-gone evidence. Incomplete cleanup preserves the binding and registration for retry. A promoted leader uses its current owned leader epoch even when the inherited record still carries a historical `manual-follower` owner label.
381
+ - Explicit stale/deleted/offline observations invalidate reuse; mere process absence does not.
381
382
 
382
383
  ### Thread is deleted
383
384
 
@@ -409,7 +410,7 @@ All files containing routing, chat ids, thread ids, or process details use priva
409
410
  - [x] Followers never call `getUpdates` for the shared bot token.
410
411
  - [x] Followers can send replies, previews, voice, attachments, menus, and chat actions through the leader transport.
411
412
  - [x] The leader can route inbound messages, edits, callbacks, reactions, media groups, and split text to the owning instance by target. Message/edit and callback/reaction routing is authorized by user id; media and split-text coalescing are target-keyed locally.
412
- - [x] Telegram UI thread targets can be provisioned as current state bindings; stale/deleted Telegram observations and explicit disconnect/reconciliation actions remove unusable bindings instead of persisting reusable history, while heartbeat-pruned followers preserve their thread binding so transient leader reload/reconnect gaps do not create split-brain Telegram UX.
413
+ - [x] Telegram UI thread targets can be provisioned as current state bindings; stable manual-follower identities reclaim current bindings across process restart, authenticated registration generation gates routing, and stale/deleted observations or explicit disconnect/reconciliation remove unusable bindings.
413
414
  - [x] Leader failover promotes one remaining follower without creating competing pollers.
414
415
  - [x] Queue, active turn, preview, reply deduplication, menu, section, button, reaction, and attachment state are scoped by instance/target. Queue reaction mutations and transport reply dedup are chat/thread-scoped; active-turn target is available to lifecycle cleanup; stored menu state is chat/message-keyed; generated button turns and section prompt/open actions preserve callback targets; preview and attachment delivery already carry targets.
415
416
  - [x] Authorization prevents arbitrary Telegram users or local processes from controlling agents or receiving artifacts.
@@ -424,7 +425,7 @@ Live client and native Windows evidence gates are tracked in `BACKLOG.md`; this
424
425
  - The transport lock distinguishes live bus leadership from ordinary classic ownership through heartbeat, leader epoch, and stale takeover rules.
425
426
  - The leader records live follower registration, heartbeat, thread identity, slot, and target mapping; followers do not poll `getUpdates`.
426
427
  - Local IPC is the default internal bus. Registered followers receive normalized inbound updates and send allowlisted, target-scoped Bot API calls through the leader.
427
- - Thread targets are current-state bindings, not durable historical delivery addresses. Stale/offline/failed entries are reconciliation evidence only.
428
+ - Thread targets are current-state bindings, not historical delivery addresses. Stable restart hints require a fresh authenticated follower registration before they become live routing authority; stale/offline/failed entries remain reconciliation evidence only.
428
429
  - Failover promotes a remaining follower after dead or clean-disconnected leaders without creating competing pollers; follower heartbeat recovery owns re-register → grace → promotion while preserving thread bindings across transient leader reload gaps.
429
430
  - Thread cleanup is centralized in `thread-reconciler`, fails closed without a leader epoch while leadership exists, revalidates that epoch immediately before every close/delete call and local cleanup-state mutation, and requires confirmed delete/stale evidence before state is marked deleted.
430
431
  - Stable docs/UI now describe classic mode, opt-in Threaded Mode, manual follower registration, status/diagnostics, unbound-thread reroute/restore UX, and operator recovery boundaries.
package/docs/outbound.md CHANGED
@@ -6,6 +6,12 @@ Normal Telegram-turn replies are intentionally prompt-driven: the agent writes M
6
6
 
7
7
  Text handlers use the portable [Command Template Standard](./command-templates.md). Programmatic outbound handlers use `registerTelegramOutboundHandler(kind, handler)`. Voice replies can use configured command-template handlers or the provider API described in [Voice Integration](./voice.md).
8
8
 
9
+ ## Proactive Public Output
10
+
11
+ Proactive projection defaults on. With `assistant.proactivePush` omitted or set to `true`, completed public assistant text blocks from local or autonomous Pi work are projected to the instance's authorized Telegram target; set it explicitly to `false` to opt out. A visible intermediate commentary/checkpoint and the final answer become separate Telegram messages in source order; this is not a final-only `agent_end` notification. The bridge consumes normalized Activity `assistant-segment` events, not raw token deltas, reasoning, or tool traffic.
12
+
13
+ Proactive blocks use `assistant.rendering` independently of voice policy. Rich mode sends native Rich Markdown and HTML mode keeps the established HTML renderer; proactive projection does not synthesize voice or attach queued files merely because Rich rendering is active. The queue revalidates exact target, profile/token transport generation, leader epoch or follower registration generation, and session generation before each send. Telegram-owned turns remain on their ordinary reply path, and `commit-unknown` never permits proactive replay.
14
+
9
15
  ## Standard
10
16
 
11
17
  An outbound handler is selected by `type`. Text replies and assistant markup map to handler types:
@@ -18,6 +24,16 @@ An outbound handler is selected by `type`. Text replies and assistant markup map
18
24
 
19
25
  The voice pipeline is detailed below: configured `type: "voice"` handlers first, then programmatic handlers, then registered synthesis providers.
20
26
 
27
+ ### Single Rich attachment result
28
+
29
+ When `assistant.rendering` is `"rich"`, a Telegram-originated turn that queues exactly one probe-confirmed PNG/JPEG photo, MP4 video, or MP3 audio file through `telegram_attach` can combine that artifact with the final assistant Markdown in one multipart `sendRichMessage` result. The bridge normalizes the Markdown, adds one `tg://photo`, `tg://video`, or `tg://audio` reference, preserves the triggering-message reply anchor and assigned thread, carries assistant-authored inline buttons, and records the returned message id under the exact local/follower ownership scope.
30
+
31
+ The optimization is deliberately narrow. HTML rendering, empty final text, multiple files, documents and other unsupported formats, Guest Mode, explicit `telegram_voice`, voice-preferred turns, and OGG/Opus artifacts retain their established text/attachment/voice paths. A known-safe Rich upload rejection falls back to those paths. A `commit-unknown` transport outcome or a nominally successful upload without a verifiable message id never falls back or replays because the first non-idempotent send may already have committed.
32
+
33
+ This behavior does not generate media or alter voice policy. `telegram_attach` still represents an explicit assistant artifact decision, while `manual`, `mirror`, and `always` continue to decide voice synthesis independently.
34
+
35
+ Core assistant output accepts only the Markdown or HTML `InputRichMessage` forms and does not construct explicit block arrays or `InputRichBlockThinking`. Telegram's Thinking block is draft-only and must never become a projection of hidden reasoning or chain-of-thought. Any future use for Activity would require an explicitly public user-visible summary rather than provider reasoning content.
36
+
21
37
  ### Guest Mode media boundary
22
38
 
23
39
  A Guest Mode reply is one `answerGuestQuery` call carrying exactly one `InlineQueryResult`; it is not a normal chat target and cannot receive `sendDocument`/`sendVoice` multipart uploads through sentinel `chatId: 0`. `telegram_attach` therefore admits at most one file during a guest turn and rejects additional files before queue mutation.
@@ -41,7 +41,7 @@ Stable commands inside Pi:
41
41
 
42
42
  - `/telegram-setup` — configure/update the bot token.
43
43
  - `/telegram-connect` — start polling here and acquire external Telegram control ownership. Accepted queue/reply state stays local if ownership later moves elsewhere.
44
- - `/telegram-disconnect` — stop polling and release ownership without deleting or silencing accepted local queue state.
44
+ - `/telegram-disconnect` — stop polling and release ownership without deleting or silencing accepted local queue state. In Threaded Mode it first asks for confirmation, then deletes this instance's current Telegram thread; a follower waits for its active leader to confirm generation-fenced cleanup before stopping.
45
45
  - `/telegram-status` — show connection, polling, execution, queue, and recent event diagnostics.
46
46
 
47
47
  ### Telegram commands
@@ -61,7 +61,7 @@ This command surface is a mobile companion subset, not a raw terminal-command br
61
61
 
62
62
  ### Tools and assistant-authored actions
63
63
 
64
- - `telegram_attach(paths, chat_id?, thread_id?, caption?)` is the stable artifact delivery tool for generated files. During Telegram turns it queues files for the active reply; outside Telegram turns it sends files directly to the paired/default chat, the registered follower's assigned thread, or an explicit `chat_id` plus optional `thread_id` when this Pi instance owns `/telegram-connect` or is registered with the multi-instance bus.
64
+ - `telegram_attach(paths, chat_id?, thread_id?, caption?)` is the stable artifact delivery tool for generated files. During Telegram turns it queues files for the active reply; with `assistant.rendering: "rich"`, exactly one PNG/JPEG, MP4, or MP3 artifact plus non-empty final Markdown can become one reply-anchored Rich Message. HTML mode, multiple/unsupported files, Guest Mode, and voice outputs retain their established paths. Outside Telegram turns the tool sends files directly to the paired/default chat, the registered follower's assigned thread, or an explicit `chat_id` plus optional `thread_id` when this Pi instance owns `/telegram-connect` or is registered with the multi-instance bus.
65
65
  - `telegram_message(text, chat_id?, thread_id?)` sends a direct Telegram Markdown message from local/TUI-initiated work when this Pi instance owns `/telegram-connect` or is registered with the multi-instance bus. 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.
66
66
  - `telegram_help()` returns detailed agent-facing guidance for pi-telegram delivery actions, Threaded Mode, formatting, and debugging. The regular prompt only points agents at this tool instead of repeating the full guidance on every turn.
67
67
  - `telegram_voice` hidden comments request Telegram-native voice delivery.
@@ -84,10 +84,14 @@ interface TelegramConfig {
84
84
  botId?: number; // runtime-managed
85
85
  allowedUserId?: number;
86
86
  lastUpdateId?: number; // runtime-managed
87
- proactivePush?: boolean;
88
87
  inboundHandlers?: TelegramInboundHandlerConfig[];
89
88
  attachmentHandlers?: TelegramInboundHandlerConfig[]; // compatibility alias
90
89
  outboundHandlers?: TelegramOutboundHandlerConfig[];
90
+ assistant?: {
91
+ draftPreviews?: boolean;
92
+ rendering?: "rich" | "html";
93
+ proactivePush?: boolean;
94
+ };
91
95
  voice?: {
92
96
  replyMode?: "manual" | "mirror" | "always";
93
97
  sendTranscript?: boolean;
@@ -101,11 +105,12 @@ interface TelegramConfig {
101
105
 
102
106
  Hidden/default semantics are represented by absence:
103
107
 
108
+ - `assistant.proactivePush` defaults to `true`; omit it to keep projection enabled, or set it explicitly to `false` to disable it. When enabled, each completed public assistant text block from local or autonomous work is projected to the authorized Telegram target once and in source order. This includes visible intermediate commentary/checkpoints and the final block. It excludes token deltas, hidden reasoning, tool calls/arguments/results, Telegram-owned turns, empty blocks, and stale authority. Projection uses the configured Rich or HTML assistant renderer and binds admitted work to the exact target, profile/token transport generation, direct leader epoch or follower registration generation, and session generation. The old top-level `proactivePush` key is ignored; move the setting manually under `assistant`.
104
109
  - Voice Reply `hidden`: no `voice.replyMode` key is persisted.
105
110
  - Agent activity status is not configurable in this release. Telegram uses native `sendChatAction(typing)` / product `...active` status as the only automatic in-chat work signal before the final reply.
106
111
  - Time Injection `hidden`: no `time.injectionMode` key is persisted; if `time` becomes empty, the whole `time` object may be omitted.
107
112
 
108
- Assistant Markdown delivery is native: final replies are sent as `InputRichMessage.markdown` via `sendRichMessage`, and draft previews use `sendRichMessageDraft` when a structurally closed preview frame is available. Draft-frame failures are recorded and skipped rather than converted into raw plain preview messages, because partial Markdown can be temporarily invalid while the final answer remains valid. Long native replies are split at Telegram Rich Message transport limits, with oversized fenced code, display-math, and fully wrapped inline-formatting blocks rewrapped per chunk so persisted chunks remain structurally valid. Guest replies use `InputRichMessageContent` in `answerGuestQuery` results. Bridge-owned UI surfaces such as menus, status, queue controls, commands, and sections keep explicit Telegram HTML/plain rendering by default because those texts are authored by the bridge or companion extensions for Telegram UI. Companion extension sections may explicitly request `"markdown"`, `"html"`, or `"plain"` per view. There is no `telegram.json` rendering toggle for assistant delivery. The bridge sets `skip_entity_detection: true` for assistant and guest Markdown so technical text such as `/commands`, hashtags, URLs, phone numbers, and card-like numbers does not gain unintended automatic entities; explicit Markdown links still belong in the Markdown source.
113
+ With `assistant.rendering: "rich"` (the default), assistant Markdown delivery is native: final replies are sent as `InputRichMessage.markdown` via `sendRichMessage`, and draft previews use `sendRichMessageDraft` when a structurally closed preview frame is available. Draft-frame failures are recorded and skipped rather than converted into raw plain preview messages, because partial Markdown can be temporarily invalid while the final answer remains valid. Long native replies are split at Telegram Rich Message transport limits, with oversized fenced code, display-math, and fully wrapped inline-formatting blocks rewrapped per chunk so persisted chunks remain structurally valid. Guest replies use `InputRichMessageContent` in `answerGuestQuery` results. Bridge-owned UI surfaces such as menus, status, queue controls, commands, and sections keep explicit Telegram HTML/plain rendering by default because those texts are authored by the bridge or companion extensions for Telegram UI. Companion extension sections may explicitly request `"markdown"`, `"html"`, or `"plain"` per view. `assistant.rendering: "html"` keeps the compatibility path that converts assistant Markdown to Telegram HTML before ordinary message delivery. The bridge sets `skip_entity_detection: true` for assistant and guest Markdown so technical text such as `/commands`, hashtags, URLs, phone numbers, and card-like numbers does not gain unintended automatic entities; explicit Markdown links still belong in the Markdown source.
109
114
 
110
115
  Environment variables are stable only where documented in the README: bot-token bootstrap, proxy behavior, agent root, and inbound/outbound file size limits.
111
116
 
package/index.ts CHANGED
@@ -220,14 +220,11 @@ export default function (pi: Pi.ExtensionAPI) {
220
220
  scheduleSnapshotPersist: runtimeDiagnostics.scheduleSnapshotPersist,
221
221
  });
222
222
  const recordThreadReconciliationPlan = threadReconciliationRuntime.recordPlan;
223
- const markTelegramConfigSyncChange =
224
- telegramSyncStateRuntime.markConfigChange;
225
- const persistTelegramConfigWithSync = async function (
226
- nextConfig?: Config.TelegramConfig,
227
- ) {
228
- await configStore.persist(nextConfig);
229
- markTelegramConfigSyncChange("config-persist");
230
- };
223
+ const persistTelegramConfigWithSync =
224
+ Sync.createTelegramConfigSyncPersister<Config.TelegramConfig>({
225
+ persist: configStore.persist,
226
+ markConfigChange: telegramSyncStateRuntime.markConfigChange,
227
+ });
231
228
  const currentInstanceThreadRuntime =
232
229
  Threads.createTelegramCurrentInstanceThreadRuntime({
233
230
  instanceId: telegramInstanceId,
@@ -271,7 +268,7 @@ export default function (pi: Pi.ExtensionAPI) {
271
268
  getFollowerTarget: telegramBusFollowerRegistrationState.getTarget,
272
269
  getFollowerSlot: telegramBusFollowerRegistrationState.getSlot,
273
270
  getFollowerThreadName: telegramBusFollowerRegistrationState.getThreadName,
274
- getCurrentIdentity: getCurrentInstanceThreadIdentity,
271
+ getCurrentIdentity: currentInstanceThreadRuntime.getRestorationIdentity,
275
272
  });
276
273
  const statusRuntime = Status.createTelegramBridgeStatusRuntime<
277
274
  Pi.ExtensionContext,
@@ -347,6 +344,9 @@ export default function (pi: Pi.ExtensionAPI) {
347
344
  },
348
345
  getRegistrationGeneration:
349
346
  telegramBusFollowerRegistrationState.getGeneration,
347
+ getForwardCommentBatchPosition:
348
+ textGroupRuntime.getPreparedForwardingPosition,
349
+ recordRuntimeEvent,
350
350
  timeoutMs: 30_000,
351
351
  });
352
352
  const telegramApiRuntime = BusApi.createTelegramBusAwareApiRuntime({
@@ -445,8 +445,45 @@ export default function (pi: Pi.ExtensionAPI) {
445
445
  });
446
446
  },
447
447
  });
448
+ const { sendTextReply, sendMarkdownReply } =
449
+ Outbound.createTelegramOutboundTextReplyRuntime({
450
+ sendTextReply: replyRuntime.sendTextReply,
451
+ sendMarkdownReply: replyRuntime.sendMarkdownReply,
452
+ execCommand: CommandTemplates.execCommandTemplate,
453
+ getHandlers: configStore.getOutboundHandlers,
454
+ recordRuntimeEvent,
455
+ });
456
+ const assistantOutputBindingRuntime =
457
+ Bindings.createTelegramAssistantOutputBindingRuntime({
458
+ isEnabled: configControls.isProactivePushEnabled,
459
+ authority: {
460
+ getPreferredTarget: proactivePushTargetGetter,
461
+ getFallbackChatId: proactivePushChatIdGetter,
462
+ getTransportStamp: telegramTransportStampRuntime.getStamp,
463
+ isTransportStampActive: telegramTransportStampRuntime.isActive,
464
+ ownsDirect: lockRuntime.owns,
465
+ getDirectEpoch: lockRuntime.getOwnedLeaderEpoch,
466
+ isFollowerRegistered:
467
+ telegramBusFollowerRegistrationState.isRegistered,
468
+ getFollowerGeneration:
469
+ telegramBusFollowerRegistrationState.getGeneration,
470
+ },
471
+ sender: {
472
+ recordOwnership: messageOwnershipRuntime.recordLocal,
473
+ sendMessage,
474
+ sendRichMessage,
475
+ editMessage: editTelegramMessageText,
476
+ getAssistantRenderingMode: configControls.getAssistantRenderingMode,
477
+ execCommand: CommandTemplates.execCommandTemplate,
478
+ getHandlers: configStore.getOutboundHandlers,
479
+ recordRuntimeEvent,
480
+ },
481
+ recordRuntimeEvent,
482
+ });
483
+ const assistantOutputRuntime = assistantOutputBindingRuntime.runtime;
448
484
  const activityRuntime = Activity.createTelegramActivityBridgeRuntime({
449
485
  generation: deliveryGenerationSeed,
486
+ observeEvent: assistantOutputBindingRuntime.observeEvent,
450
487
  recordFailure(handlerId, event, error) {
451
488
  recordRuntimeEvent("activity", error, {
452
489
  handlerId,
@@ -455,14 +492,6 @@ export default function (pi: Pi.ExtensionAPI) {
455
492
  });
456
493
  },
457
494
  });
458
- const { sendTextReply, sendMarkdownReply } =
459
- Outbound.createTelegramOutboundTextReplyRuntime({
460
- sendTextReply: replyRuntime.sendTextReply,
461
- sendMarkdownReply: replyRuntime.sendMarkdownReply,
462
- execCommand: CommandTemplates.execCommandTemplate,
463
- getHandlers: configStore.getOutboundHandlers,
464
- recordRuntimeEvent,
465
- });
466
495
  const dispatchNextQueuedTelegramTurn =
467
496
  Queue.createTelegramQueueDispatchRuntime({
468
497
  ...telegramQueueStore,
@@ -622,9 +651,7 @@ export default function (pi: Pi.ExtensionAPI) {
622
651
  callApi: callTelegramApi,
623
652
  isTopicProvisioningActive: telegramProvisioningActivity.isActive,
624
653
  getCurrentLeaderEpoch,
625
- getThreadReconciliationMachineState() {
626
- return threadReconciliationRuntime.getState();
627
- },
654
+ getThreadReconciliationMachineState: threadReconciliationRuntime.getState,
628
655
  recordThreadReconciliationPlan,
629
656
  getSyncState: telegramSyncStateRuntime.getState,
630
657
  setSyncState: telegramSyncStateRuntime.setState,
@@ -650,9 +677,7 @@ export default function (pi: Pi.ExtensionAPI) {
650
677
  recordMessageOwnership: messageOwnershipRuntime.recordRouted,
651
678
  ...inboundBusProjectionRuntime,
652
679
  getCurrentLeaderEpoch,
653
- getThreadReconciliationMachineState() {
654
- return threadReconciliationRuntime.getState();
655
- },
680
+ getThreadReconciliationMachineState: threadReconciliationRuntime.getState,
656
681
  recordThreadReconciliationPlan,
657
682
  handleTelegramTopicLifecycleUpdate: topicLifecycleSync,
658
683
  handleTelegramThreadTargetObserved(_target, ctx) {
@@ -744,13 +769,13 @@ export default function (pi: Pi.ExtensionAPI) {
744
769
  receiver: {
745
770
  socketPath: getTelegramBusFollowerSocketPath,
746
771
  instanceId: telegramInstanceId,
747
- getContext() {
748
- return telegramSessionContextStore.get();
749
- },
772
+ getContext: telegramSessionContextStore.get,
750
773
  getAuthSecret() {
751
774
  return telegramActiveBusAuthSecret;
752
775
  },
753
776
  ...forwardedRouteHandlers,
777
+ prepareForwardedMessage:
778
+ textGroupRuntime.prepareForwardedMessage,
754
779
  recordRuntimeEvent,
755
780
  },
756
781
  targetReplacement: {
@@ -766,17 +791,13 @@ export default function (pi: Pi.ExtensionAPI) {
766
791
  },
767
792
  recovery: {
768
793
  registrationState: telegramBusFollowerRegistrationState,
769
- getLeaderState() {
770
- return lockRuntime.getState();
771
- },
794
+ getLeaderState: lockRuntime.getState,
772
795
  setLifecyclePhase(phase) {
773
796
  telegramBusLifecycleOverridePhase = phase;
774
797
  },
775
798
  updateStatus,
776
799
  promoteToLeader: promoteTelegramBusFollowerToLeader,
777
- getActiveContext() {
778
- return telegramSessionContextStore.get();
779
- },
800
+ getActiveContext: telegramSessionContextStore.get,
780
801
  recordRuntimeEvent,
781
802
  },
782
803
  registration: {
@@ -784,9 +805,7 @@ export default function (pi: Pi.ExtensionAPI) {
784
805
  getFollowerBusSocketPath: getTelegramBusFollowerSocketPath,
785
806
  getLeaderSocketPath: getTelegramBusSocketPath,
786
807
  registrationState: telegramBusFollowerRegistrationState,
787
- isContextActive(ctx) {
788
- return telegramSessionContextStore.isCurrent(ctx);
789
- },
808
+ isContextActive: telegramSessionContextStore.isCurrent,
790
809
  createRequestId: telegramBusFollowerClients.createRequestId,
791
810
  getLeaderAuthSecret(owner) {
792
811
  return owner.busSecret;
@@ -794,12 +813,7 @@ export default function (pi: Pi.ExtensionAPI) {
794
813
  setActiveAuthSecret(secret) {
795
814
  telegramActiveBusAuthSecret = secret;
796
815
  },
797
- getThreadName() {
798
- return undefined;
799
- },
800
- getProfileKey() {
801
- return getTelegramManualFollowerProfileKey();
802
- },
816
+ getProfileKey: getTelegramManualFollowerProfileKey,
803
817
  recordRuntimeEvent,
804
818
  },
805
819
  });
@@ -812,6 +826,7 @@ export default function (pi: Pi.ExtensionAPI) {
812
826
  deleteWebhook,
813
827
  getUpdates,
814
828
  persistConfig: persistTelegramConfigWithSync,
829
+ prepareUpdateBatch: textGroupRuntime.prepareUpdateBatch,
815
830
  handleUpdate: Updates.createTelegramUpdateHandle({
816
831
  defaultHandle: inboundRouteRuntime.handleUpdate,
817
832
  }),
@@ -819,17 +834,13 @@ export default function (pi: Pi.ExtensionAPI) {
819
834
  updateStatus,
820
835
  recordRuntimeEvent,
821
836
  });
822
- const recoverStaleTelegramTopicApiError = function (
823
- apiBody: unknown,
824
- error: unknown,
825
- ) {
826
- return Sync.recoverStaleTelegramTopicApiError(apiBody, error, {
837
+ const recoverStaleTelegramTopicApiError =
838
+ Sync.createTelegramStaleTopicApiErrorRecoveryRuntime({
827
839
  topicTargetStore: threadStore,
828
840
  getSyncState: telegramSyncStateRuntime.getState,
829
841
  setSyncState: telegramSyncStateRuntime.setState,
830
842
  recordEvent: recordRuntimeEvent,
831
843
  });
832
- };
833
844
  const authorizeFollowerApiCall = Bus.createTelegramFollowerApiCallAuthorizer({
834
845
  isMessageOwned: messageOwnershipRuntime.isOwnedByFollower,
835
846
  });
@@ -851,9 +862,7 @@ export default function (pi: Pi.ExtensionAPI) {
851
862
  },
852
863
  getAllowedUserId: configStore.getAllowedUserId,
853
864
  instanceId: telegramInstanceId,
854
- getCwd(ctx) {
855
- return typeof ctx.cwd === "string" ? ctx.cwd : undefined;
856
- },
865
+ getCwd: Pi.getExtensionContextCwd,
857
866
  getTelegramProfile: getActiveTelegramThreadProfile,
858
867
  shouldForceFreshUnnamed:
859
868
  telegramThreadCapabilityState.shouldForceFreshLeaderThread,
@@ -865,9 +874,7 @@ export default function (pi: Pi.ExtensionAPI) {
865
874
  downloadFile: directTelegramApiRuntime.downloadFile,
866
875
  recoverStaleTargetError: recoverStaleTelegramTopicApiError,
867
876
  getCurrentLeaderEpoch,
868
- getThreadReconciliationMachineState() {
869
- return threadReconciliationRuntime.getState();
870
- },
877
+ getThreadReconciliationMachineState: threadReconciliationRuntime.getState,
871
878
  recordThreadReconciliationPlan,
872
879
  getSyncState: telegramSyncStateRuntime.getState,
873
880
  setSyncState: telegramSyncStateRuntime.setState,
@@ -937,6 +944,8 @@ export default function (pi: Pi.ExtensionAPI) {
937
944
  getCurrentLeaderEpoch,
938
945
  getLeaderTarget: telegramBusLeaderState.getTarget,
939
946
  clearLeaderTarget: telegramBusLeaderState.clear,
947
+ disconnectFollowerThread:
948
+ telegramBusFollowerRegistration.disconnectFromLeader,
940
949
  getSyncState: telegramSyncStateRuntime.getState,
941
950
  setSyncState: telegramSyncStateRuntime.setState,
942
951
  stopPolling: lockedPollingRuntime.stop,
@@ -970,6 +979,10 @@ export default function (pi: Pi.ExtensionAPI) {
970
979
  registrationRuntime: telegramBusFollowerRegistration,
971
980
  instanceId: telegramInstanceId,
972
981
  suspendPolling: lockedPollingRuntime.suspend,
982
+ isLeader: lockRuntime.owns,
983
+ getLeaderBinding: currentInstanceThreadRuntime.getRestorationIdentity,
984
+ getActiveContext: telegramSessionContextStore.get,
985
+ getActiveProfileName: getActiveTelegramThreadProfile,
973
986
  getLeaderState: lockRuntime.getState,
974
987
  updateStatus,
975
988
  recordRuntimeEvent,
@@ -1000,6 +1013,11 @@ export default function (pi: Pi.ExtensionAPI) {
1000
1013
  activeTurnRuntime,
1001
1014
  lockedPollingRuntime,
1002
1015
  stopPolling: disconnectTelegramAndDeleteCurrentThread,
1016
+ getDisconnectThreadName() {
1017
+ const record = findCurrentThreadRecord();
1018
+ if (!record?.target.threadId) return undefined;
1019
+ return record.threadName ?? "current Telegram thread";
1020
+ },
1003
1021
  onTransportChanged: deliveryLifecycleRuntime.onSessionStart,
1004
1022
  getStatusLines,
1005
1023
  buttonActionStore,
@@ -1026,6 +1044,7 @@ export default function (pi: Pi.ExtensionAPI) {
1026
1044
  onModelSelect: currentModelRuntime.onModelSelect,
1027
1045
  },
1028
1046
  activityRuntime,
1047
+ assistantOutputRuntime,
1029
1048
  configStore,
1030
1049
  abort,
1031
1050
  typing,
@@ -1051,12 +1070,8 @@ export default function (pi: Pi.ExtensionAPI) {
1051
1070
  proactivePushChatIdGetter,
1052
1071
  proactivePushTargetGetter,
1053
1072
  isProactivePushEnabled: configControls.isProactivePushEnabled,
1054
- canSendProactivePush(ctx) {
1055
- return (
1056
- lockOwnershipGuard.ownsContext(ctx) ||
1057
- telegramBusFollowerRegistrationState.isRegistered()
1058
- );
1059
- },
1073
+ getAssistantRenderingMode: configControls.getAssistantRenderingMode,
1074
+ recordMessageOwnership: messageOwnershipRuntime.recordLocal,
1060
1075
  canSendAgentActivity(ctx) {
1061
1076
  return (
1062
1077
  lockOwnershipGuard.ownsContext(ctx) ||