@llblab/pi-kit 0.5.2 → 0.7.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.
Files changed (141) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +5 -5
  3. package/node_modules/@llblab/pi-actors/AGENTS.md +1 -1
  4. package/node_modules/@llblab/pi-actors/CHANGELOG.md +6 -0
  5. package/node_modules/@llblab/pi-actors/README.md +1 -1
  6. package/node_modules/@llblab/pi-actors/dist/lib/async-runs.d.ts +3 -0
  7. package/node_modules/@llblab/pi-actors/dist/lib/async-runs.js +14 -1
  8. package/node_modules/@llblab/pi-actors/dist/lib/command-templates.js +45 -3
  9. package/node_modules/@llblab/pi-actors/dist/lib/extension-runtime.js +1 -1
  10. package/node_modules/@llblab/pi-actors/dist/lib/observability.d.ts +16 -3
  11. package/node_modules/@llblab/pi-actors/dist/lib/observability.js +92 -7
  12. package/node_modules/@llblab/pi-actors/dist/lib/pi.d.ts +0 -1
  13. package/node_modules/@llblab/pi-actors/dist/lib/pi.js +15 -24
  14. package/node_modules/@llblab/pi-actors/dist/lib/run-delivery-lineage.d.ts +17 -0
  15. package/node_modules/@llblab/pi-actors/dist/lib/run-delivery-lineage.js +44 -0
  16. package/node_modules/@llblab/pi-actors/dist/lib/run-delivery.d.ts +4 -0
  17. package/node_modules/@llblab/pi-actors/dist/lib/run-delivery.js +102 -4
  18. package/node_modules/@llblab/pi-actors/dist/lib/run-ui-runtime.js +58 -39
  19. package/node_modules/@llblab/pi-actors/dist/lib/runtime.js +14 -6
  20. package/node_modules/@llblab/pi-actors/dist/skills/actors/SKILL.md +1 -1
  21. package/node_modules/@llblab/pi-actors/docs/async-runs.md +1 -1
  22. package/node_modules/@llblab/pi-actors/docs/coordinator-delivery.md +18 -23
  23. package/node_modules/@llblab/pi-actors/lib/async-runs.ts +18 -1
  24. package/node_modules/@llblab/pi-actors/lib/command-templates.ts +41 -3
  25. package/node_modules/@llblab/pi-actors/lib/extension-runtime.ts +1 -1
  26. package/node_modules/@llblab/pi-actors/lib/observability.ts +119 -5
  27. package/node_modules/@llblab/pi-actors/lib/pi.ts +15 -28
  28. package/node_modules/@llblab/pi-actors/lib/run-delivery-lineage.ts +68 -0
  29. package/node_modules/@llblab/pi-actors/lib/run-delivery.ts +120 -4
  30. package/node_modules/@llblab/pi-actors/lib/run-ui-runtime.ts +69 -44
  31. package/node_modules/@llblab/pi-actors/lib/runtime.ts +17 -6
  32. package/node_modules/@llblab/pi-actors/package.json +1 -1
  33. package/node_modules/@llblab/pi-actors/skills/actors/SKILL.md +1 -1
  34. package/node_modules/@llblab/pi-grow-loop/AGENTS.md +2 -2
  35. package/node_modules/@llblab/pi-grow-loop/CHANGELOG.md +4 -0
  36. package/node_modules/@llblab/pi-grow-loop/README.md +6 -6
  37. package/node_modules/@llblab/pi-grow-loop/index.ts +6 -3
  38. package/node_modules/@llblab/pi-grow-loop/package.json +1 -1
  39. package/node_modules/@llblab/pi-state-flow/AGENTS.md +33 -12
  40. package/node_modules/@llblab/pi-state-flow/BACKLOG.md +125 -2
  41. package/node_modules/@llblab/pi-state-flow/CHANGELOG.md +87 -45
  42. package/node_modules/@llblab/pi-state-flow/README.md +203 -107
  43. package/node_modules/@llblab/pi-state-flow/docs/README.md +4 -0
  44. package/node_modules/@llblab/pi-state-flow/docs/architecture.md +188 -0
  45. package/node_modules/@llblab/pi-state-flow/docs/temporal-acceptance.md +42 -0
  46. package/node_modules/@llblab/pi-state-flow/index.ts +164 -2
  47. package/node_modules/@llblab/pi-state-flow/lib/acquisition.ts +138 -0
  48. package/node_modules/@llblab/pi-state-flow/lib/artifact.ts +273 -0
  49. package/node_modules/@llblab/pi-state-flow/lib/config.ts +48 -0
  50. package/node_modules/@llblab/pi-state-flow/lib/context.ts +18 -5
  51. package/node_modules/@llblab/pi-state-flow/lib/continuation.ts +268 -0
  52. package/node_modules/@llblab/pi-state-flow/lib/discovery.ts +117 -0
  53. package/node_modules/@llblab/pi-state-flow/lib/durable.ts +562 -0
  54. package/node_modules/@llblab/pi-state-flow/lib/episode.ts +24 -12
  55. package/node_modules/@llblab/pi-state-flow/lib/extension.ts +606 -70
  56. package/node_modules/@llblab/pi-state-flow/lib/git.ts +666 -0
  57. package/node_modules/@llblab/pi-state-flow/lib/history.ts +95 -0
  58. package/node_modules/@llblab/pi-state-flow/lib/json.ts +24 -0
  59. package/node_modules/@llblab/pi-state-flow/lib/maintenance.ts +141 -0
  60. package/node_modules/@llblab/pi-state-flow/lib/memory.ts +52 -0
  61. package/node_modules/@llblab/pi-state-flow/lib/migration.ts +88 -0
  62. package/node_modules/@llblab/pi-state-flow/lib/publication.ts +296 -0
  63. package/node_modules/@llblab/pi-state-flow/lib/recovery.ts +23 -7
  64. package/node_modules/@llblab/pi-state-flow/lib/rehydration.ts +79 -0
  65. package/node_modules/@llblab/pi-state-flow/lib/runtime.ts +264 -0
  66. package/node_modules/@llblab/pi-state-flow/lib/session.ts +6 -0
  67. package/node_modules/@llblab/pi-state-flow/lib/skills.ts +99 -7
  68. package/node_modules/@llblab/pi-state-flow/lib/snapshot.ts +305 -48
  69. package/node_modules/@llblab/pi-state-flow/lib/state.ts +74 -7
  70. package/node_modules/@llblab/pi-state-flow/lib/status.ts +125 -6
  71. package/node_modules/@llblab/pi-state-flow/lib/storage.ts +196 -0
  72. package/node_modules/@llblab/pi-state-flow/lib/temporal.ts +233 -0
  73. package/node_modules/@llblab/pi-state-flow/lib/terminal.ts +70 -24
  74. package/node_modules/@llblab/pi-state-flow/lib/transition.ts +254 -29
  75. package/node_modules/@llblab/pi-state-flow/package.json +8 -2
  76. package/node_modules/@llblab/pi-state-flow/skills/state-flow-memory/SKILL.md +128 -0
  77. package/node_modules/@llblab/pi-telegram/AGENTS.md +14 -9
  78. package/node_modules/@llblab/pi-telegram/BACKLOG.md +20 -4
  79. package/node_modules/@llblab/pi-telegram/CHANGELOG.md +22 -5
  80. package/node_modules/@llblab/pi-telegram/README.md +13 -9
  81. package/node_modules/@llblab/pi-telegram/docs/README.md +1 -0
  82. package/node_modules/@llblab/pi-telegram/docs/architecture.md +220 -18
  83. package/node_modules/@llblab/pi-telegram/docs/generative-apps.md +1 -1
  84. package/node_modules/@llblab/pi-telegram/docs/multi-instance-bus.md +70 -19
  85. package/node_modules/@llblab/pi-telegram/docs/outbound.md +13 -7
  86. package/node_modules/@llblab/pi-telegram/docs/public-api.md +13 -5
  87. package/node_modules/@llblab/pi-telegram/docs/ui-style.md +3 -1
  88. package/node_modules/@llblab/pi-telegram/index.ts +4 -1415
  89. package/node_modules/@llblab/pi-telegram/lib/activity.ts +19 -5
  90. package/node_modules/@llblab/pi-telegram/lib/agent-messages.ts +6 -3
  91. package/node_modules/@llblab/pi-telegram/lib/bindings.ts +37 -2
  92. package/node_modules/@llblab/pi-telegram/lib/bus-follower.ts +600 -135
  93. package/node_modules/@llblab/pi-telegram/lib/bus-leader.ts +962 -55
  94. package/node_modules/@llblab/pi-telegram/lib/bus.ts +350 -26
  95. package/node_modules/@llblab/pi-telegram/lib/channel-posts.ts +544 -0
  96. package/node_modules/@llblab/pi-telegram/lib/commands.ts +234 -11
  97. package/node_modules/@llblab/pi-telegram/lib/config.ts +178 -25
  98. package/node_modules/@llblab/pi-telegram/lib/delivery.ts +18 -18
  99. package/node_modules/@llblab/pi-telegram/lib/extension.ts +1792 -0
  100. package/node_modules/@llblab/pi-telegram/lib/generative-apps.ts +20 -2
  101. package/node_modules/@llblab/pi-telegram/lib/journal.ts +2184 -126
  102. package/node_modules/@llblab/pi-telegram/lib/lifecycle.ts +7 -1
  103. package/node_modules/@llblab/pi-telegram/lib/locks.ts +38 -1
  104. package/node_modules/@llblab/pi-telegram/lib/menu-settings.ts +154 -15
  105. package/node_modules/@llblab/pi-telegram/lib/outbound-attachments.ts +74 -40
  106. package/node_modules/@llblab/pi-telegram/lib/outbound-voice.ts +28 -42
  107. package/node_modules/@llblab/pi-telegram/lib/outbound.ts +18 -14
  108. package/node_modules/@llblab/pi-telegram/lib/paths.ts +29 -0
  109. package/node_modules/@llblab/pi-telegram/lib/polling.ts +85 -17
  110. package/node_modules/@llblab/pi-telegram/lib/preview.ts +115 -70
  111. package/node_modules/@llblab/pi-telegram/lib/prompts.ts +5 -2
  112. package/node_modules/@llblab/pi-telegram/lib/queue.ts +66 -22
  113. package/node_modules/@llblab/pi-telegram/lib/replies.ts +47 -39
  114. package/node_modules/@llblab/pi-telegram/lib/routing.ts +305 -112
  115. package/node_modules/@llblab/pi-telegram/lib/status.ts +10 -0
  116. package/node_modules/@llblab/pi-telegram/lib/sync.ts +308 -39
  117. package/node_modules/@llblab/pi-telegram/lib/telegram-api.ts +315 -7
  118. package/node_modules/@llblab/pi-telegram/lib/thread-cleanup-manager.ts +664 -0
  119. package/node_modules/@llblab/pi-telegram/lib/thread-display.ts +226 -0
  120. package/node_modules/@llblab/pi-telegram/lib/thread-naming.ts +118 -0
  121. package/node_modules/@llblab/pi-telegram/lib/threads.ts +1686 -129
  122. package/node_modules/@llblab/pi-telegram/lib/updates.ts +1319 -97
  123. package/node_modules/@llblab/pi-telegram/lib/workspace-admission.ts +1643 -0
  124. package/node_modules/@llblab/pi-telegram/lib/workspace-retirement.ts +968 -0
  125. package/node_modules/@llblab/pi-telegram/lib/workspace-slots.ts +84 -0
  126. package/node_modules/@llblab/pi-telegram/package.json +1 -1
  127. package/node_modules/@llblab/pi-telegram/screenshot.png +0 -0
  128. package/node_modules/@llblab/pi-telegram/scripts/measure-bus.mjs +83 -0
  129. package/node_modules/@llblab/pi-telegram/scripts/measure-workspace.mjs +101 -0
  130. package/node_modules/@llblab/{skills → pi-telegram/skills}/show-me/SKILL.md +28 -6
  131. package/node_modules/@llblab/pi-telegram/skills/show-me/references/telegram-surfaces.md +43 -0
  132. package/node_modules/@llblab/pi-telegram/skills/telegram-bridge/references/delivery-and-threads.md +1 -1
  133. package/node_modules/@llblab/skills/abcd-context/AGENTS.md +1 -0
  134. package/node_modules/@llblab/skills/abcd-context/CHANGELOG.md +6 -2
  135. package/node_modules/@llblab/skills/abcd-context/SKILL.md +1 -1
  136. package/node_modules/@llblab/skills/abcd-context/docs/validation-design.md +11 -5
  137. package/node_modules/@llblab/skills/abcd-context/scripts/_self-test.mjs +61 -0
  138. package/node_modules/@llblab/skills/abcd-context/scripts/validate-context.mjs +67 -0
  139. package/node_modules/@llblab/skills/package.json +2 -3
  140. package/node_modules/@llblab/skills/release-flow/SKILL.md +2 -4
  141. package/package.json +7 -6
@@ -1,1418 +1,7 @@
1
1
  /**
2
- * Telegram bridge extension entrypoint and orchestration layer
3
- * Zones: telegram, pi agent, orchestration
4
- * Keeps the runtime wiring in one place while delegating reusable domain logic to /lib modules
2
+ * Telegram package entrypoint
3
+ * Zones: telegram, pi agent, public API
4
+ * Re-exports the extension composition root without owning runtime wiring.
5
5
  */
6
6
 
7
- import * as AgentMessages from "./lib/agent-messages.ts";
8
- import * as Bindings from "./lib/bindings.ts";
9
- import * as BusApi from "./lib/bus-api.ts";
10
- import * as BusFollower from "./lib/bus-follower.ts";
11
- import * as BusLeader from "./lib/bus-leader.ts";
12
- import * as BusTransport from "./lib/bus-transport.ts";
13
- import * as Bus from "./lib/bus.ts";
14
- import * as CommandTemplates from "./lib/command-templates.ts";
15
- import * as Commands from "./lib/commands.ts";
16
- import * as Config from "./lib/config.ts";
17
- import * as Delivery from "./lib/delivery.ts";
18
- import * as Inbound from "./lib/inbound.ts";
19
- import * as Journal from "./lib/journal.ts";
20
- import * as Lifecycle from "./lib/lifecycle.ts";
21
- import * as Locks from "./lib/locks.ts";
22
- import * as Logs from "./lib/logs.ts";
23
- import * as Media from "./lib/media.ts";
24
- import * as MenuQueue from "./lib/menu-queue.ts";
25
- import * as MenuSettings from "./lib/menu-settings.ts";
26
- import * as Menu from "./lib/menu.ts";
27
- import * as Model from "./lib/model.ts";
28
- import * as Outbound from "./lib/outbound.ts";
29
- import * as Ownership from "./lib/ownership.ts";
30
- import * as Paths from "./lib/paths.ts";
31
- import * as Pi from "./lib/pi.ts";
32
- import * as Polling from "./lib/polling.ts";
33
- import * as Preview from "./lib/preview.ts";
34
- import * as PromptTemplates from "./lib/prompt-templates.ts";
35
- import * as Prompts from "./lib/prompts.ts";
36
- import * as Queue from "./lib/queue.ts";
37
- import * as Recovery from "./lib/recovery.ts";
38
- import * as Replies from "./lib/replies.ts";
39
- import * as Routing from "./lib/routing.ts";
40
- import * as Runtime from "./lib/runtime.ts";
41
- import * as Sections from "./lib/sections.ts";
42
- import * as Skills from "./lib/skills.ts";
43
- import * as Status from "./lib/status.ts";
44
- import * as Sync from "./lib/sync.ts";
45
- import * as TelegramApi from "./lib/telegram-api.ts";
46
- import * as TextGroups from "./lib/text-groups.ts";
47
- import * as ThreadReconciler from "./lib/thread-reconciler.ts";
48
- import * as Threads from "./lib/threads.ts";
49
- import * as TimeInjection from "./lib/time-injection.ts";
50
- import * as Updates from "./lib/updates.ts";
51
- import * as Voice from "./lib/voice.ts";
52
-
53
- type ActivePiModel = NonNullable<Pi.ExtensionContext["model"]>;
54
-
55
- const telegramBusProtocolIdentity =
56
- Bus.createTelegramCurrentBusProtocolIdentity([
57
- Bus.TELEGRAM_BUS_CAPABILITY_DURABLE_FOLLOWER_ADMISSION,
58
- Bus.TELEGRAM_BUS_CAPABILITY_QUEUE_HANDOFF,
59
- ]);
60
-
61
- // --- Extension Runtime ---
62
-
63
- export default function (pi: Pi.ExtensionAPI) {
64
- Skills.registerTelegramSkillDiscovery(pi);
65
- const piRuntime = Pi.createExtensionApiRuntimePorts(pi);
66
- const {
67
- getActiveTools,
68
- getCommands,
69
- getThinkingLevel,
70
- sendUserMessage,
71
- setActiveTools,
72
- setModel,
73
- setThinkingLevel,
74
- } = piRuntime;
75
- const bridgeRuntime = Runtime.createTelegramBridgeRuntime();
76
- const runtimeDiagnostics =
77
- Logs.createTelegramRuntimeDiagnosticsRuntime<Pi.ExtensionContext>();
78
- const runtimeEvents = runtimeDiagnostics.events;
79
- const recordRuntimeEvent = runtimeDiagnostics.recordRuntimeEvent;
80
- const configStore = Config.createTelegramConfigStore({ recordRuntimeEvent });
81
- const busProcessRuntime = Bus.createCurrentTelegramBusProcessRuntime({
82
- getActiveProfileName: configStore.getActiveProfileName,
83
- });
84
- const {
85
- instanceId: telegramInstanceId,
86
- processId: telegramProcessId,
87
- processBirthId: telegramQueueProcessBirthId,
88
- manualFollowerOwnerId: telegramManualFollowerOwnerId,
89
- getLeaderSocketPath: getTelegramBusSocketPath,
90
- getFollowerSocketPath: getTelegramBusFollowerSocketPath,
91
- } = busProcessRuntime;
92
- const getTelegramBotId = Config.createTelegramConfigBotIdGetter(configStore);
93
- const getTelegramActiveProfileKey =
94
- Config.createTelegramActiveProfileKeyGetter(configStore);
95
- const getTelegramManualFollowerProfileKey =
96
- BusFollower.createTelegramManualFollowerProfileKeyResolver({
97
- getActiveProfileName: configStore.getActiveProfileName,
98
- manualFollowerOwnerId: telegramManualFollowerOwnerId,
99
- });
100
- const telegramBusAuthSecret = Bus.createTelegramBusAuthSecret();
101
- const telegramBusFollowerControlState =
102
- BusFollower.createTelegramBusFollowerControlState();
103
- const telegramBusFollowerRegistry = Bus.createTelegramBusFollowerRegistry();
104
- const modelContextAvailabilityBinding =
105
- Prompts.createTelegramModelContextAvailabilityBinding();
106
- const telegramBusFollowerRegistrationState =
107
- BusFollower.createTelegramBusFollowerRegistrationState({
108
- onAvailabilityChanged: modelContextAvailabilityBinding.reconcile,
109
- });
110
- const telegramBusLeaderState =
111
- Threads.createTelegramLeaderThreadStateRuntime();
112
- const telegramThreadCapabilityState =
113
- Polling.createTelegramThreadCapabilityStateRuntime();
114
- const telegramProvisioningActivity =
115
- Sync.createTelegramProvisioningActivityRuntime();
116
- const messageOwnershipRuntime =
117
- Ownership.createTelegramBusMessageOwnershipRuntime({
118
- instanceId: telegramInstanceId,
119
- getProfileKey: getTelegramActiveProfileKey,
120
- listFollowers: telegramBusFollowerRegistry.list,
121
- });
122
- const { abort, lifecycle, queue, setup, typing } = bridgeRuntime;
123
- const getTelegramUpdateAdmissionScope =
124
- Journal.createTelegramUpdateJournalReceiptScopeResolver({
125
- getProfileName: configStore.getActiveProfileName,
126
- getBotToken: configStore.getBotToken,
127
- getBotId: getTelegramBotId,
128
- });
129
- const telegramJournalBindingRuntime =
130
- Journal.createTelegramUpdateJournalBindingRuntime({
131
- base: {
132
- getProfileName: configStore.getActiveProfileName,
133
- getBotToken: configStore.getBotToken,
134
- getBotId: getTelegramBotId,
135
- onRecovery(event) {
136
- recordRuntimeEvent(
137
- "recovery",
138
- event.kind === "repaired"
139
- ? "Telegram update journal was repaired automatically."
140
- : "Telegram update journal was reset after its damaged files were quarantined.",
141
- {
142
- phase: "journal-auto-recovery",
143
- recoveryKind: event.kind,
144
- journalPath: event.path,
145
- revision: event.revision,
146
- quarantinePath: event.quarantinePath,
147
- reason: event.reason,
148
- },
149
- );
150
- },
151
- getQueueRuntimeIdentity() {
152
- return {
153
- instanceId: telegramInstanceId,
154
- processId: telegramProcessId,
155
- processBirthId: telegramQueueProcessBirthId,
156
- };
157
- },
158
- },
159
- getLeaderJournalPath: Paths.resolveTelegramUpdateJournalPath,
160
- getFollowerJournalPath(bindingKey, profileName) {
161
- return Paths.resolveTelegramFollowerJournalPath(
162
- bindingKey,
163
- undefined,
164
- profileName,
165
- );
166
- },
167
- getActiveFollowerBindingKey: getTelegramManualFollowerProfileKey,
168
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
169
- });
170
- const resolveTelegramUpdateJournalBinding =
171
- telegramJournalBindingRuntime.resolveLeader;
172
- const resolveTelegramFollowerJournalBinding =
173
- telegramJournalBindingRuntime.resolveFollower;
174
- const getTelegramQueueJournalBinding =
175
- telegramJournalBindingRuntime.getActiveRecoveryKey;
176
- const isTelegramBusRuntimeEnabled =
177
- telegramThreadCapabilityState.isBusRuntimeEnabled;
178
- Config.bindGlobalTelegramConfigRuntime(configStore);
179
- const configControls = Config.createTelegramConfigControls(configStore);
180
- const lockRuntime = Locks.createTelegramLockRuntime<Pi.ExtensionContext>({
181
- key: Locks.createTelegramLockKeyResolver(configStore),
182
- instanceId: telegramInstanceId,
183
- busSecret: telegramBusAuthSecret,
184
- staleHeartbeatMs: Locks.TELEGRAM_BUS_LEADER_STALE_HEARTBEAT_MS,
185
- });
186
- const threadStore = Threads.createTelegramTopicTargetStore({
187
- path: function () {
188
- return Threads.getTelegramTopicTargetsPath(
189
- undefined,
190
- configStore.getActiveProfileName(),
191
- );
192
- },
193
- canPersist: lockRuntime.owns,
194
- commitPersist: lockRuntime.commitIfOwned,
195
- });
196
- runtimeDiagnostics.bindStorage({
197
- getBotToken: configStore.getBotToken,
198
- getProfileName: configStore.getActiveProfileName,
199
- canReset: lockRuntime.owns,
200
- commitReset: lockRuntime.commitIfOwned,
201
- });
202
- const lockOwnershipGuard =
203
- Locks.createTelegramLockOwnershipGuard(lockRuntime);
204
- const getCurrentLeaderEpoch = lockRuntime.getOwnedLeaderEpoch;
205
- const telegramSessionContextStore =
206
- Lifecycle.createTelegramSessionContextStore<Pi.ExtensionContext>({
207
- getIdentity(ctx) {
208
- return ctx.sessionManager ?? ctx.cwd;
209
- },
210
- });
211
- const ownsTelegramDirectDelivery =
212
- Locks.createTelegramDirectDeliveryOwnershipChecker({
213
- lock: lockRuntime,
214
- contextStore: telegramSessionContextStore,
215
- });
216
- const modelContextAvailabilityRuntime =
217
- Prompts.createTelegramModelContextAvailabilityRuntime({
218
- getActiveTools,
219
- setActiveTools,
220
- isAvailable() {
221
- return (
222
- ownsTelegramDirectDelivery() ||
223
- telegramBusFollowerRegistrationState.isRegistered()
224
- );
225
- },
226
- canReconcile() {
227
- const ctx = telegramSessionContextStore.get();
228
- return !ctx || Pi.isExtensionContextIdle(ctx);
229
- },
230
- });
231
- modelContextAvailabilityBinding.bind(modelContextAvailabilityRuntime);
232
- const activeTurnRuntime = Queue.createTelegramActiveTurnStore();
233
- const proactivePushTargetGetter =
234
- Config.createTelegramProactivePushTargetGetter({
235
- getActiveTurnTarget: activeTurnRuntime.getTarget,
236
- getAssignedTarget() {
237
- return (
238
- telegramBusFollowerRegistrationState.getTarget() ??
239
- telegramBusLeaderState.getTarget()
240
- );
241
- },
242
- getAllowedUserId: configStore.getAllowedUserId,
243
- });
244
- const proactivePushChatIdGetter =
245
- Config.createTelegramProactivePushChatIdGetter(proactivePushTargetGetter);
246
- const buttonActionStore = Outbound.createTelegramButtonActionStore();
247
- const planGenerativeAppOutput =
248
- Outbound.createTelegramOutboundReplyPlanner(
249
- buttonActionStore,
250
- configControls.getAssistantRenderingMode,
251
- );
252
- const pendingModelSwitchStore =
253
- Model.createPendingModelSwitchStore<
254
- Model.ScopedTelegramModel<ActivePiModel>
255
- >();
256
- const modelMenuRuntime = Menu.createTelegramModelMenuRuntime<ActivePiModel>();
257
- const sectionRegistry = Sections.createAndBindTelegramSectionRegistry();
258
-
259
- const timeInjectionRuntime = TimeInjection.createTimeInjectionRuntime({
260
- getConfig: Config.createTelegramTimeConfigGetter(configStore),
261
- recordRuntimeEvent,
262
- });
263
- Outbound.bindTelegramRuntimeEventRecorder(recordRuntimeEvent);
264
- const getContextModel = Pi.getExtensionContextModel;
265
- const isIdle = Pi.isExtensionContextIdle;
266
- const hasPendingMessages = Pi.hasExtensionContextPendingMessages;
267
- const compact = Pi.compactExtensionContext;
268
- const mediaGroupRuntime = Media.createTelegramMediaGroupController<
269
- TelegramApi.TelegramMessage,
270
- Pi.ExtensionContext
271
- >();
272
- const textGroupRuntime = TextGroups.createTelegramTextGroupController<
273
- TelegramApi.TelegramMessage,
274
- Pi.ExtensionContext
275
- >();
276
- const rawTelegramQueueStore =
277
- Queue.createTelegramQueueStore<Pi.ExtensionContext>();
278
- const telegramTransportStampRuntime =
279
- Queue.createTelegramTransportStampRuntime({
280
- getProfileName: configStore.getActiveProfileName,
281
- getBotToken: configStore.getBotToken,
282
- });
283
- const telegramQueueStore = Queue.createTelegramTransportStampedQueueStore(
284
- rawTelegramQueueStore,
285
- telegramTransportStampRuntime.getStamp,
286
- );
287
- const updateAdmissionRuntimeBinding =
288
- Updates.createTelegramUpdateAdmissionRuntimeBinding<Pi.ExtensionContext>({
289
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
290
- });
291
- const deferredQueueDispatchRuntime =
292
- Queue.createTelegramDeferredQueueDispatchRuntime<Pi.ExtensionContext>({
293
- recordRuntimeEvent,
294
- });
295
- const pollingControllerState = Polling.createTelegramPollingControllerState();
296
- const telegramSyncStateRuntime = Sync.createTelegramSyncStateRuntime();
297
- const threadReconciliationRuntime =
298
- ThreadReconciler.createThreadReconciliationRuntime({
299
- recordRuntimeEvent,
300
- scheduleSnapshotPersist: runtimeDiagnostics.scheduleSnapshotPersist,
301
- });
302
- const recordThreadReconciliationPlan = threadReconciliationRuntime.recordPlan;
303
- const persistTelegramConfigWithSync =
304
- Sync.createTelegramConfigSyncPersister<Config.TelegramConfig>({
305
- persist: configStore.persist,
306
- markConfigChange: telegramSyncStateRuntime.markConfigChange,
307
- });
308
- const {
309
- current: currentInstanceThreadRuntime,
310
- status: threadStatusProjectionRuntime,
311
- } = Threads.createTelegramCurrentThreadAssembly({
312
- instanceId: telegramInstanceId,
313
- listRecords: threadStore.list,
314
- getActiveTurnTarget: activeTurnRuntime.getTarget,
315
- getFollowerTarget: telegramBusFollowerRegistrationState.getTarget,
316
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
317
- getFollowerSlot: telegramBusFollowerRegistrationState.getSlot,
318
- getFollowerThreadName: telegramBusFollowerRegistrationState.getThreadName,
319
- getLeaderIdentity: telegramBusLeaderState.getIdentity,
320
- getLeaderTarget: telegramBusLeaderState.getTarget,
321
- getLeaderProtocol: telegramBusFollowerRegistrationState.getLeaderProtocol,
322
- status: {
323
- getThreadMode: function () {
324
- return threadStore.getBotState().threadMode;
325
- },
326
- isBusPollingStarted: telegramThreadCapabilityState.isBusPollingStarted,
327
- listFollowers: telegramBusFollowerRegistry.list,
328
- listReservations: threadStore.listReservations,
329
- listSyncObservations: threadStore.listSyncObservations,
330
- getLeaderSocketPath: getTelegramBusSocketPath,
331
- getFollowerSocketPath: getTelegramBusFollowerSocketPath,
332
- getTransportKind: BusTransport.getTelegramBusTransportKind,
333
- },
334
- });
335
- const findCurrentThreadRecord = currentInstanceThreadRuntime.findRecord;
336
- const getCurrentInstanceThreadIdentity =
337
- currentInstanceThreadRuntime.getIdentity;
338
- const statusRuntime = Status.createTelegramBridgeStatusRuntime<
339
- Pi.ExtensionContext,
340
- Queue.TelegramQueueItem<Pi.ExtensionContext>
341
- >({
342
- getConfig: configStore.get,
343
- getActiveProfileName: configStore.getActiveProfileName,
344
- getDiagnosticPaths: Paths.getTelegramDiagnosticsDisplayPaths,
345
- isPollingActive: Polling.createTelegramPollingActivityReader(
346
- pollingControllerState,
347
- ),
348
- getPollingState: Polling.createTelegramPollingStateReader(
349
- pollingControllerState,
350
- ),
351
- getInboundWorkerState() {
352
- return updateAdmissionRuntimeBinding.getActive()?.getState();
353
- },
354
- getAcceptedThroughUpdateId() {
355
- return resolveTelegramUpdateJournalBinding()?.journal.read()
356
- .acceptedThroughUpdateId;
357
- },
358
- getActiveSourceMessageIds: activeTurnRuntime.getSourceMessageIds,
359
- hasActiveTurn: activeTurnRuntime.has,
360
- hasDispatchPending: lifecycle.hasDispatchPending,
361
- isCompactionInProgress: lifecycle.isCompactionInProgress,
362
- getActiveToolExecutions: lifecycle.getActiveToolExecutions,
363
- hasPendingModelSwitch: pendingModelSwitchStore.has,
364
- getQueuedItems: telegramQueueStore.getQueuedItems,
365
- getQueuedItemCount: Queue.countExecutableTelegramQueueItems,
366
- formatQueuedStatus: Queue.formatQueuedTelegramItemsStatus,
367
- getRecentRuntimeEvents: runtimeEvents.getEvents,
368
- getRuntimeLockState: lockRuntime.getStatusLabel,
369
- ...threadStatusProjectionRuntime,
370
- getBusProtocol() {
371
- return telegramBusProtocolIdentity;
372
- },
373
- getBusLifecyclePhase: telegramBusFollowerControlState.getLifecyclePhase,
374
- getBotThreadMode() {
375
- return threadStore.getBotState();
376
- },
377
- getSyncState: telegramSyncStateRuntime.getState,
378
- getThreadReconciliationState() {
379
- return threadReconciliationRuntime.getState();
380
- },
381
- });
382
- runtimeDiagnostics.bindStatus({
383
- instanceId: telegramInstanceId,
384
- updateStatus: statusRuntime.updateStatus,
385
- getStatusState: statusRuntime.getStatusState,
386
- async persistSnapshot(snapshot) {
387
- threadStore.setStatusSnapshot(snapshot);
388
- await threadStore.persist();
389
- },
390
- });
391
- const updateStatus = runtimeDiagnostics.updateStatus;
392
- const getStatusLines = runtimeDiagnostics.getStatusLines;
393
- const inboundHandlerRuntime = Inbound.createTelegramInboundHandlerRuntime({
394
- getHandlers: configStore.getInboundHandlers,
395
- execCommand: CommandTemplates.execCommandTemplate,
396
- getCwd: Pi.getExtensionContextCwd,
397
- recordRuntimeEvent,
398
- });
399
-
400
- // --- Telegram API ---
401
-
402
- const directTelegramApiRuntime =
403
- TelegramApi.createDefaultTelegramBridgeApiRuntime({
404
- getBotToken: configStore.getBotToken,
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
- },
415
- });
416
- const telegramBusFollowerClients =
417
- BusFollower.createTelegramBusFollowerClientRuntime<
418
- Pi.ExtensionContext,
419
- Updates.TelegramMessageReactionUpdated,
420
- Routing.TelegramRoutedCallbackQuery,
421
- Routing.TelegramRoutedMessage
422
- >({
423
- socketPath: getTelegramBusSocketPath,
424
- instanceId: telegramInstanceId,
425
- getApiAuthSecret: telegramBusFollowerControlState.getActiveAuthSecret,
426
- getForwardingAuthSecret() {
427
- return telegramBusAuthSecret;
428
- },
429
- getRegistrationGeneration:
430
- telegramBusFollowerRegistrationState.getGeneration,
431
- waitForRegistrationGeneration:
432
- telegramBusFollowerRegistrationState.waitForGeneration,
433
- getForwardCommentBatchPosition:
434
- textGroupRuntime.getPreparedForwardingPosition,
435
- recordRuntimeEvent,
436
- });
437
- const telegramApiRuntime = BusApi.createTelegramBusAwareApiRuntime({
438
- directRuntime: directTelegramApiRuntime,
439
- ownsDirect() {
440
- return lockRuntime.owns();
441
- },
442
- getDefaultTarget: proactivePushTargetGetter,
443
- callFollowerApi: telegramBusFollowerClients.callApi,
444
- });
445
- const {
446
- call: callTelegramApi,
447
- callMultipart,
448
- deleteWebhook,
449
- getUpdates,
450
- setMyCommands,
451
- sendTypingAction,
452
- sendChatAction,
453
- sendRecordVoiceAction,
454
- sendMessageDraft,
455
- sendMessage,
456
- sendRichMessage,
457
- sendRichMessageDraft,
458
- downloadFile: downloadTelegramBridgeFile,
459
- editMessageText: editTelegramMessageText,
460
- editMessageReplyMarkup: editTelegramMessageReplyMarkup,
461
- answerCallbackQuery,
462
- answerGuestQuery,
463
- deleteMessage: deleteTelegramMessage,
464
- prepareTempDir,
465
- } = telegramApiRuntime;
466
-
467
- // --- Message Delivery ---
468
-
469
- const sendGuestReply = Replies.createGuestMarkdownReplySender({
470
- answerGuestQuery,
471
- });
472
-
473
- const promptDispatchRuntime = Runtime.createTelegramPromptDispatchRuntime({
474
- lifecycle,
475
- typing,
476
- getDefaultChatId: proactivePushChatIdGetter,
477
- sendTypingAction,
478
- sendAggregateTypingAction:
479
- BusApi.createTelegramAggregateTypingActionSender(telegramApiRuntime),
480
- updateStatus,
481
- isContextActive: telegramSessionContextStore.isCurrent,
482
- getTransportAuthority() {
483
- if (ownsTelegramDirectDelivery()) {
484
- const epoch = getCurrentLeaderEpoch();
485
- return epoch === undefined ? undefined : `direct:${epoch}`;
486
- }
487
- if (!telegramBusFollowerRegistrationState.isRegistered()) return undefined;
488
- const generation = telegramBusFollowerRegistrationState.getGeneration();
489
- return generation ? `follower:${generation}` : undefined;
490
- },
491
- recordRuntimeEvent,
492
- });
493
- const currentModelRuntime = Model.createCurrentModelRuntime({
494
- getContextModel,
495
- updateStatus,
496
- });
497
-
498
- // --- Reply Runtime & Preview ---
499
-
500
- const replyRuntime = Replies.createTelegramRenderedMessageDeliveryRuntime({
501
- recordOwnership: messageOwnershipRuntime.recordLocal,
502
- sendMessage,
503
- sendRichMessage,
504
- getAssistantRenderingMode: configControls.getAssistantRenderingMode,
505
- editMessage: editTelegramMessageText,
506
- });
507
- const { replyTransport, editInteractiveMessage, sendInteractiveMessage } =
508
- replyRuntime;
509
- const deliveryTargetPolicyRuntime =
510
- Delivery.createTelegramDeliveryTargetPolicyRuntime({
511
- ownsDirect: lockRuntime.owns,
512
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
513
- getAllowedChatId: configStore.getAllowedUserId,
514
- getFollowerTarget: telegramBusFollowerRegistrationState.getTarget,
515
- getLeaderTarget: telegramBusLeaderState.getTarget,
516
- listThreadRecords: threadStore.list,
517
- getActiveTurnTarget: activeTurnRuntime.getTarget,
518
- getActiveGuestQueryId: activeTurnRuntime.getGuestQueryId,
519
- });
520
- const deliveryGenerationSeed =
521
- Delivery.createTelegramDeliveryGenerationSeed(telegramInstanceId);
522
- const deliveryLifecycleRuntime =
523
- Delivery.createTelegramBridgeDeliveryLifecycleHooks({
524
- generationSeed: deliveryGenerationSeed,
525
- getTargetPolicyView: deliveryTargetPolicyRuntime.getTargetPolicyView,
526
- getTransportStamp: telegramTransportStampRuntime.getStamp,
527
- isTransportStampActive: telegramTransportStampRuntime.isActive,
528
- getActiveTurnTarget: deliveryTargetPolicyRuntime.getActiveTurnTarget,
529
- api: telegramApiRuntime,
530
- recordOwnership: messageOwnershipRuntime.recordLocal,
531
- recordFailure(operation, error, target) {
532
- recordRuntimeEvent("delivery", error, {
533
- operation,
534
- scope: target?.threadId === undefined ? "aggregate" : "thread",
535
- });
536
- },
537
- });
538
- const { sendTextReply, sendMarkdownReply } =
539
- Outbound.createTelegramOutboundTextReplyRuntime({
540
- sendTextReply: replyRuntime.sendTextReply,
541
- sendMarkdownReply: replyRuntime.sendMarkdownReply,
542
- execCommand: CommandTemplates.execCommandTemplate,
543
- getHandlers: configStore.getOutboundHandlers,
544
- recordRuntimeEvent,
545
- });
546
- const invokeGenerativeAppBoundButtonAction =
547
- Bindings.createTelegramGenerativeAppBoundButtonActionInvoker({
548
- agentDir: Paths.resolveAgentDir(),
549
- assertExecutionCurrent: Updates.assertTelegramUpdateExecutionCurrent,
550
- getExecutionFence: Updates.getTelegramUpdateExecutionFence,
551
- planOutput: planGenerativeAppOutput,
552
- sendMarkdownReply,
553
- editInteractiveMessage,
554
- recordRuntimeEvent,
555
- });
556
- const {
557
- activityRuntime,
558
- activityVerbosityRuntime,
559
- assistantOutputRuntime,
560
- publicationRuntime,
561
- } = Bindings.createTelegramActivityBindingRuntime({
562
- generation: deliveryGenerationSeed,
563
- assistantOutput: {
564
- authority: {
565
- getPreferredTarget: proactivePushTargetGetter,
566
- getFallbackChatId: proactivePushChatIdGetter,
567
- getTransportStamp: telegramTransportStampRuntime.getStamp,
568
- isTransportStampActive: telegramTransportStampRuntime.isActive,
569
- ownsDirect: lockRuntime.owns,
570
- getDirectEpoch: lockRuntime.getOwnedLeaderEpoch,
571
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
572
- getFollowerGeneration:
573
- telegramBusFollowerRegistrationState.getGeneration,
574
- },
575
- sender: {
576
- recordOwnership: messageOwnershipRuntime.recordLocal,
577
- sendMessage,
578
- sendRichMessage,
579
- editMessage: editTelegramMessageText,
580
- getAssistantRenderingMode: configControls.getAssistantRenderingMode,
581
- planButtonReply:
582
- Outbound.createTelegramButtonReplyPlanner(buttonActionStore),
583
- execCommand: CommandTemplates.execCommandTemplate,
584
- getHandlers: configStore.getOutboundHandlers,
585
- recordRuntimeEvent,
586
- },
587
- recordRuntimeEvent,
588
- },
589
- activityVerbosity: {
590
- getActivityMode: configControls.getActivityVerbosity,
591
- refreshActivityMode: configControls.refreshActivityVerbosity,
592
- resolveTarget(event) {
593
- return event.target ?? proactivePushTargetGetter();
594
- },
595
- sendMessage,
596
- sendRichMessage,
597
- editMessageText: editTelegramMessageText,
598
- },
599
- });
600
- const {
601
- mutation: queueMutationRuntime,
602
- dispatchNext: dispatchNextQueuedTelegramTurn,
603
- watchdog: queueDispatchWatchdogRuntime,
604
- } = Bindings.createTelegramQueueBindingRuntime({
605
- store: telegramQueueStore,
606
- queue,
607
- lifecycle,
608
- activeTurn: activeTurnRuntime,
609
- admission: updateAdmissionRuntimeBinding,
610
- transportStamp: telegramTransportStampRuntime,
611
- deferredDispatch: deferredQueueDispatchRuntime,
612
- promptDispatch: promptDispatchRuntime,
613
- isIdle,
614
- hasPendingMessages,
615
- updateStatus,
616
- sendTextReply,
617
- sendUserMessage,
618
- recordRuntimeEvent,
619
- });
620
- const nativeMarkdownDraftSender =
621
- TelegramApi.createTelegramAssistantDraftSender({
622
- getAssistantRenderingMode: configControls.getAssistantRenderingMode,
623
- renderMarkdownToHtmlDraft: Replies.renderTelegramMarkdownToHtmlDraft,
624
- sendMessageDraft,
625
- sendRichMessageDraft,
626
- });
627
- const previewRuntime = Preview.createTelegramAssistantPreviewRuntime({
628
- getActiveTurn: activeTurnRuntime.get,
629
- isAssistantMessage: Replies.isAssistantAgentMessage,
630
- getMessageText: Replies.getAgentMessageText,
631
- getDefaultReplyToMessageId: activeTurnRuntime.getReplyToMessageId,
632
- sendDraft: nativeMarkdownDraftSender,
633
- canSend: configControls.areDraftPreviewsEnabled,
634
- sendMarkdownReply,
635
- recordRuntimeEvent,
636
- ...replyTransport,
637
- });
638
- const { finalizeMarkdownPreview } =
639
- Outbound.createTelegramOutboundTextPreviewRuntime({
640
- finalizeMarkdownPreview: previewRuntime.finalizeMarkdown,
641
- execCommand: CommandTemplates.execCommandTemplate,
642
- getHandlers: configStore.getOutboundHandlers,
643
- recordRuntimeEvent,
644
- });
645
-
646
- // --- Model And Menu Setup ---
647
-
648
- const modelSwitchController =
649
- Model.createTelegramModelSwitchControllerRuntime({
650
- isIdle,
651
- getPendingModelSwitch: pendingModelSwitchStore.get,
652
- setPendingModelSwitch: pendingModelSwitchStore.set,
653
- getActiveTurn: activeTurnRuntime.get,
654
- getAbortHandler: abort.getHandler,
655
- hasAbortHandler: abort.hasHandler,
656
- getActiveToolExecutions: lifecycle.getActiveToolExecutions,
657
- allocateItemOrder: queue.allocateItemOrder,
658
- allocateControlOrder: queue.allocateControlOrder,
659
- appendQueuedItem: queueMutationRuntime.append,
660
- updateStatus,
661
- });
662
- const getQueueItemCount =
663
- Queue.createTelegramQueueItemCountGetter(telegramQueueStore);
664
- const getPromptTemplateCommands =
665
- PromptTemplates.createTelegramPromptTemplateCommandGetter({
666
- getCommands,
667
- getReservedCommandNames: Commands.getTelegramReservedCommandNames,
668
- });
669
- const menuActions = Menu.createTelegramMenuActionRuntimeWithStateBuilder({
670
- runtime: modelMenuRuntime,
671
- createSettingsManager: Pi.createSettingsManager,
672
- getActiveModel: currentModelRuntime.get,
673
- getThinkingLevel,
674
- getQueueItemCount,
675
- buildStatusHtml: Commands.createTelegramAppMenuHtmlBuilder({
676
- buildStatusHtml: Status.createTelegramStatusHtmlBuilder({
677
- getActiveModel: currentModelRuntime.get,
678
- isCompactionInProgress: lifecycle.isCompactionInProgress,
679
- getBridgeStatusLineState: statusRuntime.getStatusState,
680
- }),
681
- getPromptTemplateCommands,
682
- }),
683
- storeModelMenuState: modelMenuRuntime.storeState,
684
- isIdle,
685
- canOfferInFlightModelSwitch: modelSwitchController.canOfferInFlightSwitch,
686
- sendTextReply,
687
- editInteractiveMessage,
688
- sendInteractiveMessage,
689
- sectionRegistry,
690
-
691
- // Menu/status UI uses this to reflect whether the active Telegram turn expects voice delivery.
692
- isVoiceReplyActive: function () {
693
- const turn = activeTurnRuntime.get();
694
- return Voice.isVoiceTurn(turn);
695
- },
696
- });
697
-
698
- // --- Queue And Settings Menus ---
699
-
700
- const getQueueMenuState = Menu.createTelegramModelMenuStateBuilder({
701
- runtime: modelMenuRuntime,
702
- createSettingsManager: Pi.createSettingsManager,
703
- getActiveModel: currentModelRuntime.get,
704
- });
705
- const queueMenuRuntime = MenuQueue.createTelegramQueueMenuRuntime({
706
- telegramQueueStore,
707
- queueMutationRuntime,
708
- sendInteractiveMessage,
709
- editInteractiveMessage,
710
- answerCallbackQuery,
711
- getModelMenuState: getQueueMenuState,
712
- getStoredModelMenuState: modelMenuRuntime.getState,
713
- storeModelMenuState: modelMenuRuntime.storeState,
714
- updateStatusMessage: menuActions.updateStatusMessage,
715
- updateStatus,
716
- });
717
- const settingsMenuRuntime = MenuSettings.createTelegramSettingsMenuRuntime(
718
- {
719
- reloadConfig: configStore.load,
720
- getModelMenuState: getQueueMenuState,
721
- getStoredModelMenuState: modelMenuRuntime.getState,
722
- storeModelMenuState: modelMenuRuntime.storeState,
723
- editInteractiveMessage,
724
- sendInteractiveMessage,
725
- answerCallbackQuery,
726
- ...configControls,
727
- },
728
- sectionRegistry,
729
- );
730
-
731
- // --- Polling ---
732
-
733
- const foreignOwnedUpdateForwarder =
734
- telegramBusFollowerClients.foreignOwnedUpdateForwarder;
735
- const followerTargetController = telegramBusFollowerClients.targetController;
736
- const restoreFollowerThreadTarget =
737
- Bus.createTelegramBusFollowerThreadRestoreHandler({
738
- followerRegistry: telegramBusFollowerRegistry,
739
- followerTargetController,
740
- onRestored() {
741
- telegramSyncStateRuntime.markSliceFresh(
742
- Sync.TELEGRAM_SYNC_SLICE_TARGET_BINDINGS,
743
- {
744
- nowMs: Date.now(),
745
- action: "follower-thread-restore",
746
- },
747
- );
748
- },
749
- });
750
- const observedThreadTargetBinding =
751
- Polling.createTelegramThreadTargetObservationBinding<Pi.ExtensionContext>();
752
- const topicLifecycleSync =
753
- Sync.createTelegramObservedTopicLifecycleSyncHandler({
754
- topicTargetStore: threadStore,
755
- isBusEnabled: isTelegramBusRuntimeEnabled,
756
- callApi: callTelegramApi,
757
- isTopicProvisioningActive: telegramProvisioningActivity.isActive,
758
- getCurrentLeaderEpoch,
759
- getThreadReconciliationMachineState: threadReconciliationRuntime.getState,
760
- recordThreadReconciliationPlan,
761
- assertExecutionCurrent(message) {
762
- Updates.assertTelegramUpdateExecutionCurrent(message);
763
- },
764
- getSyncState: telegramSyncStateRuntime.getState,
765
- setSyncState: telegramSyncStateRuntime.setState,
766
- recordEvent: recordRuntimeEvent,
767
- });
768
- const inboundBusProjectionRuntime =
769
- Routing.createTelegramInboundBusProjectionRuntime({
770
- instanceId: telegramInstanceId,
771
- listFollowers: telegramBusFollowerRegistry.list,
772
- listThreadRecords: threadStore.list,
773
- getLeaderTarget: telegramBusLeaderState.getTarget,
774
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
775
- getFollowerTarget: telegramBusFollowerRegistrationState.getTarget,
776
- getCurrentIdentity: getCurrentInstanceThreadIdentity,
777
- });
778
- const inboundRouteRuntime = Routing.createTelegramInboundRouteRuntime({
779
- configStore,
780
- callApi: callTelegramApi,
781
- getCurrentInstanceId() {
782
- return telegramInstanceId;
783
- },
784
- getAdmissionScope: getTelegramUpdateAdmissionScope,
785
- getAdmissionJournalBinding: getTelegramQueueJournalBinding,
786
- getMessageOwnership: messageOwnershipRuntime.store.get,
787
- recordMessageOwnership: messageOwnershipRuntime.recordRouted,
788
- ...inboundBusProjectionRuntime,
789
- getCurrentLeaderEpoch,
790
- setCurrentLeaderIdentity: telegramBusLeaderState.set,
791
- getThreadReconciliationMachineState: threadReconciliationRuntime.getState,
792
- recordThreadReconciliationPlan,
793
- handleTelegramTopicLifecycleUpdate: topicLifecycleSync,
794
- handleTelegramThreadTargetObserved(_target, ctx) {
795
- return observedThreadTargetBinding.handle(ctx);
796
- },
797
- foreignOwnedUpdateForwarder,
798
- replaceFollowerThreadTarget: restoreFollowerThreadTarget,
799
- bridgeRuntime,
800
- activeTurnRuntime,
801
- mediaGroupRuntime,
802
- textGroupRuntime,
803
- telegramQueueStore,
804
- queueMutationRuntime,
805
- modelMenuRuntime,
806
- currentModelRuntime,
807
- modelSwitchController,
808
- menuActions,
809
- updateSettingsMenuMessage: settingsMenuRuntime.updateSettingsMenuMessage,
810
- openQueueMenu: queueMenuRuntime.openQueueMenu,
811
- queueMenuCallbackHandler: queueMenuRuntime.handleCallbackQuery,
812
- openSettingsMenu: settingsMenuRuntime.openSettingsMenu,
813
- settingsMenuCallbackHandler: settingsMenuRuntime.handleCallbackQuery,
814
- sectionRegistry,
815
- buttonActionStore,
816
- invokeBoundButtonAction: invokeGenerativeAppBoundButtonAction,
817
- inboundHandlerRuntime,
818
- threadStore,
819
- updateStatus,
820
- isContextActive: telegramSessionContextStore.isCurrent,
821
- dispatchNextQueuedTelegramTurn,
822
- requestDeferredDispatchNextQueuedTelegramTurn:
823
- deferredQueueDispatchRuntime.request,
824
- hasDeferredDispatchContext: deferredQueueDispatchRuntime.isBound,
825
- startTypingLoop: promptDispatchRuntime.startTypingLoop,
826
- stopTypingLoop: typing.stop,
827
- answerCallbackQuery,
828
- editInteractiveMessage,
829
- editMessageReplyMarkup: editTelegramMessageReplyMarkup,
830
- sendInteractiveMessage,
831
- deleteMessage: deleteTelegramMessage,
832
- answerGuestQuery,
833
- sendTextReply,
834
- setMyCommands,
835
- getCommands,
836
- downloadFile: downloadTelegramBridgeFile,
837
- resolveTimeLine: timeInjectionRuntime.resolveLine,
838
- getThinkingLevel,
839
- setThinkingLevel,
840
- persistScopedModelPatterns: Pi.createScopedModelPatternPersister({
841
- createSettingsManager: Pi.createSettingsManager,
842
- clearCachedModelMenuInputs: modelMenuRuntime.clearCachedInputs,
843
- }),
844
- setModel,
845
- sendUserMessage,
846
- isIdle,
847
- hasPendingMessages,
848
- compact,
849
- recordRuntimeEvent,
850
- });
851
- const queueHandoffReconciliationBinding =
852
- Updates.createTelegramQueueHandoffReconciliationBinding<Pi.ExtensionContext>(
853
- function (error) {
854
- recordRuntimeEvent("inbound-worker", error, {
855
- phase: "queue-handoff-reconcile",
856
- });
857
- },
858
- );
859
- const staleTopicApiErrorRecoveryDeps = {
860
- topicTargetStore: threadStore,
861
- getSyncState: telegramSyncStateRuntime.getState,
862
- setSyncState: telegramSyncStateRuntime.setState,
863
- recordEvent: recordRuntimeEvent,
864
- };
865
- const recoverStaleTelegramTopicApiError =
866
- Sync.createTelegramStaleTopicApiErrorRecoveryRuntime(
867
- staleTopicApiErrorRecoveryDeps,
868
- );
869
- const {
870
- owner: updateWorkerOwnerRuntime,
871
- leader: updateAdmissionLifecycleRuntime,
872
- follower: followerAdmissionLifecycleRuntime,
873
- } = Updates.createTelegramUpdateAdmissionRuntimeAssembly<
874
- Parameters<typeof inboundRouteRuntime.handleUpdate>[0] &
875
- Journal.TelegramJournaledUpdate,
876
- Pi.ExtensionContext
877
- >({
878
- runtimeBinding: updateAdmissionRuntimeBinding,
879
- owner: {
880
- instanceId: telegramInstanceId,
881
- processId: telegramProcessId,
882
- processBirthId: telegramQueueProcessBirthId,
883
- getSessionGeneration: telegramSessionContextStore.getGeneration,
884
- isContextCurrent: telegramSessionContextStore.isCurrent,
885
- dispatchNext: dispatchNextQueuedTelegramTurn,
886
- requestQueueHandoffReconciliation:
887
- queueHandoffReconciliationBinding.request,
888
- },
889
- worker: {
890
- defaultHandle: inboundRouteRuntime.handleUpdate,
891
- onStateChange: runtimeDiagnostics.scheduleSnapshotPersist,
892
- settleTerminalExecutionFailure(error) {
893
- return Sync.settleStaleTelegramTopicExecutionFailure(
894
- error,
895
- staleTopicApiErrorRecoveryDeps,
896
- );
897
- },
898
- },
899
- leader: {
900
- resolveBinding: resolveTelegramUpdateJournalBinding,
901
- hasAuthority: lockRuntime.owns,
902
- },
903
- follower: {
904
- resolveBinding: resolveTelegramFollowerJournalBinding,
905
- isRegistered: telegramBusFollowerRegistrationState.isRegistered,
906
- getGeneration: telegramBusFollowerRegistrationState.getGeneration,
907
- prepareUpdateForExecution(update) {
908
- return BusFollower.prepareTelegramBusFollowerJournaledUpdateForExecution(
909
- update,
910
- textGroupRuntime.prepareForwardedMessage,
911
- );
912
- },
913
- },
914
- recordRuntimeEvent,
915
- });
916
- const queueHandoffStagingRuntime =
917
- Queue.createTelegramQueueHandoffStagingRuntime({
918
- liveStore: telegramQueueStore,
919
- createControlExecution:
920
- Updates.createTelegramQueueHandoffControlExecutionFactory({
921
- isContextCurrent: telegramSessionContextStore.isCurrent,
922
- showStatus: menuActions.sendStatusMessage,
923
- openModelMenu: menuActions.openModelMenu,
924
- }),
925
- });
926
- const acceptStagedQueueHandoff =
927
- Updates.createTelegramQueueHandoffRecipientRuntime({
928
- staging: queueHandoffStagingRuntime,
929
- getRecipientOwner: updateWorkerOwnerRuntime.getQueueOwnerIdentity,
930
- getLifecycleForBinding:
931
- updateAdmissionRuntimeBinding.getLifecycleForJournalBinding,
932
- isTransportStampActive: telegramTransportStampRuntime.isActive,
933
- dispatchNext: dispatchNextQueuedTelegramTurn,
934
- });
935
- const followerDurableAdmissionRuntime =
936
- BusFollower.createTelegramBusFollowerDurableAdmissionRuntime({
937
- journal: {
938
- appendBatch(updates) {
939
- return followerAdmissionLifecycleRuntime.appendBatch(updates);
940
- },
941
- },
942
- signalWorker() {
943
- followerAdmissionLifecycleRuntime.signal();
944
- },
945
- });
946
- const promoteTelegramBusFollowerToLeader: BusFollower.TelegramBusFollowerPromotionHandler<Pi.ExtensionContext> =
947
- BusFollower.createTelegramBusFollowerPromotionHandler<Pi.ExtensionContext>({
948
- topicTargetStore: threadStore,
949
- instanceId: telegramInstanceId,
950
- getActiveProfileName: configStore.getActiveProfileName,
951
- async startLeader(ctx, election, onAcquired): Promise<boolean> {
952
- const result = await lockedPollingRuntime.start(ctx, {
953
- election,
954
- onAcquired,
955
- });
956
- return result.ok;
957
- },
958
- recordRuntimeEvent,
959
- });
960
- const agentMessageRuntime = AgentMessages.createTelegramAgentMessageRuntime({
961
- instanceId: telegramInstanceId,
962
- getAllowedChatId: configStore.getAllowedUserId,
963
- getLeaderTarget: telegramBusLeaderState.getTarget,
964
- getLeaderThreadName() {
965
- return findCurrentThreadRecord()?.threadName;
966
- },
967
- followerRegistry: telegramBusFollowerRegistry,
968
- getContext: telegramSessionContextStore.get,
969
- handleUpdate: inboundRouteRuntime.handleUpdate,
970
- });
971
- const agentMessageToolRoutingRuntime =
972
- Bindings.createTelegramAgentMessageToolRoutingRuntime({
973
- ownsLeader: lockRuntime.owns,
974
- ownsDirectDelivery: ownsTelegramDirectDelivery,
975
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
976
- getSourceTarget: proactivePushTargetGetter,
977
- getSourceThreadName() {
978
- return findCurrentThreadRecord()?.threadName;
979
- },
980
- local: agentMessageRuntime,
981
- follower: telegramBusFollowerClients.agentMessages,
982
- });
983
- const telegramBusFollowerAssembly: BusFollower.TelegramBusFollowerRuntimeAssembly<Pi.ExtensionContext> =
984
- BusFollower.createTelegramBusFollowerRuntimeAssembly<Pi.ExtensionContext>({
985
- instanceId: telegramInstanceId,
986
- registrationState: telegramBusFollowerRegistrationState,
987
- recordRuntimeEvent,
988
- receiver: {
989
- socketPath: getTelegramBusFollowerSocketPath,
990
- getContext: telegramSessionContextStore.get,
991
- getAuthSecret: telegramBusFollowerControlState.getActiveAuthSecret,
992
- getRecipientBindingKey: getTelegramManualFollowerProfileKey,
993
- durableAdmission: followerDurableAdmissionRuntime,
994
- handleQueueHandoff: acceptStagedQueueHandoff,
995
- },
996
- targetReplacement: {
997
- topicTargetStore: threadStore,
998
- getManualFollowerProfileKey: getTelegramManualFollowerProfileKey,
999
- manualFollowerOwnerId: telegramManualFollowerOwnerId,
1000
- getSyncState: telegramSyncStateRuntime.getState,
1001
- setSyncState: telegramSyncStateRuntime.setState,
1002
- updateStatus,
1003
- },
1004
- recovery: {
1005
- getLeaderState: lockRuntime.getState,
1006
- setLifecyclePhase: telegramBusFollowerControlState.setLifecyclePhase,
1007
- updateStatus,
1008
- promoteToLeader: promoteTelegramBusFollowerToLeader,
1009
- getActiveContext: telegramSessionContextStore.get,
1010
- },
1011
- registration: {
1012
- protocolIdentity: telegramBusProtocolIdentity,
1013
- getFollowerBusSocketPath: getTelegramBusFollowerSocketPath,
1014
- getLeaderSocketPath: getTelegramBusSocketPath,
1015
- isContextActive: telegramSessionContextStore.isCurrent,
1016
- createRequestId: telegramBusFollowerClients.createRequestId,
1017
- setActiveAuthSecret:
1018
- telegramBusFollowerControlState.setActiveAuthSecret,
1019
- getProfileKey: getTelegramManualFollowerProfileKey,
1020
- getProcessBirthId() {
1021
- return telegramQueueProcessBirthId;
1022
- },
1023
- getSessionGeneration: telegramSessionContextStore.getGeneration,
1024
- async onRegistered(ctx) {
1025
- await followerAdmissionLifecycleRuntime.onTransportChanged(ctx);
1026
- queueHandoffReconciliationBinding.request(ctx);
1027
- },
1028
- },
1029
- });
1030
- const telegramBusFollowerRegistration =
1031
- telegramBusFollowerAssembly.registration;
1032
- const { admission: pollingAdmissionRuntime } =
1033
- Polling.createTelegramDurablePollingRuntimeAssembly<
1034
- TelegramApi.TelegramUpdate,
1035
- Pi.ExtensionContext
1036
- >({
1037
- state: pollingControllerState,
1038
- canStart(ctx) {
1039
- return telegramSessionContextStore.isCurrent(ctx) && lockRuntime.owns(ctx);
1040
- },
1041
- onPersistentConflict(ctx, count): Promise<void> {
1042
- return lockedPollingRuntime.onPersistentConflict(ctx, count);
1043
- },
1044
- getConfig: configStore.get,
1045
- hasBotToken: configStore.hasBotToken,
1046
- deleteWebhook,
1047
- getUpdates,
1048
- persistConfig: persistTelegramConfigWithSync,
1049
- prepareUpdateBatch: textGroupRuntime.prepareUpdateBatch,
1050
- journal: {
1051
- appendBatch(updates, acceptedThroughUpdateId) {
1052
- return updateAdmissionLifecycleRuntime.appendBatch(
1053
- updates as Journal.TelegramJournaledUpdate[],
1054
- acceptedThroughUpdateId,
1055
- );
1056
- },
1057
- getAcceptedThroughUpdateId() {
1058
- return resolveTelegramUpdateJournalBinding()?.journal.read()
1059
- .acceptedThroughUpdateId;
1060
- },
1061
- async prepareCursorCutover() {
1062
- const binding = resolveTelegramUpdateJournalBinding();
1063
- if (!binding) {
1064
- throw new Error("Telegram update journal binding is unavailable.");
1065
- }
1066
- await Polling.cutOverTelegramPollingCursor({
1067
- getLegacyCursor: configStore.getLegacyPollingCursor,
1068
- readJournal: binding.journal.read,
1069
- publishJournalCursor(acceptedThroughUpdateId) {
1070
- binding.journal.appendBatch([], acceptedThroughUpdateId);
1071
- },
1072
- async removeLegacyCursor() {
1073
- configStore.removeLegacyPollingCursor();
1074
- await persistTelegramConfigWithSync();
1075
- },
1076
- });
1077
- },
1078
- getEntryCount: updateAdmissionLifecycleRuntime.getJournalEntryCount,
1079
- signalWorker: updateAdmissionLifecycleRuntime.signal,
1080
- getBootstrapEntryCount() {
1081
- return (
1082
- resolveTelegramUpdateJournalBinding()?.journal.read().entries
1083
- .length ?? 0
1084
- );
1085
- },
1086
- onSessionStart: updateAdmissionLifecycleRuntime.onSessionStart,
1087
- },
1088
- stopTypingLoop: typing.stop,
1089
- updateStatus,
1090
- onPollingStateChange: runtimeDiagnostics.scheduleSnapshotPersist,
1091
- recordRuntimeEvent,
1092
- });
1093
- const authorizeFollowerApiCall = Bus.createTelegramFollowerApiCallAuthorizer({
1094
- isMessageOwned: messageOwnershipRuntime.isOwnedByFollower,
1095
- });
1096
- const telegramBusLeaderRuntime =
1097
- BusLeader.createTelegramBusLeaderRuntimeAssembly<Pi.ExtensionContext>({
1098
- runtime: {
1099
- socketPath: getTelegramBusSocketPath,
1100
- commitEndpointPublication(commit) {
1101
- return lockRuntime.commitIfOwned(commit);
1102
- },
1103
- followerRegistry: telegramBusFollowerRegistry,
1104
- authSecret: telegramBusAuthSecret,
1105
- protocolIdentity: telegramBusProtocolIdentity,
1106
- startPolling: pollingAdmissionRuntime.start,
1107
- stopPolling: pollingAdmissionRuntime.stop,
1108
- authorizeFollowerApiCall,
1109
- resolveAgentTarget(follower, selector) {
1110
- return agentMessageRuntime.resolveTarget(selector, follower.target);
1111
- },
1112
- routeAgentMessage(follower, message) {
1113
- return agentMessageRuntime.route({
1114
- sourceTarget: follower.target,
1115
- sourceThreadName: follower.threadName,
1116
- message,
1117
- });
1118
- },
1119
- isFollowerProcessAlive: Locks.isProcessAlive,
1120
- shouldCleanupConfirmedDeadFollower:
1121
- configControls.resolveAutomaticThreadCleanupEnabled,
1122
- recordFollowerMessageOwnership(record) {
1123
- messageOwnershipRuntime.recordFollower(record);
1124
- },
1125
- },
1126
- getAllowedUserId: configStore.getAllowedUserId,
1127
- instanceId: telegramInstanceId,
1128
- getCwd: Pi.getExtensionContextCwd,
1129
- getTelegramProfile: configStore.getActiveProfileName,
1130
- shouldForceFreshUnnamed:
1131
- telegramThreadCapabilityState.shouldForceFreshLeaderThread,
1132
- topicTargetStore: threadStore,
1133
- callApi(method, body) {
1134
- return directTelegramApiRuntime.call(method, body);
1135
- },
1136
- callMultipart: directTelegramApiRuntime.callMultipart,
1137
- downloadFile: directTelegramApiRuntime.downloadFile,
1138
- recoverStaleTargetError: recoverStaleTelegramTopicApiError,
1139
- getCurrentLeaderEpoch,
1140
- getThreadReconciliationMachineState: threadReconciliationRuntime.getState,
1141
- recordThreadReconciliationPlan,
1142
- getSyncState: telegramSyncStateRuntime.getState,
1143
- setSyncState: telegramSyncStateRuntime.setState,
1144
- setLeaderTarget: telegramBusLeaderState.set,
1145
- onProvisioningStart: telegramProvisioningActivity.start,
1146
- onProvisioningEnd: telegramProvisioningActivity.end,
1147
- recordRuntimeEvent,
1148
- });
1149
- queueHandoffReconciliationBinding.set(
1150
- Updates.createTelegramQueueHandoffReconciliationRuntimeAssembly({
1151
- ownsDirect: lockRuntime.owns,
1152
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
1153
- isBusEnabled: isTelegramBusRuntimeEnabled,
1154
- canHandoffWithLeader() {
1155
- return Bus.hasTelegramBusCapability(
1156
- telegramBusFollowerRegistrationState.getLeaderProtocol(),
1157
- Bus.TELEGRAM_BUS_CAPABILITY_QUEUE_HANDOFF,
1158
- );
1159
- },
1160
- listFollowers: telegramBusFollowerRegistry.list,
1161
- createRecipientJournalResolver:
1162
- telegramJournalBindingRuntime.createRecipientResolver,
1163
- queueStore: telegramQueueStore,
1164
- admission: updateAdmissionRuntimeBinding,
1165
- createHandoffToken: Journal.createTelegramUpdateQueueHandoffToken,
1166
- createRequestId: telegramBusFollowerClients.createRequestId,
1167
- donorInstanceId: telegramInstanceId,
1168
- authSecret: telegramBusAuthSecret,
1169
- stageThroughFollower: telegramBusFollowerClients.queueHandoff,
1170
- routeThroughLeader: telegramBusLeaderRuntime.routeQueueHandoff,
1171
- recordRuntimeEvent,
1172
- }),
1173
- );
1174
- const telegramLeaderHealthRuntime = Sync.createTelegramLeaderHealthRuntime({
1175
- callGetMe() {
1176
- return directTelegramApiRuntime.call("getMe", {});
1177
- },
1178
- getSyncState: telegramSyncStateRuntime.getState,
1179
- setSyncState: telegramSyncStateRuntime.setState,
1180
- recordEvent: recordRuntimeEvent,
1181
- });
1182
- const telegramThreadCapabilityRuntime =
1183
- Polling.createTelegramThreadCapabilityOrchestration<
1184
- Pi.ExtensionContext,
1185
- Locks.TelegramLockEntry
1186
- >({
1187
- state: telegramThreadCapabilityState,
1188
- getAllowedUserId: configStore.getAllowedUserId,
1189
- callApi: callTelegramApi,
1190
- topicTargetStore: threadStore,
1191
- isBusRuntimeEnabled: isTelegramBusRuntimeEnabled,
1192
- ownsLock: lockRuntime.owns,
1193
- isFollowerRegistered: telegramBusFollowerRegistrationState.isRegistered,
1194
- startClassicPolling: pollingAdmissionRuntime.start,
1195
- stopClassicPolling: pollingAdmissionRuntime.stop,
1196
- startBusLeaderPolling: telegramBusLeaderRuntime.startPolling,
1197
- stopBusLeaderPolling: telegramBusLeaderRuntime.stopPolling,
1198
- startLeaderHealth: telegramLeaderHealthRuntime.start,
1199
- stopLeaderHealth: telegramLeaderHealthRuntime.stop,
1200
- registerFollowerWithLeader:
1201
- telegramBusFollowerRegistration.registerWithLeader,
1202
- stopFollowerRegistration: telegramBusFollowerRegistration.stop,
1203
- isTopicModeUnavailableError: Threads.isTelegramTopicModeUnavailableError,
1204
- updateStatus,
1205
- recordEvent: recordRuntimeEvent,
1206
- });
1207
- const telegramThreadCapabilityMonitor =
1208
- telegramThreadCapabilityRuntime.monitor;
1209
- observedThreadTargetBinding.set(
1210
- telegramThreadCapabilityRuntime.observeTarget,
1211
- );
1212
- const threadAwarePollingPorts = telegramThreadCapabilityRuntime.pollingPorts;
1213
- const lockedPollingRuntime = Locks.createTelegramLockedPollingRuntime({
1214
- lock: lockRuntime,
1215
- transportMonitor: telegramThreadCapabilityMonitor,
1216
- hasBotToken: configStore.hasBotToken,
1217
- canStartPolling: Pi.canStartPollingInExtensionContext,
1218
- isContextCurrent: telegramSessionContextStore.isCurrent,
1219
- formatStartBlockedMessage: Pi.formatPollingStartBlockedByRunMode,
1220
- startPolling: threadAwarePollingPorts.startPolling,
1221
- stopPolling: threadAwarePollingPorts.stopPolling,
1222
- registerFollowerWithOwner:
1223
- threadAwarePollingPorts.registerFollowerWithOwner,
1224
- stopFollowerRegistration: threadAwarePollingPorts.stopFollowerRegistration,
1225
- onTransportAvailabilityChanged() {
1226
- modelContextAvailabilityRuntime.reconcile();
1227
- const ctx = telegramSessionContextStore.get();
1228
- if (ctx) queueHandoffReconciliationBinding.request(ctx);
1229
- },
1230
- updateStatus,
1231
- recordRuntimeEvent,
1232
- });
1233
- const {
1234
- disconnect: disconnectTelegramAndDeleteCurrentThread,
1235
- cleanupForSessionRestart: cleanupTelegramThreadForSessionRestart,
1236
- } = Sync.createTelegramThreadDisconnectAssembly({
1237
- instanceId: telegramInstanceId,
1238
- getCurrentThreadRecord: findCurrentThreadRecord,
1239
- topicTargetStore: threadStore,
1240
- callApi: callTelegramApi,
1241
- getCurrentLeaderEpoch,
1242
- getLeaderTarget: telegramBusLeaderState.getTarget,
1243
- clearLeaderTarget: telegramBusLeaderState.clear,
1244
- disconnectFollowerThread:
1245
- telegramBusFollowerRegistration.disconnectFromLeader,
1246
- getSyncState: telegramSyncStateRuntime.getState,
1247
- setSyncState: telegramSyncStateRuntime.setState,
1248
- stopPolling: lockedPollingRuntime.stop,
1249
- suspendPolling: lockedPollingRuntime.suspend,
1250
- recordRuntimeEvent,
1251
- });
1252
- const telegramBridgeSessionLifecycleDeps =
1253
- Lifecycle.createTelegramBridgeSessionLifecycleDeps({
1254
- contextStore: telegramSessionContextStore,
1255
- queue: {
1256
- getCurrentModel: getContextModel,
1257
- loadConfig: configStore.load,
1258
- setQueuedItems: telegramQueueStore.setQueuedItems,
1259
- setCurrentModel: currentModelRuntime.set,
1260
- setPendingModelSwitch: pendingModelSwitchStore.set,
1261
- syncCounters: queue.syncCounters,
1262
- syncFlags: lifecycle.syncFlags,
1263
- bindDeferredDispatchContext: deferredQueueDispatchRuntime.bind,
1264
- prepareTempDir,
1265
- updateStatus,
1266
- unbindDeferredDispatchContext: deferredQueueDispatchRuntime.unbind,
1267
- discardQueuedItems: queueMutationRuntime.clear,
1268
- clearModelMenuState: modelMenuRuntime.clear,
1269
- getActiveTurnChatId: activeTurnRuntime.getChatId,
1270
- getActiveTurnTarget: activeTurnRuntime.getTarget,
1271
- clearPreview: previewRuntime.clear,
1272
- clearActiveTurn: activeTurnRuntime.clear,
1273
- clearAbort: abort.clearHandler,
1274
- recordRuntimeEvent,
1275
- },
1276
- follower: {
1277
- registrationState: telegramBusFollowerRegistrationState,
1278
- registrationRuntime: telegramBusFollowerRegistration,
1279
- instanceId: telegramInstanceId,
1280
- suspendPolling: lockedPollingRuntime.suspend,
1281
- isLeader: lockRuntime.owns,
1282
- getLeaderBinding: currentInstanceThreadRuntime.getRestorationIdentity,
1283
- getActiveContext: telegramSessionContextStore.get,
1284
- getActiveProfileName: configStore.getActiveProfileName,
1285
- getLeaderState: lockRuntime.getState,
1286
- updateStatus,
1287
- recordRuntimeEvent,
1288
- },
1289
- services: {
1290
- mediaGroup: {
1291
- resume: mediaGroupRuntime.resume,
1292
- suspend: mediaGroupRuntime.suspend,
1293
- },
1294
- textGroup: {
1295
- resume: textGroupRuntime.resume,
1296
- suspend: textGroupRuntime.suspend,
1297
- },
1298
- delivery: deliveryLifecycleRuntime,
1299
- polling: lockedPollingRuntime,
1300
- inboundWorker: {
1301
- onSessionShutdown: updateAdmissionRuntimeBinding.onSessionShutdown,
1302
- },
1303
- capabilityMonitor: telegramThreadCapabilityMonitor,
1304
- queueWatchdog: queueDispatchWatchdogRuntime,
1305
- },
1306
- });
1307
- const sessionLifecycleRuntime =
1308
- Lifecycle.createTelegramBridgeSessionLifecycleAssembly(
1309
- telegramBridgeSessionLifecycleDeps,
1310
- );
1311
-
1312
- // --- Extension API Bindings ---
1313
-
1314
- Bindings.registerTelegramCommandsAndTools({
1315
- pi,
1316
- agentDir: Paths.resolveAgentDir(),
1317
- configStore,
1318
- persistConfig: persistTelegramConfigWithSync,
1319
- setup,
1320
- activeTurnRuntime,
1321
- lockedPollingRuntime,
1322
- stopPolling: disconnectTelegramAndDeleteCurrentThread,
1323
- recoverPollingStart: Recovery.createTelegramPollingStartRecoveryHandler({
1324
- getOwnersPath: Paths.resolveTelegramOwnersPath,
1325
- getStatePaths() {
1326
- return [
1327
- Threads.getTelegramTopicTargetsPath(
1328
- undefined,
1329
- configStore.getActiveProfileName(),
1330
- ),
1331
- ];
1332
- },
1333
- suspendPolling: lockedPollingRuntime.suspend,
1334
- releaseOwnership: lockRuntime.release,
1335
- recordRuntimeEvent,
1336
- }),
1337
- getDisconnectThreadName() {
1338
- const record = findCurrentThreadRecord();
1339
- if (!record?.target.threadId) return undefined;
1340
- return record.threadName ?? "current Telegram thread";
1341
- },
1342
- onTransportChanged() {
1343
- deliveryLifecycleRuntime.onSessionStart();
1344
- activityVerbosityRuntime.reset();
1345
- modelContextAvailabilityRuntime.reconcile();
1346
- },
1347
- getStatusLines,
1348
- buttonActionStore,
1349
- sendMarkdownReply,
1350
- callMultipart,
1351
- getDefaultChatId: proactivePushChatIdGetter,
1352
- getDefaultTarget: proactivePushTargetGetter,
1353
- ...agentMessageToolRoutingRuntime,
1354
- updateStatus,
1355
- recordRuntimeEvent,
1356
- });
1357
-
1358
- // --- Lifecycle Hooks ---
1359
-
1360
- Bindings.registerTelegramLifecycleRuntimeHooks({
1361
- pi,
1362
- sessionLifecycleRuntime: {
1363
- ...sessionLifecycleRuntime,
1364
- onModelSelect: currentModelRuntime.onModelSelect,
1365
- },
1366
- activityRuntime,
1367
- activityVerbosityRuntime,
1368
- assistantOutputRuntime,
1369
- publicationRuntime,
1370
- configStore,
1371
- abort,
1372
- typing,
1373
- lifecycle,
1374
- activeTurnRuntime,
1375
- telegramQueueStore,
1376
- modelSwitchController,
1377
- previewRuntime,
1378
- promptDispatchRuntime,
1379
- deferredQueueDispatchRuntime,
1380
- modelContextAvailabilityRuntime,
1381
- disconnectOnQuit: cleanupTelegramThreadForSessionRestart,
1382
- resolveAutomaticThreadCleanupEnabled:
1383
- configControls.resolveAutomaticThreadCleanupEnabled,
1384
- buttonActionStore,
1385
- callMultipart,
1386
- sendChatAction,
1387
- sendRecordVoiceAction,
1388
- sendMarkdownReply,
1389
- sendTextReply,
1390
- dispatchNextQueuedTelegramTurn,
1391
- onPromptHandedOff(turn, ctx) {
1392
- updateAdmissionRuntimeBinding
1393
- .getSettlement()
1394
- ?.onPromptHandedOff(turn, ctx);
1395
- },
1396
- answerGuestQuery,
1397
- deleteMessage: deleteTelegramMessage,
1398
- sendGuestReply,
1399
- finalizeMarkdownPreview,
1400
- proactivePushTargetGetter,
1401
- getAssistantRenderingMode: configControls.getAssistantRenderingMode,
1402
- recordMessageOwnership: messageOwnershipRuntime.recordLocal,
1403
- canSendAgentActivity(ctx) {
1404
- return (
1405
- lockOwnershipGuard.ownsContext(ctx) ||
1406
- telegramBusFollowerRegistrationState.isRegistered()
1407
- );
1408
- },
1409
- isSessionContextActive(ctx) {
1410
- return telegramSessionContextStore.isCurrent(ctx);
1411
- },
1412
- isTurnTransportActive(turn) {
1413
- return telegramTransportStampRuntime.isActive(turn.transportStamp);
1414
- },
1415
- updateStatus,
1416
- recordRuntimeEvent,
1417
- });
1418
- }
7
+ export { default } from "./lib/extension.ts";