@leitwerk-dev/telegram 0.1.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 (73) hide show
  1. package/README.md +145 -0
  2. package/dist/LICENSE +13 -0
  3. package/dist/actions.d.ts +9 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/actions.js +32 -0
  6. package/dist/actions.js.map +1 -0
  7. package/dist/bridge.d.ts +132 -0
  8. package/dist/bridge.d.ts.map +1 -0
  9. package/dist/bridge.js +2032 -0
  10. package/dist/bridge.js.map +1 -0
  11. package/dist/config.d.ts +25 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +70 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/fake-telegram-client.d.ts +82 -0
  16. package/dist/fake-telegram-client.d.ts.map +1 -0
  17. package/dist/fake-telegram-client.js +107 -0
  18. package/dist/fake-telegram-client.js.map +1 -0
  19. package/dist/form-session.d.ts +143 -0
  20. package/dist/form-session.d.ts.map +1 -0
  21. package/dist/form-session.js +218 -0
  22. package/dist/form-session.js.map +1 -0
  23. package/dist/grammy-telegram-client.d.ts +131 -0
  24. package/dist/grammy-telegram-client.d.ts.map +1 -0
  25. package/dist/grammy-telegram-client.js +151 -0
  26. package/dist/grammy-telegram-client.js.map +1 -0
  27. package/dist/index.d.ts +19 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +55 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/launch-session.d.ts +103 -0
  32. package/dist/launch-session.d.ts.map +1 -0
  33. package/dist/launch-session.js +435 -0
  34. package/dist/launch-session.js.map +1 -0
  35. package/dist/markdown-html.d.ts +29 -0
  36. package/dist/markdown-html.d.ts.map +1 -0
  37. package/dist/markdown-html.js +259 -0
  38. package/dist/markdown-html.js.map +1 -0
  39. package/dist/mermaid-image.d.ts +2 -0
  40. package/dist/mermaid-image.d.ts.map +1 -0
  41. package/dist/mermaid-image.js +99 -0
  42. package/dist/mermaid-image.js.map +1 -0
  43. package/dist/process-feed.d.ts +58 -0
  44. package/dist/process-feed.d.ts.map +1 -0
  45. package/dist/process-feed.js +165 -0
  46. package/dist/process-feed.js.map +1 -0
  47. package/dist/process-thread-store.d.ts +18 -0
  48. package/dist/process-thread-store.d.ts.map +1 -0
  49. package/dist/process-thread-store.js +74 -0
  50. package/dist/process-thread-store.js.map +1 -0
  51. package/dist/topic-title.d.ts +7 -0
  52. package/dist/topic-title.d.ts.map +1 -0
  53. package/dist/topic-title.js +29 -0
  54. package/dist/topic-title.js.map +1 -0
  55. package/dist/types.d.ts +118 -0
  56. package/dist/types.d.ts.map +1 -0
  57. package/dist/types.js +19 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +57 -0
  60. package/src/actions.ts +41 -0
  61. package/src/bridge.ts +2870 -0
  62. package/src/config.ts +108 -0
  63. package/src/fake-telegram-client.ts +167 -0
  64. package/src/form-session.ts +359 -0
  65. package/src/grammy-telegram-client.ts +292 -0
  66. package/src/index.ts +68 -0
  67. package/src/launch-session.ts +620 -0
  68. package/src/markdown-html.ts +297 -0
  69. package/src/mermaid-image.ts +99 -0
  70. package/src/process-feed.ts +237 -0
  71. package/src/process-thread-store.ts +98 -0
  72. package/src/topic-title.ts +35 -0
  73. package/src/types.ts +138 -0
package/src/bridge.ts ADDED
@@ -0,0 +1,2870 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import type {
3
+ ProcessInstance,
4
+ ProcessLeafOutcomeSnapshot,
5
+ ProcessTurnRecord,
6
+ ProcessTurnRecordPathType,
7
+ } from "@leitwerk-dev/domain";
8
+ import { TELEGRAM_ACTOR } from "@leitwerk-dev/domain";
9
+ import type {
10
+ CoreServerSetupDeps,
11
+ FormDefinition,
12
+ LauncherFieldOptionDefinition,
13
+ LauncherModelConfigPreviewLike,
14
+ LauncherModelConfigSchemaLike,
15
+ ModelProfileOptionSummaryLike,
16
+ ProcessActionSummaryLike,
17
+ ProcessLaunchPlan,
18
+ ProcessModelSelectionServiceLike,
19
+ ServerExtensionEventMap,
20
+ ServerExtensionLogger,
21
+ UiLauncherSummary,
22
+ } from "@leitwerk-dev/process-sdk";
23
+ import { buildActionKeyboard, continuableFailedTurnRecordId } from "./actions.js";
24
+ import type { TelegramExtensionConfig } from "./config.js";
25
+ import {
26
+ type ActionPreviewLike,
27
+ applyFormSkip,
28
+ applyFormText,
29
+ applyQuestionText,
30
+ buildActionFormSession,
31
+ buildActionModelPrompt,
32
+ buildActionModelSession,
33
+ buildActionModelSwitchWarning,
34
+ buildContinueSession,
35
+ buildFieldPrompt,
36
+ buildQuestionPrompt,
37
+ buildQuestionSession,
38
+ buildRecoveryModelPrompt,
39
+ buildRecoveryModelSession,
40
+ canSkipActionFormField,
41
+ currentField,
42
+ type PendingActionFormSession,
43
+ type PendingActionModelSession,
44
+ type PendingRecoveryModelSession,
45
+ type PendingTelegramSession,
46
+ } from "./form-session.js";
47
+ import {
48
+ applyLaunchFieldText,
49
+ applyLaunchFieldValue,
50
+ applyLaunchModelStepAction,
51
+ applyLaunchModelStepText,
52
+ beginLaunchModelEdit,
53
+ buildLaunchFieldPrompt,
54
+ buildLaunchInput,
55
+ buildLaunchModelConfig,
56
+ buildLaunchModelStepPrompt,
57
+ buildLaunchModelSummary,
58
+ buildLaunchReview,
59
+ createLaunchSession,
60
+ currentLaunchField,
61
+ currentLaunchModelStep,
62
+ finishLaunchModelEdit,
63
+ getLaunchFieldOptions,
64
+ hasLaunchModelControls,
65
+ type LaunchFieldOptionsById,
66
+ type LaunchModelStep,
67
+ type LaunchModelStepAction,
68
+ type LaunchModelStepResult,
69
+ moveLaunchSessionToValidationField,
70
+ type PendingLaunchSession,
71
+ seedLaunchModelConfigFromPlan,
72
+ } from "./launch-session.js";
73
+ import {
74
+ escapeTelegramHtml as escapeHtml,
75
+ renderResultMarkdownForTelegram,
76
+ splitPlainTelegramText,
77
+ splitTelegramHtml,
78
+ type TelegramResultPart,
79
+ telegramHtmlToPlainText,
80
+ } from "./markdown-html.js";
81
+ import { renderMermaidPng } from "./mermaid-image.js";
82
+ import {
83
+ buildActionSubmittedMessage,
84
+ buildActionsPromptMessage,
85
+ buildLeafOutcomeMessage,
86
+ buildLifecycleMessage,
87
+ buildProcessCreatedMessage,
88
+ buildStatusMessage,
89
+ buildTurnOutcomeMessage,
90
+ buildTurnStartedMessage,
91
+ formatTurnIdLabel,
92
+ } from "./process-feed.js";
93
+ import { ProcessThreadStore, threadKey } from "./process-thread-store.js";
94
+ import { buildTopicTitle } from "./topic-title.js";
95
+ import type {
96
+ TelegramCallbackUpdate,
97
+ TelegramClient,
98
+ TelegramForumTopicClosedUpdate,
99
+ TelegramForumTopicCreatedUpdate,
100
+ TelegramInlineKeyboard,
101
+ TelegramProcessThread,
102
+ TelegramReplyMarkup,
103
+ TelegramTextUpdate,
104
+ } from "./types.js";
105
+
106
+ type TelegramCallbackCommand =
107
+ | { kind: "process_action"; actionId: string; instanceId: string }
108
+ | { kind: "action_form_skip"; fieldId: string; instanceId: string; sessionId: string }
109
+ | { kind: "action_model_select"; instanceId: string; sessionId: string; profileIndex: number }
110
+ | { kind: "action_model_skip"; instanceId: string; sessionId: string }
111
+ | { kind: "retry"; instanceId: string }
112
+ | { kind: "continue"; instanceId: string };
113
+
114
+ type TelegramLaunchCallbackCommand =
115
+ | { kind: "select_launcher"; sessionKey: string; launcherId: string }
116
+ | { kind: "field_value"; sessionKey: string; fieldId: string; value: unknown }
117
+ | { kind: "skip_field"; sessionKey: string; fieldId: string }
118
+ | { kind: "edit_models"; sessionKey: string }
119
+ | ({ kind: "model_step"; sessionKey: string; stepKey: string } & LaunchModelStepAction)
120
+ | { kind: "finish_model_edit"; sessionKey: string }
121
+ | { kind: "confirm_launch"; sessionKey: string }
122
+ | { kind: "cancel_launch"; sessionKey: string };
123
+
124
+ interface ChatTarget {
125
+ chatId: string;
126
+ messageThreadId?: number;
127
+ }
128
+
129
+ type TelegramActionExecutionSummary = ProcessActionSummaryLike & {
130
+ preview?: ActionPreviewLike | null;
131
+ };
132
+
133
+ interface StoredLaunchCallbackCommand {
134
+ command: TelegramLaunchCallbackCommand;
135
+ expiresAt: number;
136
+ }
137
+
138
+ interface ResolvedLaunchCallbackCommand {
139
+ token: string;
140
+ command: TelegramLaunchCallbackCommand;
141
+ }
142
+
143
+ const LAUNCH_CALLBACK_PREFIX = "launch:";
144
+ const LAUNCH_SESSION_TTL_MS = 20 * 60 * 1000;
145
+ const MAX_LAUNCHER_BUTTONS = 30;
146
+ const MAX_FIELD_OPTION_BUTTONS = 20;
147
+ const MAX_MODEL_PROFILE_BUTTONS = 20;
148
+ const CONTINUE_PROMPT =
149
+ "Send an optional continuation instruction, or send /skip to continue with the default prompt.";
150
+
151
+ function commandName(text: string): string | null {
152
+ return /^\/(\w+)(?:@\w+)?(?:\s|$)/.exec(text.trim())?.[1]?.toLowerCase() ?? null;
153
+ }
154
+
155
+ function commandArgs(text: string): string {
156
+ return text
157
+ .trim()
158
+ .replace(/^\/\w+(?:@\w+)?\s*/, "")
159
+ .trim();
160
+ }
161
+
162
+ function rows<T>(items: readonly T[], size: number): T[][] {
163
+ return Array.from({ length: Math.ceil(items.length / size) }, (_, index) => [
164
+ ...items.slice(index * size, index * size + size),
165
+ ]);
166
+ }
167
+
168
+ function messageTarget(chatId: string, messageThreadId: number | undefined) {
169
+ return { chatId, ...(messageThreadId !== undefined ? { messageThreadId } : {}) };
170
+ }
171
+
172
+ function launchSessionKey(input: {
173
+ chatId: string;
174
+ messageThreadId?: number;
175
+ from: { id: number } | null | undefined;
176
+ }): string | null {
177
+ return typeof input.from?.id === "number"
178
+ ? `${input.chatId}:${input.messageThreadId ?? 0}:${input.from.id}`
179
+ : null;
180
+ }
181
+
182
+ function splitScopedCallbackPayload(payload: string): { instanceId: string; value: string } | null {
183
+ const separator = payload.indexOf(":");
184
+ if (separator <= 0 || separator === payload.length - 1) return null;
185
+ return {
186
+ instanceId: payload.slice(0, separator),
187
+ value: payload.slice(separator + 1),
188
+ };
189
+ }
190
+
191
+ function parseTripleCallbackPayload(
192
+ payload: string,
193
+ ): { instanceId: string; sessionId: string; value: string } | null {
194
+ const parts = payload.split(":");
195
+ const [instanceId, sessionId, ...rest] = parts;
196
+ if (!instanceId || !sessionId) return null;
197
+ return { instanceId, sessionId, value: rest.join(":") };
198
+ }
199
+
200
+ function parseActionFormSkipCallbackPayload(
201
+ payload: string,
202
+ ): Extract<TelegramCallbackCommand, { kind: "action_form_skip" }> | null {
203
+ const parsed = parseTripleCallbackPayload(payload);
204
+ if (!parsed) return null;
205
+ return {
206
+ kind: "action_form_skip",
207
+ instanceId: parsed.instanceId,
208
+ sessionId: parsed.sessionId,
209
+ fieldId: parsed.value,
210
+ };
211
+ }
212
+
213
+ function parseCallbackCommand(data: string): TelegramCallbackCommand | null {
214
+ if (data.startsWith("a:")) {
215
+ const scoped = splitScopedCallbackPayload(data.slice("a:".length));
216
+ return scoped
217
+ ? { kind: "process_action", instanceId: scoped.instanceId, actionId: scoped.value }
218
+ : null;
219
+ }
220
+ if (data.startsWith("fs:")) {
221
+ return parseActionFormSkipCallbackPayload(data.slice("fs:".length));
222
+ }
223
+ if (data.startsWith("ams:")) {
224
+ return parseActionModelSelectCallbackPayload(data.slice("ams:".length));
225
+ }
226
+ if (data.startsWith("amk:")) {
227
+ return parseActionModelSkipCallbackPayload(data.slice("amk:".length));
228
+ }
229
+ if (data.startsWith("r:")) {
230
+ const instanceId = data.slice("r:".length);
231
+ return instanceId ? { kind: "retry", instanceId } : null;
232
+ }
233
+ if (data.startsWith("c:")) {
234
+ const instanceId = data.slice("c:".length);
235
+ return instanceId ? { kind: "continue", instanceId } : null;
236
+ }
237
+ return null;
238
+ }
239
+
240
+ function parseActionModelSelectCallbackPayload(
241
+ payload: string,
242
+ ): Extract<TelegramCallbackCommand, { kind: "action_model_select" }> | null {
243
+ const parsed = parseTripleCallbackPayload(payload);
244
+ if (!parsed) return null;
245
+ const profileIndex = Number(parsed.value);
246
+ if (!Number.isInteger(profileIndex) || profileIndex < 1) return null;
247
+ return {
248
+ kind: "action_model_select",
249
+ instanceId: parsed.instanceId,
250
+ sessionId: parsed.sessionId,
251
+ profileIndex,
252
+ };
253
+ }
254
+
255
+ function parseActionModelSkipCallbackPayload(
256
+ payload: string,
257
+ ): Extract<TelegramCallbackCommand, { kind: "action_model_skip" }> | null {
258
+ const parsed = parseTripleCallbackPayload(payload);
259
+ if (!parsed) return null;
260
+ return {
261
+ kind: "action_model_skip",
262
+ instanceId: parsed.instanceId,
263
+ sessionId: parsed.sessionId,
264
+ };
265
+ }
266
+
267
+ function resolveProfileByTextOrIndex(
268
+ text: string,
269
+ profiles: readonly ModelProfileOptionSummaryLike[],
270
+ ): ModelProfileOptionSummaryLike | null {
271
+ const byIdOrLabel = profiles.find(
272
+ (p) => p.id === text || p.label.toLowerCase() === text.toLowerCase(),
273
+ );
274
+ if (byIdOrLabel) return byIdOrLabel;
275
+ const index = Number(text);
276
+ if (Number.isInteger(index) && index >= 1 && index <= profiles.length) {
277
+ return profiles[index - 1] ?? null;
278
+ }
279
+ return null;
280
+ }
281
+
282
+ function resolveModelProfileFromSession(
283
+ session: PendingTelegramSession | undefined,
284
+ profileIndex: number,
285
+ ): ModelProfileOptionSummaryLike | null {
286
+ const profiles =
287
+ session?.kind === "action_model"
288
+ ? session.profiles
289
+ : session?.kind === "recovery_model"
290
+ ? session.profiles
291
+ : null;
292
+ if (!profiles) return null;
293
+ return profiles[profileIndex - 1] ?? null;
294
+ }
295
+
296
+ function processCanAcceptFreeText(process: ProcessInstance): boolean {
297
+ return !["completed", "aborted", "error"].includes(process.lifecycleStatus);
298
+ }
299
+
300
+ function processIsFinished(process: ProcessInstance): boolean {
301
+ return process.lifecycleStatus === "completed" || process.lifecycleStatus === "aborted";
302
+ }
303
+
304
+ function resultTurnRecordKey(instanceId: string, turnRecordId: string): string {
305
+ return `${instanceId}:${turnRecordId}`;
306
+ }
307
+
308
+ function recoveryActionLabels(process: ProcessInstance): string[] {
309
+ if (process.lifecycleStatus !== "error" || !process.currentExecution) return [];
310
+ return ["Retry", ...(continuableFailedTurnRecordId(process) ? ["Continue"] : [])];
311
+ }
312
+
313
+ function readActionPreview(action: ProcessActionSummaryLike): ActionPreviewLike | null {
314
+ const preview = (action as { preview?: unknown }).preview;
315
+ if (!isRecord(preview)) return null;
316
+ return {
317
+ ...(typeof preview.kind === "string" ? { kind: preview.kind } : {}),
318
+ ...(typeof preview.turnId === "string" ? { turnId: preview.turnId } : {}),
319
+ ...(typeof preview.lifecycleStatus === "string"
320
+ ? { lifecycleStatus: preview.lifecycleStatus }
321
+ : {}),
322
+ };
323
+ }
324
+
325
+ function shouldDeferActionPromptUntilTurnTerminalEvent(changedFields: readonly string[]): boolean {
326
+ return changedFields.includes("currentExecution");
327
+ }
328
+
329
+ function shouldDeferCompletedLifecycleUntilTurnOutcome(input: {
330
+ process: ProcessInstance;
331
+ changedFields: readonly string[];
332
+ }): boolean {
333
+ return (
334
+ input.process.lifecycleStatus === "completed" &&
335
+ input.changedFields.includes("currentExecution")
336
+ );
337
+ }
338
+
339
+ function isRecord(value: unknown): value is Record<string, unknown> {
340
+ return typeof value === "object" && value !== null && !Array.isArray(value);
341
+ }
342
+
343
+ function readClaimedLaunchThread(
344
+ process: ProcessInstance,
345
+ expectedChatId: string,
346
+ ): Pick<TelegramProcessThread, "mode" | "chatId" | "messageThreadId"> | null {
347
+ const telegram = isRecord(process.metadata?.telegram) ? process.metadata.telegram : null;
348
+ const thread = isRecord(telegram?.launchThread) ? telegram.launchThread : null;
349
+ return thread?.mode === "forum_topic" &&
350
+ thread.chatId === expectedChatId &&
351
+ typeof thread.messageThreadId === "number"
352
+ ? { mode: "forum_topic", chatId: thread.chatId, messageThreadId: thread.messageThreadId }
353
+ : null;
354
+ }
355
+
356
+ function createActionFormSessionId(): string {
357
+ return randomBytes(4).toString("hex");
358
+ }
359
+
360
+ function attachLaunchThreadMetadata(
361
+ launchPlan: ProcessLaunchPlan,
362
+ thread: Pick<TelegramProcessThread, "mode" | "chatId" | "messageThreadId">,
363
+ ): ProcessLaunchPlan {
364
+ const metadata = launchPlan.processInput.metadata ?? {};
365
+ const telegram = isRecord(metadata.telegram) ? metadata.telegram : {};
366
+ return {
367
+ ...launchPlan,
368
+ processInput: {
369
+ ...launchPlan.processInput,
370
+ metadata: {
371
+ ...metadata,
372
+ telegram: {
373
+ ...telegram,
374
+ launchThread: { ...thread },
375
+ },
376
+ },
377
+ },
378
+ };
379
+ }
380
+
381
+ export class TelegramBridge {
382
+ private readonly store: ProcessThreadStore;
383
+ private readonly sessions = new Map<string, PendingTelegramSession>();
384
+ private readonly launchSessions = new Map<string, PendingLaunchSession>();
385
+ private readonly launchCallbacks = new Map<string, StoredLaunchCallbackCommand>();
386
+ private nextLaunchCallbackId = 1;
387
+ private readonly processModelSelection: ProcessModelSelectionServiceLike | null;
388
+ private readonly threadEligibleInstanceIds = new Set<string>();
389
+ private readonly introSentInstanceIds = new Set<string>();
390
+ private readonly closedThreadKeys = new Set<string>();
391
+ private readonly sentResultTurnRecordKeys = new Set<string>();
392
+ private readonly deferredCompletedLifecycleProcesses = new Map<string, ProcessInstance>();
393
+ private readonly queues = new Map<string, Promise<void>>();
394
+ private readonly lastTurnInfo = new Map<
395
+ string,
396
+ { pathType: ProcessTurnRecordPathType; turnId: string }
397
+ >();
398
+
399
+ constructor(
400
+ private readonly input: {
401
+ config: TelegramExtensionConfig;
402
+ deps: CoreServerSetupDeps;
403
+ client: TelegramClient;
404
+ logger?: ServerExtensionLogger;
405
+ },
406
+ ) {
407
+ this.store = new ProcessThreadStore(input.deps);
408
+ this.processModelSelection = input.deps.processModelSelection ?? null;
409
+ input.client.onText((update) => this.handleText(update));
410
+ input.client.onCallback((update) => this.handleCallback(update));
411
+ input.client.onForumTopicCreated((update) => this.handleForumTopicCreated(update));
412
+ input.client.onForumTopicClosed((update) => this.handleForumTopicClosed(update));
413
+ }
414
+
415
+ async start(): Promise<void> {
416
+ for (const instanceId of this.store.rebuildFromEvents()) {
417
+ this.threadEligibleInstanceIds.add(instanceId);
418
+ this.introSentInstanceIds.add(instanceId);
419
+ }
420
+ this.seedLastTurnInfoFromEvents();
421
+ await this.input.client.start();
422
+ for (const request of this.input.deps.processQuestions?.listOpen() ?? []) {
423
+ await this.onQuestionRequested({ instanceId: request.instanceId, request });
424
+ }
425
+ }
426
+
427
+ /**
428
+ * After a server restart the in-memory lastTurnInfo map is empty.
429
+ * Rebuild it from the most recent turn_started event for every non-terminal
430
+ * process that already has a Telegram thread, so that /status and actions
431
+ * prompts show the correct path label without waiting for the next turn.
432
+ */
433
+ private seedLastTurnInfoFromEvents(): void {
434
+ for (const process of this.input.deps.processes.listAll()) {
435
+ if (["completed", "aborted"].includes(process.lifecycleStatus)) continue;
436
+ if (!this.store.getByInstanceId(process.id)) continue;
437
+ if (this.lastTurnInfo.has(process.id)) continue;
438
+ const events = this.input.deps.events.listByInstance(process.id, 50);
439
+ const turnStartedEvent = events.find((e) => e.eventType === "turn_started");
440
+ if (!turnStartedEvent) continue;
441
+ const pathType = turnStartedEvent.data.pathType as ProcessTurnRecordPathType | undefined;
442
+ const turnId = turnStartedEvent.data.turnId as string | undefined;
443
+ if (pathType && turnId) {
444
+ this.lastTurnInfo.set(process.id, { pathType, turnId });
445
+ }
446
+ }
447
+ }
448
+
449
+ async stop(): Promise<void> {
450
+ await this.input.client.stop();
451
+ }
452
+
453
+ register(events: {
454
+ on<K extends keyof ServerExtensionEventMap & string>(
455
+ event: K,
456
+ handler: (payload: ServerExtensionEventMap[K]) => void | Promise<void>,
457
+ ): void;
458
+ }): void {
459
+ const on = <K extends keyof ServerExtensionEventMap & string>(
460
+ event: K,
461
+ handler: (payload: ServerExtensionEventMap[K]) => Promise<void>,
462
+ ) =>
463
+ events.on(event, (payload) => void this.enqueue(payload.instanceId, () => handler(payload)));
464
+ on("process_created", (payload) => this.onProcessCreated(payload));
465
+ on("process_updated", (payload) => this.onProcessUpdated(payload));
466
+ on("turn_started", (payload) => this.onTurnStarted(payload.turnRecord));
467
+ on("turn_failed", (payload) => this.onTurnFailed(payload));
468
+ on("leaf_outcome_captured", (payload) => this.onLeafOutcome(payload.snapshot));
469
+ on("question_requested", (payload) => this.onQuestionRequested(payload));
470
+ on("turn_outcome", (payload) => this.onTurnOutcome(payload));
471
+ }
472
+
473
+ private enqueue(instanceId: string, task: () => Promise<void>): Promise<void> {
474
+ const previous = this.queues.get(instanceId) ?? Promise.resolve();
475
+ const next = previous
476
+ .catch(() => undefined)
477
+ .then(task)
478
+ .catch((error) => this.logError(error, "Telegram bridge task failed"));
479
+ const stored = next.finally(() => {
480
+ if (this.queues.get(instanceId) === stored) this.queues.delete(instanceId);
481
+ });
482
+ this.queues.set(instanceId, stored);
483
+ return stored;
484
+ }
485
+
486
+ private async onProcessCreated(
487
+ payload: ServerExtensionEventMap["process_created"],
488
+ ): Promise<void> {
489
+ this.threadEligibleInstanceIds.add(payload.process.id);
490
+ const thread = await this.ensureThread(payload.process);
491
+ if (!thread) return;
492
+ await this.sendProcessIntro(thread, payload.process);
493
+ if (processIsFinished(payload.process)) {
494
+ await this.closeThread(thread);
495
+ return;
496
+ }
497
+ if (["waiting", "error"].includes(payload.process.lifecycleStatus)) {
498
+ await this.sendActionsForProcess(payload.process);
499
+ }
500
+ }
501
+
502
+ private async onProcessUpdated(
503
+ payload: ServerExtensionEventMap["process_updated"],
504
+ ): Promise<void> {
505
+ const thread = await this.getThread(payload.process);
506
+ if (!thread) return;
507
+ if (payload.changedFields.includes("title")) {
508
+ await this.syncThreadTitle(thread, payload.process);
509
+ }
510
+ const deferCompletedLifecycle = shouldDeferCompletedLifecycleUntilTurnOutcome({
511
+ process: payload.process,
512
+ changedFields: payload.changedFields,
513
+ });
514
+ if (deferCompletedLifecycle) {
515
+ this.deferredCompletedLifecycleProcesses.set(payload.process.id, payload.process);
516
+ } else if (payload.changedFields.includes("lifecycleStatus")) {
517
+ this.deferredCompletedLifecycleProcesses.delete(payload.process.id);
518
+ const lifecycleMessage = buildLifecycleMessage({
519
+ process: payload.process,
520
+ status: payload.process.lifecycleStatus,
521
+ });
522
+ if (lifecycleMessage) await this.sendHtml(thread, lifecycleMessage);
523
+ if (processIsFinished(payload.process)) {
524
+ await this.closeThread(thread);
525
+ return;
526
+ }
527
+ }
528
+ if (
529
+ (payload.process.lifecycleStatus === "waiting" ||
530
+ payload.process.lifecycleStatus === "error" ||
531
+ payload.changedFields.includes("selectedTurnId")) &&
532
+ !shouldDeferActionPromptUntilTurnTerminalEvent(payload.changedFields)
533
+ ) {
534
+ await this.sendActionsForProcess(payload.process);
535
+ }
536
+ }
537
+
538
+ private async onTurnStarted(turnRecord: ProcessTurnRecord): Promise<void> {
539
+ const thread = await this.getThread(turnRecord.instanceId);
540
+ if (!thread) return;
541
+ const modelLabel = this.resolveTurnModelLabel(turnRecord);
542
+ const turnDescription = formatTurnIdLabel(turnRecord.turnId);
543
+ this.lastTurnInfo.set(turnRecord.instanceId, {
544
+ pathType: turnRecord.pathType,
545
+ turnId: turnRecord.turnId,
546
+ });
547
+ await this.sendHtml(
548
+ thread,
549
+ buildTurnStartedMessage(turnRecord, { turnDescription, modelLabel }),
550
+ );
551
+ }
552
+
553
+ private async onQuestionRequested(
554
+ payload: ServerExtensionEventMap["question_requested"],
555
+ ): Promise<void> {
556
+ const thread = await this.getThread(payload.instanceId);
557
+ if (!thread) return;
558
+ const key = threadKey(thread.chatId, thread.messageThreadId);
559
+ const existing = this.sessions.get(key);
560
+ if (existing?.kind === "question" && existing.request.id === payload.request.id) return;
561
+ const session = buildQuestionSession(payload);
562
+ this.sessions.set(key, session);
563
+ await this.sendCurrentSessionPrompt(thread, session);
564
+ }
565
+
566
+ // Resolves the human-readable label for the model currently running in a turn.
567
+ // Intentionally queries unfiltered availableProfiles (not filtered through allowedModelProfileIds)
568
+ // because this describes what IS running, not what the user could have selected.
569
+ private resolveTurnModelLabel(turnRecord: ProcessTurnRecord): string | null {
570
+ if (turnRecord.turnType !== "llm" || !turnRecord.modelProfileId) return null;
571
+ const profile = this.processModelSelection
572
+ ?.listAvailableProfiles(turnRecord.instanceId)
573
+ ?.find((p) => p.id === turnRecord.modelProfileId);
574
+ return profile?.label ?? turnRecord.modelProfileId;
575
+ }
576
+
577
+ private filterProfiles<T extends ModelProfileOptionSummaryLike>(
578
+ profiles: readonly T[],
579
+ ): readonly T[] {
580
+ const allowedIds = this.input.config.allowedModelProfileIds;
581
+ if (!allowedIds.length) return profiles;
582
+ const allowed = new Set(allowedIds);
583
+ return profiles.filter((p) => allowed.has(p.id));
584
+ }
585
+
586
+ private listSelectableProfiles(instanceId: string): readonly ModelProfileOptionSummaryLike[] {
587
+ if (!this.input.config.actionModelSelection.enabled || !this.processModelSelection) return [];
588
+ return this.filterProfiles(this.processModelSelection.listAvailableProfiles(instanceId) ?? []);
589
+ }
590
+
591
+ private filterLaunchSchemaAvailableProfiles(
592
+ schema: LauncherModelConfigSchemaLike | null,
593
+ ): LauncherModelConfigSchemaLike | null {
594
+ return schema
595
+ ? { ...schema, availableProfiles: this.filterProfiles(schema.availableProfiles) }
596
+ : null;
597
+ }
598
+
599
+ private async onTurnFailed(payload: ServerExtensionEventMap["turn_failed"]): Promise<void> {
600
+ const { turnRecord } = payload;
601
+ const thread = await this.getThread(turnRecord.instanceId);
602
+ if (!thread) return;
603
+ const errorSummary = payload.errorSummary.trim() || turnRecord.errorSummary || "Turn failed";
604
+ const errorClass = payload.errorClass ?? turnRecord.errorClass ?? null;
605
+ await this.sendHtml(
606
+ thread,
607
+ [
608
+ `⚠️ <b>Turn failed</b>: ${escapeHtml(turnRecord.turnId)}`,
609
+ `Error: ${escapeHtml(errorSummary)}`,
610
+ ...(errorClass ? [`Class: ${escapeHtml(errorClass)}`] : []),
611
+ "",
612
+ "Use the recovery buttons for retry or continue options.",
613
+ ].join("\n"),
614
+ );
615
+ const process = this.input.deps.processes.getById(turnRecord.instanceId);
616
+ if (process) await this.sendActionsForProcess(process);
617
+ }
618
+
619
+ private async sendPublishedResult(
620
+ thread: TelegramProcessThread,
621
+ input: {
622
+ instanceId: string;
623
+ turnRecordId: string;
624
+ markdown: string;
625
+ buildMessage: (leadingHtml: string) => string;
626
+ },
627
+ ): Promise<void> {
628
+ const markdown = input.markdown.trim();
629
+ if (!markdown) return;
630
+ const dedupeKey = resultTurnRecordKey(input.instanceId, input.turnRecordId);
631
+ if (this.sentResultTurnRecordKeys.has(dedupeKey)) return;
632
+ const parts = renderResultMarkdownForTelegram({
633
+ markdown,
634
+ instanceId: input.instanceId,
635
+ turnRecordId: input.turnRecordId,
636
+ });
637
+ const leadingHtml = parts[0]?.kind === "html" ? parts[0] : null;
638
+ await this.sendHtml(thread, input.buildMessage(leadingHtml?.html ?? ""));
639
+ await this.sendResultParts(
640
+ thread,
641
+ input.instanceId,
642
+ input.turnRecordId,
643
+ parts.slice(leadingHtml ? 1 : 0),
644
+ );
645
+ this.sentResultTurnRecordKeys.add(dedupeKey);
646
+ }
647
+
648
+ private async onLeafOutcome(snapshot: ProcessLeafOutcomeSnapshot): Promise<void> {
649
+ const thread = await this.getThread(snapshot.instanceId);
650
+ if (!thread) return;
651
+ const markdown = snapshot.fallbackMarkdown?.trim() ?? "";
652
+ if (markdown && snapshot.turnRecordId) {
653
+ await this.sendPublishedResult(thread, {
654
+ instanceId: snapshot.instanceId,
655
+ turnRecordId: snapshot.turnRecordId,
656
+ markdown,
657
+ buildMessage: (markdownHtml) => buildLeafOutcomeMessage({ snapshot, markdownHtml }),
658
+ });
659
+ return;
660
+ }
661
+ await this.sendHtml(thread, buildLeafOutcomeMessage({ snapshot }));
662
+ }
663
+
664
+ private async onTurnOutcome(payload: ServerExtensionEventMap["turn_outcome"]): Promise<void> {
665
+ const thread = await this.getThread(payload.instanceId);
666
+ if (!thread) return;
667
+ const pathType = this.lastTurnInfo.get(payload.instanceId)?.pathType ?? null;
668
+ await this.sendPublishedResult(thread, {
669
+ instanceId: payload.instanceId,
670
+ turnRecordId: payload.turnRecordId,
671
+ markdown: payload.turnResultMarkdown ?? "",
672
+ buildMessage: (markdownHtml) =>
673
+ buildTurnOutcomeMessage({
674
+ turnId: payload.turnId,
675
+ outcome: payload.outcome,
676
+ markdown: payload.turnResultMarkdown ?? "",
677
+ markdownHtml,
678
+ pathType,
679
+ }),
680
+ });
681
+ const deferredCompletedProcess = this.deferredCompletedLifecycleProcesses.get(
682
+ payload.instanceId,
683
+ );
684
+ if (deferredCompletedProcess) {
685
+ this.deferredCompletedLifecycleProcesses.delete(payload.instanceId);
686
+ const process =
687
+ this.input.deps.processes.getById(payload.instanceId) ?? deferredCompletedProcess;
688
+ const lifecycleMessage = buildLifecycleMessage({
689
+ process,
690
+ status: process.lifecycleStatus,
691
+ });
692
+ if (lifecycleMessage) await this.sendHtml(thread, lifecycleMessage);
693
+ if (processIsFinished(process)) await this.closeThread(thread);
694
+ return;
695
+ }
696
+ const process = this.input.deps.processes.getById(payload.instanceId);
697
+ if (process && ["waiting", "error"].includes(process.lifecycleStatus)) {
698
+ await this.sendActionsForProcess(process);
699
+ }
700
+ }
701
+
702
+ private async ensureThread(process: ProcessInstance): Promise<TelegramProcessThread | null> {
703
+ const existing = this.store.getByInstanceId(process.id);
704
+ if (existing) return existing;
705
+ const topicName = buildTopicTitle({ process, template: this.input.config.topicTitleTemplate });
706
+ const claimedThread = readClaimedLaunchThread(process, this.input.config.delivery.forumChatId);
707
+ if (claimedThread) {
708
+ const thread: TelegramProcessThread = { ...claimedThread, topicName };
709
+ try {
710
+ await this.input.client.editForumTopic({
711
+ chatId: thread.chatId,
712
+ messageThreadId: thread.messageThreadId,
713
+ name: topicName,
714
+ });
715
+ } catch (error) {
716
+ this.logError(error, "Failed to rename claimed Telegram launch topic");
717
+ }
718
+ this.store.record(process, thread);
719
+ return thread;
720
+ }
721
+ try {
722
+ const topic = await this.input.client.createForumTopic({
723
+ chatId: this.input.config.delivery.forumChatId,
724
+ name: topicName,
725
+ });
726
+ const thread: TelegramProcessThread = {
727
+ mode: "forum_topic",
728
+ chatId: this.input.config.delivery.forumChatId,
729
+ messageThreadId: topic.messageThreadId,
730
+ topicName,
731
+ };
732
+ this.store.record(process, thread);
733
+ return thread;
734
+ } catch (error) {
735
+ this.logError(error, "Failed to create Telegram process topic");
736
+ return null;
737
+ }
738
+ }
739
+
740
+ private async getThread(input: ProcessInstance | string): Promise<TelegramProcessThread | null> {
741
+ const instanceId = typeof input === "string" ? input : input.id;
742
+ const existing = this.store.getByInstanceId(instanceId);
743
+ if (existing) return existing;
744
+ if (!this.threadEligibleInstanceIds.has(instanceId)) return null;
745
+ const process = typeof input === "string" ? this.input.deps.processes.getById(input) : input;
746
+ if (!process) return null;
747
+ const thread = await this.ensureThread(process);
748
+ if (thread) await this.sendProcessIntro(thread, process);
749
+ return thread;
750
+ }
751
+
752
+ private async sendProcessIntro(
753
+ thread: TelegramProcessThread,
754
+ process: ProcessInstance,
755
+ ): Promise<void> {
756
+ if (this.introSentInstanceIds.has(process.id)) return;
757
+ await this.sendHtml(
758
+ thread,
759
+ buildProcessCreatedMessage({ process, serverBaseUrl: this.input.deps.serverBaseUrl }),
760
+ );
761
+ this.introSentInstanceIds.add(process.id);
762
+ }
763
+
764
+ private async closeThread(thread: TelegramProcessThread): Promise<void> {
765
+ if (this.closedThreadKeys.has(threadKey(thread.chatId, thread.messageThreadId))) return;
766
+ try {
767
+ await this.input.client.closeForumTopic({
768
+ chatId: thread.chatId,
769
+ messageThreadId: thread.messageThreadId,
770
+ });
771
+ } catch (error) {
772
+ this.logError(error, "Failed to close Telegram process topic");
773
+ }
774
+ }
775
+
776
+ private async syncThreadTitle(
777
+ thread: TelegramProcessThread,
778
+ process: ProcessInstance,
779
+ ): Promise<void> {
780
+ const topicName = buildTopicTitle({ process, template: this.input.config.topicTitleTemplate });
781
+ if (topicName === thread.topicName) return;
782
+ try {
783
+ await this.input.client.editForumTopic({
784
+ chatId: thread.chatId,
785
+ messageThreadId: thread.messageThreadId,
786
+ name: topicName,
787
+ });
788
+ this.store.record(process, { ...thread, topicName });
789
+ } catch (error) {
790
+ this.logError(error, "Failed to rename Telegram process topic");
791
+ }
792
+ }
793
+
794
+ private async sendActionsForProcess(
795
+ process: ProcessInstance,
796
+ options: { explicit?: boolean } = {},
797
+ ): Promise<void> {
798
+ const thread = this.store.getByInstanceId(process.id);
799
+ if (!thread) return;
800
+ const actions =
801
+ process.lifecycleStatus === "waiting"
802
+ ? this.input.deps.processActions.listVisibleActions(process.id)
803
+ : [];
804
+ const isRecoveryOrHumanWait = ["waiting", "error"].includes(process.lifecycleStatus);
805
+ if (!options.explicit && !isRecoveryOrHumanWait && actions.length === 0) return;
806
+ const keyboard = buildActionKeyboard({
807
+ process,
808
+ actions,
809
+ });
810
+ if (!keyboard) {
811
+ if (options.explicit)
812
+ await this.sendHtml(thread, "No actions are available for this process.");
813
+ return;
814
+ }
815
+ const turnInfo = this.lastTurnInfo.get(process.id);
816
+ await this.sendHtml(
817
+ thread,
818
+ buildActionsPromptMessage({
819
+ process,
820
+ actions,
821
+ recoveryActions: recoveryActionLabels(process),
822
+ currentTurnDescription: turnInfo ? formatTurnIdLabel(turnInfo.turnId) : null,
823
+ currentTurnPathType: turnInfo?.pathType ?? null,
824
+ }),
825
+ keyboard,
826
+ );
827
+ }
828
+
829
+ private async handleForumTopicCreated(update: TelegramForumTopicCreatedUpdate): Promise<void> {
830
+ if (!this.isAllowed(update.from)) return;
831
+ if (update.chatId !== this.input.config.delivery.forumChatId) return;
832
+ if (this.store.getInstanceIdForThread(update.chatId, update.messageThreadId)) return;
833
+ await this.sendUnmappedTopicHelp(update.chatId, update.messageThreadId);
834
+ }
835
+
836
+ private async handleForumTopicClosed(update: TelegramForumTopicClosedUpdate): Promise<void> {
837
+ if (update.chatId !== this.input.config.delivery.forumChatId) return;
838
+ const instanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
839
+ if (!instanceId) return;
840
+ this.closedThreadKeys.add(threadKey(update.chatId, update.messageThreadId));
841
+ await this.enqueue(instanceId, () => this.abortProcessForClosedTopic(instanceId));
842
+ }
843
+
844
+ private async abortProcessForClosedTopic(instanceId: string): Promise<void> {
845
+ const process = this.input.deps.processes.getById(instanceId);
846
+ if (!process || processIsFinished(process)) return;
847
+ const result = await this.input.deps.commands.abortProcess(instanceId, {
848
+ actor: TELEGRAM_ACTOR,
849
+ });
850
+ if (!result.ok) {
851
+ this.logError(
852
+ result.message ?? result.code ?? "Abort failed",
853
+ "Failed to abort closed Telegram topic",
854
+ );
855
+ }
856
+ }
857
+
858
+ private async handleText(update: TelegramTextUpdate): Promise<void> {
859
+ if (!this.isAllowed(update.from)) return;
860
+ const name = commandName(update.text);
861
+ const instanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
862
+ if (!instanceId) {
863
+ await this.handleUnmappedTopicText(update, name);
864
+ return;
865
+ }
866
+ await this.enqueue(instanceId, () => this.handleProcessText(instanceId, update, name));
867
+ }
868
+
869
+ private async handleUnmappedTopicText(
870
+ update: TelegramTextUpdate,
871
+ name: string | null,
872
+ ): Promise<void> {
873
+ const key = launchSessionKey(update);
874
+ if (!key) return;
875
+ const inConfiguredForum = update.chatId === this.input.config.delivery.forumChatId;
876
+ if (!inConfiguredForum) {
877
+ if (name === "help") {
878
+ await this.sendPlainToChat(
879
+ update.chatId,
880
+ update.messageThreadId,
881
+ "This bot is operated from the configured process forum chat.",
882
+ );
883
+ }
884
+ return;
885
+ }
886
+ if (name === "cancel") {
887
+ this.launchSessions.delete(key);
888
+ await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Cancelled.");
889
+ return;
890
+ }
891
+ if (name === "help") {
892
+ await this.sendUnmappedTopicHelp(update.chatId, update.messageThreadId);
893
+ return;
894
+ }
895
+ if (name === "launchers") {
896
+ await this.sendLauncherList(update, key, { includeButtons: false });
897
+ return;
898
+ }
899
+ if (name === "launch") {
900
+ if (update.messageThreadId === undefined) {
901
+ await this.sendHtmlToChat(
902
+ update.chatId,
903
+ update.messageThreadId,
904
+ "Create a new forum topic first, then send /launch in that topic.",
905
+ );
906
+ return;
907
+ }
908
+ const launcherId = commandArgs(update.text);
909
+ if (launcherId) {
910
+ await this.startLaunchSession(update, key, launcherId);
911
+ return;
912
+ }
913
+ await this.sendLauncherList(update, key, { includeButtons: true });
914
+ return;
915
+ }
916
+
917
+ const session = this.launchSessions.get(key);
918
+ if (session) {
919
+ await this.handleLaunchSessionText(key, session, update, name);
920
+ return;
921
+ }
922
+ if (name) {
923
+ await this.sendHtmlToChat(
924
+ update.chatId,
925
+ update.messageThreadId,
926
+ "Unknown command. Use /help for available commands.",
927
+ );
928
+ }
929
+ }
930
+
931
+ private async handleProcessText(
932
+ instanceId: string,
933
+ update: TelegramTextUpdate,
934
+ name: string | null,
935
+ ): Promise<void> {
936
+ const thread = this.store.getByInstanceId(instanceId);
937
+ if (!thread) return;
938
+ const key = threadKey(update.chatId, update.messageThreadId);
939
+ if (name === "cancel") {
940
+ if (this.sessions.get(key)?.kind === "question") {
941
+ await this.sendHtml(
942
+ thread,
943
+ "The active turn is still waiting for this answer. Answer here, use the Web UI, or stop the turn.",
944
+ );
945
+ return;
946
+ }
947
+ this.sessions.delete(key);
948
+ await this.sendHtml(thread, "Cancelled.");
949
+ return;
950
+ }
951
+ if (name === "actions") {
952
+ const process = this.input.deps.processes.getById(instanceId);
953
+ if (process) await this.sendActionsForProcess(process, { explicit: true });
954
+ return;
955
+ }
956
+ if (name === "status") {
957
+ const process = this.input.deps.processes.getById(instanceId);
958
+ if (process) {
959
+ const actions =
960
+ process.lifecycleStatus === "waiting"
961
+ ? this.input.deps.processActions.listVisibleActions(process.id)
962
+ : [];
963
+ const turnInfo = this.lastTurnInfo.get(instanceId);
964
+ await this.sendHtml(
965
+ thread,
966
+ buildStatusMessage({
967
+ process,
968
+ actions,
969
+ currentTurnDescription: turnInfo ? formatTurnIdLabel(turnInfo.turnId) : null,
970
+ currentTurnPathType: turnInfo?.pathType ?? null,
971
+ }),
972
+ );
973
+ }
974
+ return;
975
+ }
976
+ if (name === "help") {
977
+ await this.sendHtml(
978
+ thread,
979
+ "Use /actions for current actions, /status for status, /skip to skip optional prompts, /cancel to cancel a pending prompt. Close this topic to abort the process. To launch a new process, create a new topic and send /launch there.",
980
+ );
981
+ return;
982
+ }
983
+ if (name === "launch") {
984
+ await this.sendHtml(
985
+ thread,
986
+ "This topic is already linked to a process. Create a new forum topic and send /launch there to start another process.",
987
+ );
988
+ return;
989
+ }
990
+
991
+ const session = this.sessions.get(key);
992
+ if (session) {
993
+ await this.handleSessionText(key, session, update.text, thread, name);
994
+ return;
995
+ }
996
+ if (name) {
997
+ await this.sendHtml(thread, "Unknown command. Use /help for available commands.");
998
+ return;
999
+ }
1000
+
1001
+ const process = this.input.deps.processes.getById(instanceId);
1002
+ if (!process) return;
1003
+ if (!processCanAcceptFreeText(process)) {
1004
+ await this.sendHtml(
1005
+ thread,
1006
+ "This process is not accepting free-text input right now. Use /actions for available options.",
1007
+ );
1008
+ return;
1009
+ }
1010
+ const result = await this.input.deps.commands.queueInputs(
1011
+ instanceId,
1012
+ [{ source: "external_comment", kind: "instruction", bodyMarkdown: update.text }],
1013
+ {
1014
+ dispatchErrorMessage: "Failed to deliver the Telegram input to the worker",
1015
+ actor: TELEGRAM_ACTOR,
1016
+ },
1017
+ );
1018
+ await this.sendCommandResult(thread, result, "💬 Sent to process.", "Failed to send input");
1019
+ }
1020
+
1021
+ private async handleCallback(update: TelegramCallbackUpdate): Promise<void> {
1022
+ if (!this.isAllowed(update.from)) {
1023
+ await this.answerCallback(update.id, "Not allowed", true);
1024
+ return;
1025
+ }
1026
+ const launchCallback = this.readLaunchCallbackCommand(update.data);
1027
+ if (launchCallback) {
1028
+ const key = launchSessionKey(update);
1029
+ if (!key || key !== launchCallback.command.sessionKey) {
1030
+ await this.answerCallback(
1031
+ update.id,
1032
+ "This launch button belongs to another session.",
1033
+ true,
1034
+ );
1035
+ return;
1036
+ }
1037
+ this.launchCallbacks.delete(launchCallback.token);
1038
+ await this.answerCallback(update.id);
1039
+ await this.executeLaunchCallbackCommand(key, update, launchCallback.command);
1040
+ return;
1041
+ }
1042
+ if (update.data.startsWith(LAUNCH_CALLBACK_PREFIX)) {
1043
+ await this.answerCallback(
1044
+ update.id,
1045
+ "This launch button expired. Send /launch to start again.",
1046
+ true,
1047
+ );
1048
+ return;
1049
+ }
1050
+ const command = parseCallbackCommand(update.data);
1051
+ if (!command) {
1052
+ await this.answerCallback(update.id, "Unknown button. Send /actions to refresh.", true);
1053
+ return;
1054
+ }
1055
+ const resolved = this.resolveCallbackInstance(update, command);
1056
+ if (!resolved.ok) {
1057
+ await this.answerCallback(update.id, resolved.message, true);
1058
+ return;
1059
+ }
1060
+ await this.answerCallback(update.id);
1061
+ await this.enqueue(resolved.instanceId, () =>
1062
+ this.executeCallbackCommand(resolved.instanceId, command),
1063
+ );
1064
+ }
1065
+
1066
+ private resolveCallbackInstance(
1067
+ update: TelegramCallbackUpdate,
1068
+ command: TelegramCallbackCommand,
1069
+ ): { ok: true; instanceId: string } | { ok: false; message: string } {
1070
+ const threadInstanceId = this.store.getInstanceIdForThread(
1071
+ update.chatId,
1072
+ update.messageThreadId,
1073
+ );
1074
+ if (!threadInstanceId) {
1075
+ return { ok: false, message: "This button is not in a process topic." };
1076
+ }
1077
+ if (command.instanceId !== threadInstanceId) {
1078
+ return { ok: false, message: "This button belongs to another process topic." };
1079
+ }
1080
+ return { ok: true, instanceId: threadInstanceId };
1081
+ }
1082
+
1083
+ private async answerCallback(id: string, text?: string, showAlert?: boolean): Promise<void> {
1084
+ await this.input.client.answerCallbackQuery({
1085
+ callbackQueryId: id,
1086
+ ...(text ? { text } : {}),
1087
+ ...(showAlert !== undefined ? { showAlert } : {}),
1088
+ });
1089
+ }
1090
+
1091
+ private getLauncher(launcherId: string): UiLauncherSummary | null {
1092
+ return (
1093
+ this.input.deps.launcherService
1094
+ .listUiLaunchers()
1095
+ .find((launcher) => launcher.id === launcherId) ?? null
1096
+ );
1097
+ }
1098
+
1099
+ private async sendUnmappedTopicHelp(
1100
+ chatId: string,
1101
+ messageThreadId: number | undefined,
1102
+ ): Promise<void> {
1103
+ await this.sendHtmlToChat(
1104
+ chatId,
1105
+ messageThreadId,
1106
+ [
1107
+ "This topic can become a new leitwerk process.",
1108
+ "Send /launch to choose a process launcher, then answer the prompts here.",
1109
+ "Required fields are asked first; optional fields come after and can be skipped with /skip.",
1110
+ "Use /launchers to list launcher ids, or /cancel to discard a pending launch draft.",
1111
+ ].join("\n"),
1112
+ );
1113
+ }
1114
+
1115
+ private async sendLauncherList(
1116
+ update: TelegramTextUpdate,
1117
+ sessionKey: string,
1118
+ options: { includeButtons: boolean },
1119
+ ): Promise<void> {
1120
+ const launchers = this.input.deps.launcherService.listUiLaunchers();
1121
+ if (launchers.length === 0) {
1122
+ await this.sendHtmlToChat(
1123
+ update.chatId,
1124
+ update.messageThreadId,
1125
+ "No launchers are available.",
1126
+ );
1127
+ return;
1128
+ }
1129
+ const lines = ["Available launchers:", ""];
1130
+ for (const launcher of launchers) {
1131
+ const description = launcher.description.trim();
1132
+ lines.push(
1133
+ description
1134
+ ? `- ${launcher.label} (${launcher.id}) — ${description}`
1135
+ : `- ${launcher.label} (${launcher.id})`,
1136
+ );
1137
+ }
1138
+ if (launchers.length > MAX_LAUNCHER_BUTTONS && options.includeButtons) {
1139
+ lines.push(
1140
+ "",
1141
+ `Showing buttons for the first ${MAX_LAUNCHER_BUTTONS}. Use /launch <launcherId> for others.`,
1142
+ );
1143
+ }
1144
+ await this.sendHtmlToChat(
1145
+ update.chatId,
1146
+ update.messageThreadId,
1147
+ escapeHtml(lines.join("\n")),
1148
+ options.includeButtons ? this.buildLauncherListKeyboard(launchers, sessionKey) : undefined,
1149
+ );
1150
+ }
1151
+
1152
+ private async startLaunchSession(
1153
+ update: TelegramTextUpdate | TelegramCallbackUpdate,
1154
+ sessionKey: string,
1155
+ launcherId: string,
1156
+ ): Promise<void> {
1157
+ if (update.chatId !== this.input.config.delivery.forumChatId) {
1158
+ await this.sendHtmlToChat(
1159
+ update.chatId,
1160
+ update.messageThreadId,
1161
+ "Launches are only available from the configured process forum chat.",
1162
+ );
1163
+ return;
1164
+ }
1165
+ if (update.messageThreadId === undefined) {
1166
+ await this.sendHtmlToChat(
1167
+ update.chatId,
1168
+ update.messageThreadId,
1169
+ "Create a new forum topic first, then send /launch in that topic.",
1170
+ );
1171
+ return;
1172
+ }
1173
+ const launcher = this.getLauncher(launcherId);
1174
+ if (!launcher) {
1175
+ await this.sendHtmlToChat(
1176
+ update.chatId,
1177
+ update.messageThreadId,
1178
+ `Unknown launcher: ${escapeHtml(launcherId)}`,
1179
+ );
1180
+ return;
1181
+ }
1182
+ let defaults: Record<string, unknown>;
1183
+ try {
1184
+ defaults = await this.input.deps.launcherService.resolveUiDefaults(launcher.id);
1185
+ } catch (error) {
1186
+ this.logError(error, "Failed to resolve Telegram launcher defaults");
1187
+ await this.sendHtmlToChat(
1188
+ update.chatId,
1189
+ update.messageThreadId,
1190
+ "Couldn't load launcher defaults. Try /launch again later.",
1191
+ );
1192
+ return;
1193
+ }
1194
+ const session = createLaunchSession({
1195
+ launcher,
1196
+ defaults,
1197
+ ttlMs: LAUNCH_SESSION_TTL_MS,
1198
+ });
1199
+ this.launchSessions.set(sessionKey, session);
1200
+ await this.sendHtmlToChat(
1201
+ update.chatId,
1202
+ update.messageThreadId,
1203
+ `Starting launcher: ${escapeHtml(launcher.label)}. I’ll ask required fields first, then optional fields. Use /skip for optional/defaulted fields and /cancel to discard this draft.`,
1204
+ );
1205
+ await this.sendNextLaunchPrompt(sessionKey, session, update);
1206
+ }
1207
+
1208
+ private async handleLaunchSessionText(
1209
+ sessionKey: string,
1210
+ session: PendingLaunchSession,
1211
+ update: TelegramTextUpdate,
1212
+ name: string | null,
1213
+ ): Promise<void> {
1214
+ if (session.expiresAt < Date.now()) {
1215
+ this.launchSessions.delete(sessionKey);
1216
+ await this.sendHtmlToChat(
1217
+ update.chatId,
1218
+ update.messageThreadId,
1219
+ "This launch draft expired. Send /launch to start again.",
1220
+ );
1221
+ return;
1222
+ }
1223
+ if (name && name !== "skip") {
1224
+ await this.sendHtmlToChat(
1225
+ update.chatId,
1226
+ update.messageThreadId,
1227
+ "Finish this launch prompt, or send /cancel to discard it.",
1228
+ );
1229
+ return;
1230
+ }
1231
+ const launcher = this.getLauncher(session.launcherId);
1232
+ if (!launcher) {
1233
+ this.launchSessions.delete(sessionKey);
1234
+ await this.sendHtmlToChat(
1235
+ update.chatId,
1236
+ update.messageThreadId,
1237
+ "This launcher is no longer available. Send /launch to choose another.",
1238
+ );
1239
+ return;
1240
+ }
1241
+ if (session.modelEdit) {
1242
+ await this.handleLaunchModelText(sessionKey, session, update);
1243
+ return;
1244
+ }
1245
+ const optionsById = await this.resolveLaunchOptions(session);
1246
+ const step = applyLaunchFieldText(session, launcher, update.text, optionsById);
1247
+ if (!step.ok) {
1248
+ await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeHtml(step.prompt));
1249
+ return;
1250
+ }
1251
+ if (step.done) {
1252
+ await this.sendLaunchReview(sessionKey, session, launcher, update);
1253
+ return;
1254
+ }
1255
+ await this.sendNextLaunchPrompt(sessionKey, session, update);
1256
+ }
1257
+
1258
+ private async executeLaunchCallbackCommand(
1259
+ sessionKey: string,
1260
+ update: TelegramCallbackUpdate,
1261
+ command: TelegramLaunchCallbackCommand,
1262
+ ): Promise<void> {
1263
+ switch (command.kind) {
1264
+ case "select_launcher":
1265
+ await this.startLaunchSession(update, sessionKey, command.launcherId);
1266
+ return;
1267
+ case "cancel_launch":
1268
+ this.launchSessions.delete(sessionKey);
1269
+ await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Cancelled.");
1270
+ return;
1271
+ case "edit_models":
1272
+ await this.startLaunchModelEdit(sessionKey, update);
1273
+ return;
1274
+ case "model_step":
1275
+ await this.executeLaunchModelCallbackCommand(sessionKey, update, command);
1276
+ return;
1277
+ case "finish_model_edit":
1278
+ await this.finishLaunchModelEdit(sessionKey, update);
1279
+ return;
1280
+ case "confirm_launch": {
1281
+ const session = await this.getActiveLaunchSession(sessionKey, update);
1282
+ if (!session) return;
1283
+ if (session.modelEdit) {
1284
+ await this.sendHtmlToChat(
1285
+ update.chatId,
1286
+ update.messageThreadId,
1287
+ "Finish model setup before starting this process.",
1288
+ );
1289
+ await this.sendNextLaunchModelPrompt(sessionKey, session, update);
1290
+ return;
1291
+ }
1292
+ await this.executeLaunchSession(sessionKey, session, update);
1293
+ return;
1294
+ }
1295
+ case "field_value":
1296
+ case "skip_field": {
1297
+ const context = await this.getLaunchContext(sessionKey, update);
1298
+ if (!context) return;
1299
+ const { session, launcher } = context;
1300
+ const field = currentLaunchField(session, launcher);
1301
+ if (!field || field.id !== command.fieldId) {
1302
+ await this.sendHtmlToChat(
1303
+ update.chatId,
1304
+ update.messageThreadId,
1305
+ "That launch button is stale. Continue with the latest prompt or send /cancel.",
1306
+ );
1307
+ return;
1308
+ }
1309
+ const optionsById = await this.resolveLaunchOptions(session);
1310
+ const step =
1311
+ command.kind === "skip_field"
1312
+ ? applyLaunchFieldText(session, launcher, "/skip", optionsById)
1313
+ : applyLaunchFieldValue(session, launcher, command.value, optionsById);
1314
+ if (!step.ok) {
1315
+ await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeHtml(step.prompt));
1316
+ return;
1317
+ }
1318
+ if (step.done) {
1319
+ await this.sendLaunchReview(sessionKey, session, launcher, update);
1320
+ return;
1321
+ }
1322
+ await this.sendNextLaunchPrompt(sessionKey, session, update);
1323
+ return;
1324
+ }
1325
+ }
1326
+ }
1327
+
1328
+ private async getLaunchModelSchema(
1329
+ session: PendingLaunchSession,
1330
+ ): Promise<LauncherModelConfigSchemaLike | null> {
1331
+ try {
1332
+ const schema = await this.input.deps.launcherModelConfigs.getSchema(session.launcherId);
1333
+ return this.filterLaunchSchemaAvailableProfiles(schema);
1334
+ } catch (error) {
1335
+ this.logError(error, "Failed to resolve Telegram launcher model schema");
1336
+ return null;
1337
+ }
1338
+ }
1339
+
1340
+ private async getLaunchModelPreview(
1341
+ session: PendingLaunchSession,
1342
+ ): Promise<LauncherModelConfigPreviewLike | null> {
1343
+ try {
1344
+ return await this.input.deps.launcherModelConfigs.preview(
1345
+ session.launcherId,
1346
+ buildLaunchInput(session),
1347
+ { modelConfig: buildLaunchModelConfig(session) },
1348
+ );
1349
+ } catch (error) {
1350
+ this.logError(error, "Failed to resolve Telegram launcher model preview");
1351
+ return null;
1352
+ }
1353
+ }
1354
+
1355
+ private async getActiveLaunchSession(
1356
+ sessionKey: string,
1357
+ target: ChatTarget,
1358
+ ): Promise<PendingLaunchSession | null> {
1359
+ const session = this.launchSessions.get(sessionKey);
1360
+ if (session && session.expiresAt >= Date.now()) return session;
1361
+ if (session) this.launchSessions.delete(sessionKey);
1362
+ await this.sendHtmlToChat(
1363
+ target.chatId,
1364
+ target.messageThreadId,
1365
+ "This launch draft expired. Send /launch to start again.",
1366
+ );
1367
+ return null;
1368
+ }
1369
+
1370
+ private async getLaunchContext(
1371
+ sessionKey: string,
1372
+ target: ChatTarget,
1373
+ ): Promise<{ session: PendingLaunchSession; launcher: UiLauncherSummary } | null> {
1374
+ const session = await this.getActiveLaunchSession(sessionKey, target);
1375
+ if (!session) return null;
1376
+ const launcher = this.getLauncher(session.launcherId);
1377
+ if (launcher) return { session, launcher };
1378
+ this.launchSessions.delete(sessionKey);
1379
+ await this.sendHtmlToChat(
1380
+ target.chatId,
1381
+ target.messageThreadId,
1382
+ "This launcher is no longer available. Send /launch to choose another.",
1383
+ );
1384
+ return null;
1385
+ }
1386
+
1387
+ private async sendLaunchReviewForSession(
1388
+ sessionKey: string,
1389
+ session: PendingLaunchSession,
1390
+ target: ChatTarget,
1391
+ ): Promise<void> {
1392
+ const launcher = this.getLauncher(session.launcherId);
1393
+ if (!launcher) {
1394
+ this.launchSessions.delete(sessionKey);
1395
+ await this.sendHtmlToChat(
1396
+ target.chatId,
1397
+ target.messageThreadId,
1398
+ "This launcher is no longer available. Send /launch to choose another.",
1399
+ );
1400
+ return;
1401
+ }
1402
+ await this.sendLaunchReview(sessionKey, session, launcher, target);
1403
+ }
1404
+
1405
+ private async finishLaunchModelEditAndReview(
1406
+ sessionKey: string,
1407
+ session: PendingLaunchSession,
1408
+ target: ChatTarget,
1409
+ ): Promise<void> {
1410
+ finishLaunchModelEdit(session);
1411
+ await this.sendLaunchReviewForSession(sessionKey, session, target);
1412
+ }
1413
+
1414
+ private async startLaunchModelEdit(sessionKey: string, target: ChatTarget): Promise<void> {
1415
+ const session = await this.getActiveLaunchSession(sessionKey, target);
1416
+ if (!session) return;
1417
+ const schema = await this.getLaunchModelSchema(session);
1418
+ if (!hasLaunchModelControls(schema)) {
1419
+ await this.sendHtmlToChat(
1420
+ target.chatId,
1421
+ target.messageThreadId,
1422
+ "This launcher has no editable model setup.",
1423
+ );
1424
+ return;
1425
+ }
1426
+ beginLaunchModelEdit(session, schema);
1427
+ await this.sendNextLaunchModelPrompt(sessionKey, session, target);
1428
+ }
1429
+
1430
+ private async executeLaunchModelCallbackCommand(
1431
+ sessionKey: string,
1432
+ target: ChatTarget,
1433
+ command: Extract<TelegramLaunchCallbackCommand, { kind: "model_step" }>,
1434
+ ): Promise<void> {
1435
+ const session = await this.getActiveLaunchSession(sessionKey, target);
1436
+ if (!session) return;
1437
+ const schema = await this.getLaunchModelSchema(session);
1438
+ if (!hasLaunchModelControls(schema)) {
1439
+ await this.finishLaunchModelEditAndReview(sessionKey, session, target);
1440
+ return;
1441
+ }
1442
+ const step = currentLaunchModelStep(session, schema);
1443
+ if (!step || step.key !== command.stepKey) {
1444
+ await this.sendHtmlToChat(
1445
+ target.chatId,
1446
+ target.messageThreadId,
1447
+ "That model button is stale. Continue with the latest prompt or send /cancel.",
1448
+ );
1449
+ await this.sendNextLaunchModelPrompt(sessionKey, session, target);
1450
+ return;
1451
+ }
1452
+ const action: LaunchModelStepAction =
1453
+ command.action === "set"
1454
+ ? { action: "set", value: command.value }
1455
+ : command.action === "inherit"
1456
+ ? { action: "inherit" }
1457
+ : { action: "skip" };
1458
+ await this.continueAfterLaunchModelResult(
1459
+ sessionKey,
1460
+ session,
1461
+ schema,
1462
+ applyLaunchModelStepAction(session, schema, action),
1463
+ target,
1464
+ );
1465
+ }
1466
+
1467
+ private async finishLaunchModelEdit(sessionKey: string, target: ChatTarget): Promise<void> {
1468
+ const session = await this.getActiveLaunchSession(sessionKey, target);
1469
+ if (session) await this.finishLaunchModelEditAndReview(sessionKey, session, target);
1470
+ }
1471
+
1472
+ private async handleLaunchModelText(
1473
+ sessionKey: string,
1474
+ session: PendingLaunchSession,
1475
+ update: TelegramTextUpdate,
1476
+ ): Promise<void> {
1477
+ const schema = await this.getLaunchModelSchema(session);
1478
+ if (!hasLaunchModelControls(schema)) {
1479
+ await this.finishLaunchModelEditAndReview(sessionKey, session, update);
1480
+ return;
1481
+ }
1482
+ await this.continueAfterLaunchModelResult(
1483
+ sessionKey,
1484
+ session,
1485
+ schema,
1486
+ applyLaunchModelStepText(session, schema, update.text),
1487
+ update,
1488
+ );
1489
+ }
1490
+
1491
+ private async continueAfterLaunchModelResult(
1492
+ sessionKey: string,
1493
+ session: PendingLaunchSession,
1494
+ schema: LauncherModelConfigSchemaLike,
1495
+ result: LaunchModelStepResult,
1496
+ target: ChatTarget,
1497
+ ): Promise<void> {
1498
+ if (!result.ok) {
1499
+ const step = currentLaunchModelStep(session, schema);
1500
+ await this.sendHtmlToChat(
1501
+ target.chatId,
1502
+ target.messageThreadId,
1503
+ escapeHtml(result.prompt),
1504
+ step ? this.buildLaunchModelReplyMarkup({ sessionKey, step, schema }) : undefined,
1505
+ );
1506
+ return;
1507
+ }
1508
+ if (result.done) {
1509
+ await this.sendLaunchReviewForSession(sessionKey, session, target);
1510
+ return;
1511
+ }
1512
+ await this.sendNextLaunchModelPrompt(sessionKey, session, target);
1513
+ }
1514
+
1515
+ private resolveLaunchRecentValues(
1516
+ session: PendingLaunchSession,
1517
+ ): Record<string, readonly string[]> {
1518
+ try {
1519
+ return this.input.deps.launcherRecentValues.list(session.launcherId);
1520
+ } catch (error) {
1521
+ this.logError(error, "Failed to resolve Telegram launcher recent values");
1522
+ return {};
1523
+ }
1524
+ }
1525
+
1526
+ private recordLaunchRecentValuesBestEffort(session: PendingLaunchSession): void {
1527
+ try {
1528
+ this.input.deps.launcherRecentValues.record(session.launcherId, buildLaunchInput(session));
1529
+ } catch (error) {
1530
+ this.logError(error, "Failed to record Telegram launcher recent values");
1531
+ }
1532
+ }
1533
+
1534
+ private async resolveLaunchOptions(
1535
+ session: PendingLaunchSession,
1536
+ ): Promise<LaunchFieldOptionsById> {
1537
+ const launcher = this.getLauncher(session.launcherId);
1538
+ if (!launcher?.launchConfigSchema.fields.some((field) => field.kind === "select")) {
1539
+ return {};
1540
+ }
1541
+ try {
1542
+ return await this.input.deps.launcherService.resolveUiOptions(
1543
+ session.launcherId,
1544
+ buildLaunchInput(session),
1545
+ );
1546
+ } catch (error) {
1547
+ this.logError(error, "Failed to resolve Telegram launch field options");
1548
+ return {};
1549
+ }
1550
+ }
1551
+
1552
+ private async sendNextLaunchModelPrompt(
1553
+ sessionKey: string,
1554
+ session: PendingLaunchSession,
1555
+ target: ChatTarget,
1556
+ ): Promise<void> {
1557
+ const schema = await this.getLaunchModelSchema(session);
1558
+ if (!hasLaunchModelControls(schema)) {
1559
+ await this.finishLaunchModelEditAndReview(sessionKey, session, target);
1560
+ return;
1561
+ }
1562
+ const step = currentLaunchModelStep(session, schema);
1563
+ if (!step) {
1564
+ await this.sendLaunchReviewForSession(sessionKey, session, target);
1565
+ return;
1566
+ }
1567
+ const preview = await this.getLaunchModelPreview(session);
1568
+ const prompt = buildLaunchModelStepPrompt({ step, schema, session, preview });
1569
+ await this.sendHtmlToChat(
1570
+ target.chatId,
1571
+ target.messageThreadId,
1572
+ escapeHtml(prompt),
1573
+ this.buildLaunchModelReplyMarkup({ sessionKey, step, schema }),
1574
+ );
1575
+ }
1576
+
1577
+ private async sendNextLaunchPrompt(
1578
+ sessionKey: string,
1579
+ session: PendingLaunchSession,
1580
+ target: ChatTarget,
1581
+ ): Promise<void> {
1582
+ if (session.modelEdit) {
1583
+ await this.sendNextLaunchModelPrompt(sessionKey, session, target);
1584
+ return;
1585
+ }
1586
+ const launcher = this.getLauncher(session.launcherId);
1587
+ if (!launcher) return;
1588
+ const field = currentLaunchField(session, launcher);
1589
+ if (!field) {
1590
+ await this.sendLaunchReview(sessionKey, session, launcher, target);
1591
+ return;
1592
+ }
1593
+ const optionsById = await this.resolveLaunchOptions(session);
1594
+ const recentValuesById = this.resolveLaunchRecentValues(session);
1595
+ const fieldOptions = getLaunchFieldOptions(field, optionsById);
1596
+ const fieldRecentValues = recentValuesById[field.id] ?? [];
1597
+ const prompt = buildLaunchFieldPrompt({
1598
+ field,
1599
+ currentValue: session.values[field.id],
1600
+ options: fieldOptions,
1601
+ recentValues: fieldRecentValues,
1602
+ });
1603
+ await this.sendHtmlToChat(
1604
+ target.chatId,
1605
+ target.messageThreadId,
1606
+ escapeHtml(prompt),
1607
+ this.buildLaunchFieldReplyMarkup({
1608
+ sessionKey,
1609
+ fieldId: field.id,
1610
+ fieldKind: field.kind,
1611
+ currentValue: session.values[field.id],
1612
+ options: fieldOptions,
1613
+ recentValues: fieldRecentValues,
1614
+ required: field.required,
1615
+ }),
1616
+ );
1617
+ }
1618
+
1619
+ private async sendLaunchReview(
1620
+ sessionKey: string,
1621
+ session: PendingLaunchSession,
1622
+ launcher: UiLauncherSummary,
1623
+ target: ChatTarget,
1624
+ ): Promise<void> {
1625
+ const prepared = await this.prepareLaunchSession(session, launcher);
1626
+ if (!prepared.ok) {
1627
+ await this.sendHtmlToChat(
1628
+ target.chatId,
1629
+ target.messageThreadId,
1630
+ escapeHtml(prepared.message),
1631
+ );
1632
+ if (prepared.reprompt) await this.sendNextLaunchPrompt(sessionKey, session, target);
1633
+ return;
1634
+ }
1635
+ const schema = await this.getLaunchModelSchema(session);
1636
+ const modelSummary = hasLaunchModelControls(schema)
1637
+ ? buildLaunchModelSummary({
1638
+ schema,
1639
+ session,
1640
+ preview: await this.getLaunchModelPreview(session),
1641
+ })
1642
+ : null;
1643
+ await this.sendHtmlToChat(
1644
+ target.chatId,
1645
+ target.messageThreadId,
1646
+ escapeHtml(
1647
+ [
1648
+ buildLaunchReview({ launcher, session }),
1649
+ ...(modelSummary ? ["", modelSummary] : []),
1650
+ ].join("\n"),
1651
+ ),
1652
+ this.buildLaunchConfirmationKeyboard(sessionKey, Boolean(modelSummary)),
1653
+ );
1654
+ }
1655
+
1656
+ private async prepareLaunchSession(
1657
+ session: PendingLaunchSession,
1658
+ launcher: UiLauncherSummary,
1659
+ ): Promise<
1660
+ { ok: true; launchPlan: ProcessLaunchPlan } | { ok: false; message: string; reprompt: boolean }
1661
+ > {
1662
+ let resolved: Awaited<ReturnType<CoreServerSetupDeps["launcherService"]["resolveUiLauncher"]>>;
1663
+ try {
1664
+ resolved = await this.input.deps.launcherService.resolveUiLauncher(
1665
+ launcher.id,
1666
+ buildLaunchInput(session),
1667
+ );
1668
+ } catch (error) {
1669
+ this.logError(error, "Failed to resolve Telegram launcher input");
1670
+ return {
1671
+ ok: false,
1672
+ message: "Couldn't validate launcher input. Try again or send /cancel.",
1673
+ reprompt: false,
1674
+ };
1675
+ }
1676
+ if (!resolved.ok) {
1677
+ const field = moveLaunchSessionToValidationField(session, launcher, resolved.errors);
1678
+ return {
1679
+ ok: false,
1680
+ message:
1681
+ resolved.errors.map((error) => error.message).join("\n") || "Launcher input is invalid.",
1682
+ reprompt: Boolean(field),
1683
+ };
1684
+ }
1685
+ let prepared: Awaited<ReturnType<CoreServerSetupDeps["launchPlans"]["prepare"]>>;
1686
+ try {
1687
+ prepared = await this.input.deps.launchPlans.prepare(resolved.launcher.launchPlan, {
1688
+ ...(session.modelConfigTouched
1689
+ ? { modelConfig: buildLaunchModelConfig(session), replaceModelConfig: true }
1690
+ : {}),
1691
+ });
1692
+ } catch (error) {
1693
+ this.logError(error, "Failed to prepare Telegram launch plan");
1694
+ return {
1695
+ ok: false,
1696
+ message: "Couldn't prepare this launch. Try again or send /cancel.",
1697
+ reprompt: false,
1698
+ };
1699
+ }
1700
+ if (!prepared.ok) {
1701
+ return {
1702
+ ok: false,
1703
+ message:
1704
+ prepared.errors.map((error) => error.message).join("\n") ||
1705
+ "Launch configuration is invalid.",
1706
+ reprompt: false,
1707
+ };
1708
+ }
1709
+ seedLaunchModelConfigFromPlan(session, prepared.launchPlan);
1710
+ return { ok: true, launchPlan: prepared.launchPlan };
1711
+ }
1712
+
1713
+ private async executeLaunchSession(
1714
+ sessionKey: string,
1715
+ session: PendingLaunchSession,
1716
+ target: ChatTarget,
1717
+ ): Promise<void> {
1718
+ const { chatId, messageThreadId } = target;
1719
+ const launcher = this.getLauncher(session.launcherId);
1720
+ if (!launcher) {
1721
+ this.launchSessions.delete(sessionKey);
1722
+ await this.sendHtmlToChat(
1723
+ chatId,
1724
+ messageThreadId,
1725
+ "This launcher is no longer available. Send /launch to choose another.",
1726
+ );
1727
+ return;
1728
+ }
1729
+ const prepared = await this.prepareLaunchSession(session, launcher);
1730
+ if (!prepared.ok) {
1731
+ await this.sendHtmlToChat(chatId, messageThreadId, escapeHtml(prepared.message));
1732
+ if (prepared.reprompt) await this.sendNextLaunchPrompt(sessionKey, session, target);
1733
+ return;
1734
+ }
1735
+ if (messageThreadId === undefined) {
1736
+ await this.sendHtmlToChat(
1737
+ chatId,
1738
+ messageThreadId,
1739
+ "Create a new forum topic first, then send /launch in that topic.",
1740
+ );
1741
+ return;
1742
+ }
1743
+ const launchPlan = attachLaunchThreadMetadata(prepared.launchPlan, {
1744
+ mode: "forum_topic",
1745
+ chatId,
1746
+ messageThreadId,
1747
+ });
1748
+ let result: Awaited<
1749
+ ReturnType<CoreServerSetupDeps["processLaunches"]["createProcessFromLaunchPlan"]>
1750
+ >;
1751
+ try {
1752
+ result = await this.input.deps.processLaunches.createProcessFromLaunchPlan(launchPlan, {
1753
+ actor: TELEGRAM_ACTOR,
1754
+ });
1755
+ } catch (error) {
1756
+ this.logError(error, "Failed to create Telegram-launched process");
1757
+ await this.sendHtmlToChat(
1758
+ chatId,
1759
+ messageThreadId,
1760
+ "Couldn't create this process. Try again or send /cancel.",
1761
+ );
1762
+ return;
1763
+ }
1764
+ if (result.ok) {
1765
+ this.recordLaunchRecentValuesBestEffort(session);
1766
+ this.launchSessions.delete(sessionKey);
1767
+ await this.sendHtmlToChat(
1768
+ chatId,
1769
+ messageThreadId,
1770
+ `✅ Process launched. Web UI: ${escapeHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${result.process.id}`)}`,
1771
+ );
1772
+ return;
1773
+ }
1774
+ const process = "process" in result ? result.process : null;
1775
+ if (process) {
1776
+ this.recordLaunchRecentValuesBestEffort(session);
1777
+ this.launchSessions.delete(sessionKey);
1778
+ await this.sendHtmlToChat(
1779
+ chatId,
1780
+ messageThreadId,
1781
+ `⚠️ Process was created but launch had a follow-up problem. Web UI: ${escapeHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${process.id}`)}`,
1782
+ );
1783
+ return;
1784
+ }
1785
+ await this.sendHtmlToChat(
1786
+ chatId,
1787
+ messageThreadId,
1788
+ `⚠️ ${escapeHtml(String(result.body.error ?? "Launch failed"))}`,
1789
+ );
1790
+ }
1791
+
1792
+ private createLaunchCallbackCommand(command: TelegramLaunchCallbackCommand): string {
1793
+ const token = `${Date.now().toString(36)}_${(this.nextLaunchCallbackId++).toString(36)}`;
1794
+ this.launchCallbacks.set(token, {
1795
+ command,
1796
+ expiresAt: Date.now() + LAUNCH_SESSION_TTL_MS,
1797
+ });
1798
+ return `${LAUNCH_CALLBACK_PREFIX}${token}`;
1799
+ }
1800
+
1801
+ private readLaunchCallbackCommand(data: string): ResolvedLaunchCallbackCommand | null {
1802
+ if (!data.startsWith(LAUNCH_CALLBACK_PREFIX)) return null;
1803
+ const token = data.slice(LAUNCH_CALLBACK_PREFIX.length);
1804
+ const stored = this.launchCallbacks.get(token);
1805
+ if (!stored) return null;
1806
+ if (stored.expiresAt < Date.now()) {
1807
+ this.launchCallbacks.delete(token);
1808
+ return null;
1809
+ }
1810
+ return { token, command: stored.command };
1811
+ }
1812
+
1813
+ private buildLauncherListKeyboard(
1814
+ launchers: readonly UiLauncherSummary[],
1815
+ sessionKey: string,
1816
+ ): TelegramInlineKeyboard | undefined {
1817
+ const buttons = launchers.slice(0, MAX_LAUNCHER_BUTTONS).map((launcher) => ({
1818
+ text: launcher.label,
1819
+ callbackData: this.createLaunchCallbackCommand({
1820
+ kind: "select_launcher",
1821
+ sessionKey,
1822
+ launcherId: launcher.id,
1823
+ }),
1824
+ }));
1825
+ return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
1826
+ }
1827
+
1828
+ private buildLaunchConfirmationKeyboard(
1829
+ sessionKey: string,
1830
+ includeModelControls: boolean,
1831
+ ): TelegramInlineKeyboard {
1832
+ return {
1833
+ inlineKeyboard: [
1834
+ [
1835
+ {
1836
+ text: "Start process",
1837
+ callbackData: this.createLaunchCallbackCommand({
1838
+ kind: "confirm_launch",
1839
+ sessionKey,
1840
+ }),
1841
+ },
1842
+ {
1843
+ text: "Cancel",
1844
+ callbackData: this.createLaunchCallbackCommand({
1845
+ kind: "cancel_launch",
1846
+ sessionKey,
1847
+ }),
1848
+ },
1849
+ ],
1850
+ ...(includeModelControls
1851
+ ? [
1852
+ [
1853
+ {
1854
+ text: "Change models",
1855
+ callbackData: this.createLaunchCallbackCommand({
1856
+ kind: "edit_models",
1857
+ sessionKey,
1858
+ }),
1859
+ },
1860
+ ],
1861
+ ]
1862
+ : []),
1863
+ ],
1864
+ };
1865
+ }
1866
+
1867
+ private buildLaunchModelReplyMarkup(input: {
1868
+ sessionKey: string;
1869
+ step: LaunchModelStep;
1870
+ schema: LauncherModelConfigSchemaLike;
1871
+ }): TelegramInlineKeyboard {
1872
+ const buttons: Array<{ text: string; callbackData: string }> = [];
1873
+ for (const profile of input.schema.availableProfiles.slice(0, MAX_MODEL_PROFILE_BUTTONS)) {
1874
+ buttons.push({
1875
+ text: profile.id,
1876
+ callbackData: this.createLaunchCallbackCommand({
1877
+ kind: "model_step",
1878
+ sessionKey: input.sessionKey,
1879
+ stepKey: input.step.key,
1880
+ action: "set",
1881
+ value: profile.id,
1882
+ }),
1883
+ });
1884
+ }
1885
+ buttons.push(
1886
+ {
1887
+ text: "Inherit",
1888
+ callbackData: this.createLaunchCallbackCommand({
1889
+ kind: "model_step",
1890
+ sessionKey: input.sessionKey,
1891
+ stepKey: input.step.key,
1892
+ action: "inherit",
1893
+ }),
1894
+ },
1895
+ {
1896
+ text: "Keep current",
1897
+ callbackData: this.createLaunchCallbackCommand({
1898
+ kind: "model_step",
1899
+ sessionKey: input.sessionKey,
1900
+ stepKey: input.step.key,
1901
+ action: "skip",
1902
+ }),
1903
+ },
1904
+ {
1905
+ text: "Done",
1906
+ callbackData: this.createLaunchCallbackCommand({
1907
+ kind: "finish_model_edit",
1908
+ sessionKey: input.sessionKey,
1909
+ }),
1910
+ },
1911
+ );
1912
+ return { inlineKeyboard: rows(buttons, 1) };
1913
+ }
1914
+
1915
+ private buildLaunchFieldReplyMarkup(input: {
1916
+ sessionKey: string;
1917
+ fieldId: string;
1918
+ fieldKind: string;
1919
+ currentValue: unknown;
1920
+ options: readonly LauncherFieldOptionDefinition[];
1921
+ recentValues: readonly string[];
1922
+ required?: boolean;
1923
+ }): TelegramReplyMarkup | undefined {
1924
+ const buttons: Array<{ text: string; callbackData: string }> = [];
1925
+ if (input.fieldKind === "boolean") {
1926
+ buttons.push(
1927
+ {
1928
+ text: "Yes",
1929
+ callbackData: this.createLaunchCallbackCommand({
1930
+ kind: "field_value",
1931
+ sessionKey: input.sessionKey,
1932
+ fieldId: input.fieldId,
1933
+ value: true,
1934
+ }),
1935
+ },
1936
+ {
1937
+ text: "No",
1938
+ callbackData: this.createLaunchCallbackCommand({
1939
+ kind: "field_value",
1940
+ sessionKey: input.sessionKey,
1941
+ fieldId: input.fieldId,
1942
+ value: false,
1943
+ }),
1944
+ },
1945
+ );
1946
+ } else if (input.fieldKind === "select") {
1947
+ for (const option of input.options.slice(0, MAX_FIELD_OPTION_BUTTONS)) {
1948
+ buttons.push({
1949
+ text: option.label,
1950
+ callbackData: this.createLaunchCallbackCommand({
1951
+ kind: "field_value",
1952
+ sessionKey: input.sessionKey,
1953
+ fieldId: input.fieldId,
1954
+ value: option.value,
1955
+ }),
1956
+ });
1957
+ }
1958
+ } else {
1959
+ for (const value of input.recentValues.slice(0, MAX_FIELD_OPTION_BUTTONS)) {
1960
+ buttons.push({
1961
+ text: this.formatRecentValueButtonText(value),
1962
+ callbackData: this.createLaunchCallbackCommand({
1963
+ kind: "field_value",
1964
+ sessionKey: input.sessionKey,
1965
+ fieldId: input.fieldId,
1966
+ value,
1967
+ }),
1968
+ });
1969
+ }
1970
+ }
1971
+ const hasCurrentValue =
1972
+ typeof input.currentValue === "boolean" ||
1973
+ (typeof input.currentValue === "number" && Number.isFinite(input.currentValue)) ||
1974
+ (typeof input.currentValue === "string" && input.currentValue.trim() !== "");
1975
+ if (
1976
+ input.fieldKind !== "boolean" &&
1977
+ input.fieldKind !== "select" &&
1978
+ input.required &&
1979
+ !hasCurrentValue &&
1980
+ buttons.length === 0
1981
+ ) {
1982
+ return {
1983
+ forceReply: true,
1984
+ selective: true,
1985
+ inputFieldPlaceholder: "Reply with this field value",
1986
+ };
1987
+ }
1988
+ if (!input.required || hasCurrentValue) {
1989
+ buttons.push({
1990
+ text: hasCurrentValue ? "Use default" : "Skip",
1991
+ callbackData: this.createLaunchCallbackCommand({
1992
+ kind: "skip_field",
1993
+ sessionKey: input.sessionKey,
1994
+ fieldId: input.fieldId,
1995
+ }),
1996
+ });
1997
+ }
1998
+ if (buttons.length > 0) return { inlineKeyboard: rows(buttons, 1) };
1999
+ return {
2000
+ forceReply: true,
2001
+ selective: true,
2002
+ inputFieldPlaceholder: "Reply with this field value",
2003
+ };
2004
+ }
2005
+
2006
+ private formatRecentValueButtonText(value: string): string {
2007
+ const normalized = value.replace(/\s+/g, " ").trim();
2008
+ return normalized.length > 56 ? `${normalized.slice(0, 55)}…` : normalized;
2009
+ }
2010
+
2011
+ private buildActionFormFieldReplyMarkup(
2012
+ session: PendingActionFormSession,
2013
+ field: NonNullable<ReturnType<typeof currentField>>,
2014
+ ): TelegramInlineKeyboard | undefined {
2015
+ if (!canSkipActionFormField(field)) {
2016
+ return undefined;
2017
+ }
2018
+ return {
2019
+ inlineKeyboard: [
2020
+ [
2021
+ {
2022
+ text: "Skip",
2023
+ callbackData: `fs:${session.instanceId}:${session.sessionId}:${field.id}`,
2024
+ },
2025
+ ],
2026
+ ],
2027
+ };
2028
+ }
2029
+
2030
+ private async sendActionFormFieldPrompt(
2031
+ thread: TelegramProcessThread,
2032
+ session: PendingActionFormSession,
2033
+ field: NonNullable<ReturnType<typeof currentField>>,
2034
+ prompt = buildFieldPrompt(field),
2035
+ ): Promise<void> {
2036
+ await this.sendHtml(
2037
+ thread,
2038
+ escapeHtml(prompt),
2039
+ this.buildActionFormFieldReplyMarkup(session, field),
2040
+ );
2041
+ }
2042
+
2043
+ private async executeCallbackCommand(
2044
+ instanceId: string,
2045
+ command: TelegramCallbackCommand,
2046
+ ): Promise<void> {
2047
+ const process = this.input.deps.processes.getById(instanceId);
2048
+ if (!process) return;
2049
+ const thread = this.store.getByInstanceId(process.id);
2050
+ if (!thread) return;
2051
+ const key = threadKey(thread.chatId, thread.messageThreadId);
2052
+
2053
+ switch (command.kind) {
2054
+ case "process_action": {
2055
+ if (process.lifecycleStatus !== "waiting") {
2056
+ await this.sendHtml(
2057
+ thread,
2058
+ "That action is no longer available. Use /actions to refresh.",
2059
+ );
2060
+ return;
2061
+ }
2062
+ const action = this.input.deps.processActions
2063
+ .listVisibleActions(process.id)
2064
+ .find((candidate) => candidate.id === command.actionId);
2065
+ if (!action) {
2066
+ await this.sendHtml(
2067
+ thread,
2068
+ "That action is no longer available. Use /actions to refresh.",
2069
+ );
2070
+ return;
2071
+ }
2072
+ if (action.form?.fields.length) {
2073
+ const session = buildActionFormSession({
2074
+ instanceId: process.id,
2075
+ actionId: action.id,
2076
+ actionLabel: action.label,
2077
+ actionPreview: readActionPreview(action),
2078
+ sessionId: createActionFormSessionId(),
2079
+ form: action.form,
2080
+ });
2081
+ this.sessions.set(key, session);
2082
+ const field = currentField(session);
2083
+ if (field) await this.sendActionFormFieldPrompt(thread, session, field);
2084
+ return;
2085
+ }
2086
+ await this.maybeSelectActionModel({
2087
+ instanceId: process.id,
2088
+ action,
2089
+ formValues: {},
2090
+ sessionKey: key,
2091
+ thread,
2092
+ });
2093
+ return;
2094
+ }
2095
+ case "action_form_skip": {
2096
+ await this.skipCurrentActionFormField(key, command.sessionId, command.fieldId, thread);
2097
+ return;
2098
+ }
2099
+ case "action_model_select": {
2100
+ const modelSession = this.sessions.get(key);
2101
+ const modelProfile = resolveModelProfileFromSession(modelSession, command.profileIndex);
2102
+ if (!modelProfile) {
2103
+ await this.sendHtml(
2104
+ thread,
2105
+ "That model option is no longer available. Use /actions to start again.",
2106
+ );
2107
+ return;
2108
+ }
2109
+ if (modelSession?.kind === "recovery_model") {
2110
+ await this.handleRecoveryModelSelect(
2111
+ key,
2112
+ command.sessionId,
2113
+ modelProfile.id,
2114
+ modelSession,
2115
+ thread,
2116
+ );
2117
+ return;
2118
+ }
2119
+ await this.handleActionModelSelect(key, command.sessionId, modelProfile.id, thread);
2120
+ return;
2121
+ }
2122
+ case "action_model_skip": {
2123
+ const modelSession = this.sessions.get(key);
2124
+ if (modelSession?.kind === "recovery_model") {
2125
+ await this.handleRecoveryModelSkip(key, command.sessionId, modelSession, thread);
2126
+ return;
2127
+ }
2128
+ await this.handleActionModelSkip(key, command.sessionId, thread);
2129
+ return;
2130
+ }
2131
+ case "retry": {
2132
+ await this.maybeSelectRecoveryModel({
2133
+ instanceId: process.id,
2134
+ recoveryKind: "retry",
2135
+ sessionKey: key,
2136
+ thread,
2137
+ execute: (opts) =>
2138
+ this.input.deps.commands
2139
+ .retryProcess(process.id, {
2140
+ ...(opts?.nextTurnModelProfileId !== undefined ? opts : {}),
2141
+ actor: TELEGRAM_ACTOR,
2142
+ })
2143
+ .then((result) => {
2144
+ this.sendCommandResult(thread, result, "Retry started.", "Retry failed");
2145
+ }),
2146
+ });
2147
+ return;
2148
+ }
2149
+ case "continue": {
2150
+ const turnRecordId = continuableFailedTurnRecordId(process);
2151
+ if (!turnRecordId) {
2152
+ await this.sendHtml(thread, "No failed turn is available to continue.");
2153
+ return;
2154
+ }
2155
+ await this.maybeSelectRecoveryModel({
2156
+ instanceId: process.id,
2157
+ recoveryKind: "continue",
2158
+ turnRecordId,
2159
+ sessionKey: key,
2160
+ thread,
2161
+ execute: (opts) => {
2162
+ const session = buildContinueSession({
2163
+ instanceId: process.id,
2164
+ turnRecordId,
2165
+ nextTurnModelProfileId: opts?.nextTurnModelProfileId,
2166
+ });
2167
+ this.sessions.set(key, session);
2168
+ this.sendCurrentSessionPrompt(thread, session);
2169
+ },
2170
+ });
2171
+ return;
2172
+ }
2173
+ }
2174
+ }
2175
+
2176
+ private async sendCurrentSessionPrompt(
2177
+ thread: TelegramProcessThread,
2178
+ session: PendingTelegramSession,
2179
+ ): Promise<boolean> {
2180
+ if (session.kind === "continue") {
2181
+ await this.sendHtml(thread, CONTINUE_PROMPT);
2182
+ return true;
2183
+ }
2184
+ if (session.kind === "question") {
2185
+ await this.sendHtml(thread, escapeHtml(buildQuestionPrompt(session)));
2186
+ return true;
2187
+ }
2188
+ if (session.kind === "action_model") {
2189
+ await this.sendActionModelPrompt(thread, session);
2190
+ return true;
2191
+ }
2192
+ if (session.kind === "recovery_model") {
2193
+ await this.sendRecoveryModelPrompt(thread, session);
2194
+ return true;
2195
+ }
2196
+ const field = currentField(session);
2197
+ if (!field) return false;
2198
+ if (session.kind === "action_form") {
2199
+ await this.sendActionFormFieldPrompt(thread, session, field);
2200
+ return true;
2201
+ }
2202
+ await this.sendHtml(thread, escapeHtml(buildFieldPrompt(field)));
2203
+ return true;
2204
+ }
2205
+
2206
+ private async maybeSelectActionModel(input: {
2207
+ instanceId: string;
2208
+ action: {
2209
+ id: string;
2210
+ label: string;
2211
+ form?: FormDefinition;
2212
+ preview?: ActionPreviewLike | null;
2213
+ };
2214
+ formValues: Record<string, unknown>;
2215
+ sessionKey: string;
2216
+ thread: TelegramProcessThread;
2217
+ }): Promise<void> {
2218
+ const fallback = () =>
2219
+ this.executeProcessAction(
2220
+ input.instanceId,
2221
+ { id: input.action.id, label: input.action.label, preview: input.action.preview },
2222
+ input.formValues,
2223
+ input.thread,
2224
+ );
2225
+ try {
2226
+ const profiles = this.listSelectableProfiles(input.instanceId);
2227
+ if (!profiles.length) return fallback();
2228
+ const result = await this.processModelSelection?.preview(
2229
+ input.instanceId,
2230
+ input.action.id,
2231
+ input.formValues,
2232
+ );
2233
+ if (!result) return fallback();
2234
+ if (result.kind === "operational_failure") {
2235
+ this.input.logger?.warn?.(
2236
+ { code: result.code },
2237
+ "Action model preview unavailable; falling back to direct execution",
2238
+ );
2239
+ return fallback();
2240
+ }
2241
+ if (result.kind !== "llm_turn") return fallback();
2242
+ const sessionId = createActionFormSessionId();
2243
+ const session = buildActionModelSession({
2244
+ instanceId: input.instanceId,
2245
+ actionId: input.action.id,
2246
+ actionLabel: input.action.label,
2247
+ actionPreview: input.action.preview,
2248
+ sessionId,
2249
+ formValues: input.formValues,
2250
+ preview: result,
2251
+ profiles,
2252
+ });
2253
+ this.sessions.set(input.sessionKey, session);
2254
+ await this.sendActionModelPrompt(input.thread, session);
2255
+ } catch (error) {
2256
+ this.logError(error, "Action model preview failed; falling back to direct execution");
2257
+ return fallback();
2258
+ }
2259
+ }
2260
+
2261
+ private async resolveActionModelSession(
2262
+ sessionKey: string,
2263
+ sessionId: string,
2264
+ thread: TelegramProcessThread,
2265
+ ): Promise<PendingActionModelSession | null> {
2266
+ const session = this.sessions.get(sessionKey);
2267
+ if (!session || session.kind !== "action_model" || session.sessionId !== sessionId) {
2268
+ await this.sendHtml(thread, "That model selection expired. Use /actions to start again.");
2269
+ return null;
2270
+ }
2271
+ if (session.expiresAt < Date.now()) {
2272
+ this.sessions.delete(sessionKey);
2273
+ await this.sendHtml(thread, "That model selection expired. Use /actions to start again.");
2274
+ return null;
2275
+ }
2276
+ this.sessions.delete(sessionKey);
2277
+ return session;
2278
+ }
2279
+
2280
+ private executeActionModelSession(
2281
+ session: PendingActionModelSession,
2282
+ thread: TelegramProcessThread,
2283
+ opts?: { nextTurnModelProfileId?: string | null },
2284
+ ): Promise<void> {
2285
+ return this.executeProcessAction(
2286
+ session.instanceId,
2287
+ { id: session.actionId, label: session.actionLabel, preview: session.actionPreview },
2288
+ session.formValues,
2289
+ thread,
2290
+ opts,
2291
+ );
2292
+ }
2293
+
2294
+ private async sendActionModelSwitchWarning(
2295
+ session: PendingActionModelSession,
2296
+ effectiveModelProfileId: string | null | undefined,
2297
+ thread: TelegramProcessThread,
2298
+ ): Promise<void> {
2299
+ if (!effectiveModelProfileId) return;
2300
+ const warning = buildActionModelSwitchWarning({ session, effectiveModelProfileId });
2301
+ if (warning) await this.sendHtml(thread, escapeHtml(warning));
2302
+ }
2303
+
2304
+ private async handleActionModelSelect(
2305
+ sessionKey: string,
2306
+ sessionId: string,
2307
+ modelProfileId: string,
2308
+ thread: TelegramProcessThread,
2309
+ ): Promise<void> {
2310
+ const session = await this.resolveActionModelSession(sessionKey, sessionId, thread);
2311
+ if (!session) return;
2312
+ await this.sendActionModelSwitchWarning(session, modelProfileId, thread);
2313
+ await this.executeActionModelSession(session, thread, {
2314
+ nextTurnModelProfileId: modelProfileId,
2315
+ });
2316
+ }
2317
+
2318
+ private async handleActionModelSkip(
2319
+ sessionKey: string,
2320
+ sessionId: string,
2321
+ thread: TelegramProcessThread,
2322
+ ): Promise<void> {
2323
+ const session = await this.resolveActionModelSession(sessionKey, sessionId, thread);
2324
+ if (!session) return;
2325
+ const resolved = session.preview.resolvedModel;
2326
+ await this.sendActionModelSwitchWarning(
2327
+ session,
2328
+ resolved?.status === "resolved" ? resolved.modelProfileId : null,
2329
+ thread,
2330
+ );
2331
+ await this.executeActionModelSession(session, thread);
2332
+ }
2333
+
2334
+ private async sendActionModelPrompt(
2335
+ thread: TelegramProcessThread,
2336
+ session: PendingActionModelSession,
2337
+ ): Promise<void> {
2338
+ await this.sendHtml(
2339
+ thread,
2340
+ escapeHtml(buildActionModelPrompt({ session })),
2341
+ this.buildActionModelReplyMarkup(session),
2342
+ );
2343
+ }
2344
+
2345
+ private buildActionModelReplyMarkup(
2346
+ session: PendingActionModelSession,
2347
+ ): TelegramInlineKeyboard | undefined {
2348
+ const buttons: Array<{ text: string; callbackData: string }> = [];
2349
+ let index = 0;
2350
+ for (const profile of session.profiles.slice(0, 20)) {
2351
+ index += 1;
2352
+ const switchesModel = buildActionModelSwitchWarning({
2353
+ session,
2354
+ effectiveModelProfileId: profile.id,
2355
+ });
2356
+ buttons.push({
2357
+ text: `${switchesModel ? "⚠ " : ""}${profile.id}`,
2358
+ callbackData: `ams:${session.instanceId}:${session.sessionId}:${index}`,
2359
+ });
2360
+ }
2361
+ const resolved = session.preview.resolvedModel;
2362
+ const resolvedProfileId = resolved?.status === "resolved" ? resolved.modelProfileId : null;
2363
+ const keepingCurrentSwitchesModel = resolvedProfileId
2364
+ ? buildActionModelSwitchWarning({ session, effectiveModelProfileId: resolvedProfileId })
2365
+ : null;
2366
+ buttons.push({
2367
+ text: `${keepingCurrentSwitchesModel ? "⚠ " : ""}Keep current`,
2368
+ callbackData: `amk:${session.instanceId}:${session.sessionId}`,
2369
+ });
2370
+ return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
2371
+ }
2372
+
2373
+ private async applyActionFormStep(
2374
+ key: string,
2375
+ session: PendingActionFormSession,
2376
+ step: ReturnType<typeof applyFormText>,
2377
+ thread: TelegramProcessThread,
2378
+ ): Promise<void> {
2379
+ if (!step.ok || !step.done) {
2380
+ const field = currentField(session);
2381
+ if (field) {
2382
+ await this.sendActionFormFieldPrompt(thread, session, field, step.prompt);
2383
+ } else {
2384
+ await this.sendHtml(thread, escapeHtml(step.prompt));
2385
+ }
2386
+ return;
2387
+ }
2388
+ this.sessions.delete(key);
2389
+ await this.maybeSelectActionModel({
2390
+ instanceId: session.instanceId,
2391
+ action: {
2392
+ id: session.actionId,
2393
+ label: session.actionLabel,
2394
+ form: session.form,
2395
+ preview: session.actionPreview,
2396
+ },
2397
+ formValues: step.values,
2398
+ sessionKey: key,
2399
+ thread,
2400
+ });
2401
+ }
2402
+
2403
+ private async applyActionFormText(
2404
+ key: string,
2405
+ session: PendingActionFormSession,
2406
+ text: string,
2407
+ thread: TelegramProcessThread,
2408
+ ): Promise<void> {
2409
+ await this.applyActionFormStep(key, session, applyFormText(session, text), thread);
2410
+ }
2411
+
2412
+ private async applyActionFormSkip(
2413
+ key: string,
2414
+ session: PendingActionFormSession,
2415
+ thread: TelegramProcessThread,
2416
+ ): Promise<void> {
2417
+ await this.applyActionFormStep(key, session, applyFormSkip(session), thread);
2418
+ }
2419
+
2420
+ private async skipCurrentActionFormField(
2421
+ key: string,
2422
+ sessionId: string,
2423
+ fieldId: string,
2424
+ thread: TelegramProcessThread,
2425
+ ): Promise<void> {
2426
+ const session = this.sessions.get(key);
2427
+ if (!session || session.kind !== "action_form") {
2428
+ await this.sendHtml(thread, "This form prompt expired. Use /actions to start again.");
2429
+ return;
2430
+ }
2431
+ if (session.expiresAt < Date.now()) {
2432
+ this.sessions.delete(key);
2433
+ await this.sendHtml(thread, "This form prompt expired. Use /actions to start again.");
2434
+ return;
2435
+ }
2436
+ const field = currentField(session);
2437
+ if (session.sessionId !== sessionId || !field || field.id !== fieldId) {
2438
+ await this.sendHtml(
2439
+ thread,
2440
+ "That skip button is stale. Continue with the latest prompt or send /cancel.",
2441
+ );
2442
+ return;
2443
+ }
2444
+ if (!canSkipActionFormField(field)) {
2445
+ await this.sendActionFormFieldPrompt(
2446
+ thread,
2447
+ session,
2448
+ field,
2449
+ `${field.label} is required and cannot be skipped.\n${buildFieldPrompt(field)}`,
2450
+ );
2451
+ return;
2452
+ }
2453
+ await this.applyActionFormSkip(key, session, thread);
2454
+ }
2455
+
2456
+ private async handleSessionText(
2457
+ key: string,
2458
+ session: PendingTelegramSession,
2459
+ text: string,
2460
+ thread: TelegramProcessThread,
2461
+ name: string | null,
2462
+ ): Promise<void> {
2463
+ if (session.expiresAt < Date.now()) {
2464
+ this.sessions.delete(key);
2465
+ await this.sendHtml(thread, "This prompt expired. Use /actions to start again.");
2466
+ return;
2467
+ }
2468
+ if (session.kind === "continue") {
2469
+ const prompt = name === "skip" ? null : text;
2470
+ this.sessions.delete(key);
2471
+ const result = await this.input.deps.commands.continueFailedTurn(
2472
+ session.instanceId,
2473
+ session.turnRecordId,
2474
+ {
2475
+ prompt,
2476
+ ...(session.nextTurnModelProfileId !== undefined &&
2477
+ session.nextTurnModelProfileId !== null
2478
+ ? { nextTurnModelProfileId: session.nextTurnModelProfileId }
2479
+ : {}),
2480
+ actor: TELEGRAM_ACTOR,
2481
+ },
2482
+ );
2483
+ await this.sendCommandResult(thread, result, "Continue started.", "Continue failed");
2484
+ return;
2485
+ }
2486
+ if (session.kind === "question") {
2487
+ if (name) {
2488
+ await this.sendHtml(thread, escapeHtml(buildQuestionPrompt(session)));
2489
+ return;
2490
+ }
2491
+ const step = applyQuestionText(session, text);
2492
+ if (!step.done) {
2493
+ await this.sendHtml(thread, escapeHtml(step.prompt ?? buildQuestionPrompt(session)));
2494
+ return;
2495
+ }
2496
+ const service = this.input.deps.processQuestions;
2497
+ const result = service
2498
+ ? await service.submitAnswers(
2499
+ session.instanceId,
2500
+ session.request.id,
2501
+ step.draft,
2502
+ TELEGRAM_ACTOR,
2503
+ )
2504
+ : { ok: false as const, message: "Answers cannot be submitted through Telegram." };
2505
+ this.sessions.delete(key);
2506
+ await this.sendHtml(
2507
+ thread,
2508
+ result.ok ? "✅ Answers sent. The active turn is continuing." : escapeHtml(result.message),
2509
+ );
2510
+ return;
2511
+ }
2512
+ if (session.kind === "action_model") {
2513
+ if (name === "skip") {
2514
+ await this.handleActionModelSkip(key, session.sessionId, thread);
2515
+ return;
2516
+ }
2517
+ if (name === "cancel") {
2518
+ this.sessions.delete(key);
2519
+ await this.sendHtml(thread, "Cancelled.");
2520
+ return;
2521
+ }
2522
+ await this.handleActionModelText(key, session, text, thread);
2523
+ return;
2524
+ }
2525
+ if (session.kind === "recovery_model") {
2526
+ if (name === "skip") {
2527
+ await this.handleRecoveryModelSkip(key, session.sessionId, session, thread);
2528
+ return;
2529
+ }
2530
+ if (name === "cancel") {
2531
+ this.sessions.delete(key);
2532
+ await this.sendHtml(thread, "Cancelled.");
2533
+ return;
2534
+ }
2535
+ await this.handleRecoveryModelText(key, session, text, thread);
2536
+ return;
2537
+ }
2538
+ if (name === "skip") {
2539
+ const field = currentField(session);
2540
+ if (!canSkipActionFormField(field)) {
2541
+ if (field) {
2542
+ await this.sendActionFormFieldPrompt(
2543
+ thread,
2544
+ session,
2545
+ field,
2546
+ `${field.label} is required and cannot be skipped.\n${buildFieldPrompt(field)}`,
2547
+ );
2548
+ }
2549
+ return;
2550
+ }
2551
+ await this.applyActionFormSkip(key, session as PendingActionFormSession, thread);
2552
+ return;
2553
+ }
2554
+ await this.applyActionFormText(key, session as PendingActionFormSession, text, thread);
2555
+ }
2556
+
2557
+ private async handleActionModelText(
2558
+ sessionKey: string,
2559
+ session: PendingActionModelSession,
2560
+ text: string,
2561
+ thread: TelegramProcessThread,
2562
+ ): Promise<void> {
2563
+ const profile = resolveProfileByTextOrIndex(text.trim(), session.profiles);
2564
+ if (profile) {
2565
+ this.sessions.delete(sessionKey);
2566
+ await this.sendActionModelSwitchWarning(session, profile.id, thread);
2567
+ return this.executeActionModelSession(session, thread, {
2568
+ nextTurnModelProfileId: profile.id,
2569
+ });
2570
+ }
2571
+ await this.sendHtml(
2572
+ thread,
2573
+ escapeHtml(`Model must match an available profile.\n${buildActionModelPrompt({ session })}`),
2574
+ this.buildActionModelReplyMarkup(session),
2575
+ );
2576
+ }
2577
+
2578
+ private async maybeSelectRecoveryModel(input: {
2579
+ instanceId: string;
2580
+ recoveryKind: "retry" | "continue";
2581
+ turnRecordId?: string;
2582
+ sessionKey: string;
2583
+ thread: TelegramProcessThread;
2584
+ execute: (opts?: { nextTurnModelProfileId?: string | null }) => void | Promise<void>;
2585
+ }): Promise<void> {
2586
+ try {
2587
+ const profiles = this.listSelectableProfiles(input.instanceId);
2588
+ if (!profiles.length) return input.execute();
2589
+ const sessionId = createActionFormSessionId();
2590
+ const session = buildRecoveryModelSession({
2591
+ instanceId: input.instanceId,
2592
+ recoveryKind: input.recoveryKind,
2593
+ turnRecordId: input.turnRecordId,
2594
+ sessionId,
2595
+ profiles,
2596
+ });
2597
+ this.sessions.set(input.sessionKey, session);
2598
+ await this.sendRecoveryModelPrompt(input.thread, session);
2599
+ } catch (error) {
2600
+ this.logError(error, "Recovery model selection failed; falling back to direct execution");
2601
+ return input.execute();
2602
+ }
2603
+ }
2604
+
2605
+ private async handleRecoveryModelSelect(
2606
+ sessionKey: string,
2607
+ _sessionId: string,
2608
+ modelProfileId: string,
2609
+ session: PendingRecoveryModelSession,
2610
+ thread: TelegramProcessThread,
2611
+ ): Promise<void> {
2612
+ this.sessions.delete(sessionKey);
2613
+ await this.executeRecoveryModelSession(session, thread, {
2614
+ nextTurnModelProfileId: modelProfileId,
2615
+ });
2616
+ }
2617
+
2618
+ private async handleRecoveryModelSkip(
2619
+ sessionKey: string,
2620
+ _sessionId: string,
2621
+ session: PendingRecoveryModelSession,
2622
+ thread: TelegramProcessThread,
2623
+ ): Promise<void> {
2624
+ this.sessions.delete(sessionKey);
2625
+ await this.executeRecoveryModelSession(session, thread);
2626
+ }
2627
+
2628
+ private async handleRecoveryModelText(
2629
+ sessionKey: string,
2630
+ session: PendingRecoveryModelSession,
2631
+ text: string,
2632
+ thread: TelegramProcessThread,
2633
+ ): Promise<void> {
2634
+ const profile = resolveProfileByTextOrIndex(text.trim(), session.profiles);
2635
+ if (profile) {
2636
+ this.sessions.delete(sessionKey);
2637
+ await this.executeRecoveryModelSession(session, thread, {
2638
+ nextTurnModelProfileId: profile.id,
2639
+ });
2640
+ return;
2641
+ }
2642
+ await this.sendHtml(
2643
+ thread,
2644
+ escapeHtml(
2645
+ `Model must match an available profile.\n${buildRecoveryModelPrompt({ session })}`,
2646
+ ),
2647
+ this.buildRecoveryModelReplyMarkup(session),
2648
+ );
2649
+ }
2650
+
2651
+ private async executeRecoveryModelSession(
2652
+ session: PendingRecoveryModelSession,
2653
+ thread: TelegramProcessThread,
2654
+ opts?: { nextTurnModelProfileId?: string | null },
2655
+ ): Promise<void> {
2656
+ if (session.recoveryKind === "retry") {
2657
+ const retryOpts = {
2658
+ ...(opts?.nextTurnModelProfileId !== undefined ? opts : {}),
2659
+ actor: TELEGRAM_ACTOR,
2660
+ };
2661
+ void this.input.deps.commands.retryProcess(session.instanceId, retryOpts).then((result) => {
2662
+ this.sendCommandResult(thread, result, "Retry started.", "Retry failed");
2663
+ });
2664
+ } else {
2665
+ const continueSession = buildContinueSession({
2666
+ instanceId: session.instanceId,
2667
+ turnRecordId: session.turnRecordId ?? "",
2668
+ nextTurnModelProfileId: opts?.nextTurnModelProfileId,
2669
+ });
2670
+ const key = threadKey(thread.chatId, thread.messageThreadId);
2671
+ this.sessions.set(key, continueSession);
2672
+ await this.sendCurrentSessionPrompt(thread, continueSession);
2673
+ }
2674
+ }
2675
+
2676
+ private async sendRecoveryModelPrompt(
2677
+ thread: TelegramProcessThread,
2678
+ session: PendingRecoveryModelSession,
2679
+ ): Promise<void> {
2680
+ await this.sendHtml(
2681
+ thread,
2682
+ escapeHtml(buildRecoveryModelPrompt({ session })),
2683
+ this.buildRecoveryModelReplyMarkup(session),
2684
+ );
2685
+ }
2686
+
2687
+ private buildRecoveryModelReplyMarkup(
2688
+ session: PendingRecoveryModelSession,
2689
+ ): TelegramInlineKeyboard | undefined {
2690
+ const buttons: Array<{ text: string; callbackData: string }> = [];
2691
+ let index = 0;
2692
+ for (const profile of session.profiles.slice(0, 20)) {
2693
+ index += 1;
2694
+ buttons.push({
2695
+ text: profile.id,
2696
+ callbackData: `ams:${session.instanceId}:${session.sessionId}:${index}`,
2697
+ });
2698
+ }
2699
+ buttons.push({
2700
+ text: "Keep current",
2701
+ callbackData: `amk:${session.instanceId}:${session.sessionId}`,
2702
+ });
2703
+ return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
2704
+ }
2705
+
2706
+ private async executeProcessAction(
2707
+ instanceId: string,
2708
+ action: TelegramActionExecutionSummary,
2709
+ input: Record<string, unknown>,
2710
+ thread: TelegramProcessThread,
2711
+ opts?: { nextTurnModelProfileId?: string | null },
2712
+ ): Promise<void> {
2713
+ const executeOpts: Parameters<typeof this.input.deps.processActions.executeAction>[3] = {
2714
+ source: "ui",
2715
+ origin: "external_interface",
2716
+ actor: TELEGRAM_ACTOR,
2717
+ };
2718
+ if (opts?.nextTurnModelProfileId !== undefined) {
2719
+ executeOpts.nextTurnModelProfileId = opts.nextTurnModelProfileId;
2720
+ }
2721
+ const result = await this.input.deps.processActions.executeAction(
2722
+ instanceId,
2723
+ action.id,
2724
+ input,
2725
+ executeOpts,
2726
+ );
2727
+ await this.sendCommandResult(
2728
+ thread,
2729
+ result,
2730
+ buildActionSubmittedMessage({ action, values: input }),
2731
+ `Action failed: ${action.label}`,
2732
+ );
2733
+ }
2734
+
2735
+ private async sendCommandResult(
2736
+ thread: TelegramProcessThread,
2737
+ result: { ok: boolean; message?: string | null; error?: string | null },
2738
+ successText: string,
2739
+ fallbackError: string,
2740
+ ): Promise<void> {
2741
+ await this.sendHtml(
2742
+ thread,
2743
+ result.ok ? successText : `⚠️ ${escapeHtml(result.error ?? result.message ?? fallbackError)}`,
2744
+ );
2745
+ }
2746
+
2747
+ private isAllowed(from: { id: number } | null | undefined): boolean {
2748
+ return typeof from?.id === "number" && this.input.config.allowUserIds.includes(from.id);
2749
+ }
2750
+
2751
+ private async sendHtml(
2752
+ thread: TelegramProcessThread,
2753
+ text: string,
2754
+ replyMarkup?: TelegramReplyMarkup,
2755
+ ): Promise<void> {
2756
+ await this.sendHtmlToChat(thread.chatId, thread.messageThreadId, text, replyMarkup);
2757
+ }
2758
+
2759
+ private async sendResultParts(
2760
+ thread: TelegramProcessThread,
2761
+ instanceId: string,
2762
+ turnRecordId: string,
2763
+ parts: readonly TelegramResultPart[],
2764
+ ): Promise<void> {
2765
+ for (const [index, part] of parts.entries()) {
2766
+ if (part.kind === "html") {
2767
+ await this.sendHtml(thread, part.html);
2768
+ continue;
2769
+ }
2770
+ if (part.kind === "mermaid") {
2771
+ try {
2772
+ await this.sendPhotoWithDocumentFallback(thread, {
2773
+ bytes: await renderMermaidPng(part.source),
2774
+ filename: `diagram-${index + 1}.png`,
2775
+ caption: "Mermaid diagram",
2776
+ });
2777
+ } catch (error) {
2778
+ this.logError(error, "Telegram Mermaid rendering failed; sending diagram source");
2779
+ await this.sendHtml(
2780
+ thread,
2781
+ `⚠️ <b>Diagram could not be rendered</b>\n<pre><code>${escapeHtml(part.source)}</code></pre>`,
2782
+ );
2783
+ }
2784
+ continue;
2785
+ }
2786
+ try {
2787
+ const bytes = await this.input.deps.resultImages?.get(
2788
+ instanceId,
2789
+ turnRecordId,
2790
+ part.imageId,
2791
+ );
2792
+ if (!bytes) throw new Error("Managed result image is unavailable");
2793
+ await this.sendPhotoWithDocumentFallback(thread, {
2794
+ bytes,
2795
+ filename: part.imageId,
2796
+ ...(part.alt.trim() ? { caption: part.alt.trim().slice(0, 900) } : {}),
2797
+ });
2798
+ } catch (error) {
2799
+ this.logError(error, "Telegram result image delivery failed");
2800
+ const label = part.alt.trim() || part.imageId;
2801
+ await this.sendHtml(thread, `⚠️ Image unavailable: ${escapeHtml(label)}`);
2802
+ }
2803
+ }
2804
+ }
2805
+
2806
+ private async sendPhotoWithDocumentFallback(
2807
+ thread: TelegramProcessThread,
2808
+ file: { bytes: Uint8Array; filename: string; caption?: string },
2809
+ ): Promise<void> {
2810
+ const input = { ...messageTarget(thread.chatId, thread.messageThreadId), ...file };
2811
+ try {
2812
+ await this.input.client.sendPhoto(input);
2813
+ } catch (error) {
2814
+ this.logError(error, "Telegram photo send failed; retrying as a document");
2815
+ await this.input.client.sendDocument(input);
2816
+ }
2817
+ }
2818
+
2819
+ private async sendPlainToChat(
2820
+ chatId: string,
2821
+ messageThreadId: number | undefined,
2822
+ text: string,
2823
+ replyMarkup?: TelegramReplyMarkup,
2824
+ ): Promise<void> {
2825
+ const chunks = splitPlainTelegramText(text, this.input.config.markdown.maxChars);
2826
+ for (const [index, chunk] of chunks.entries()) {
2827
+ const isLast = index === chunks.length - 1;
2828
+ await this.input.client.sendMessage({
2829
+ ...messageTarget(chatId, messageThreadId),
2830
+ text: chunk,
2831
+ ...(isLast && replyMarkup ? { replyMarkup } : {}),
2832
+ });
2833
+ }
2834
+ }
2835
+
2836
+ private async sendHtmlToChat(
2837
+ chatId: string,
2838
+ messageThreadId: number | undefined,
2839
+ text: string,
2840
+ replyMarkup?: TelegramReplyMarkup,
2841
+ ): Promise<void> {
2842
+ const chunks = splitTelegramHtml(text, this.input.config.markdown.maxChars);
2843
+ for (const [index, chunk] of chunks.entries()) {
2844
+ const isLast = index === chunks.length - 1;
2845
+ try {
2846
+ await this.input.client.sendMessage({
2847
+ ...messageTarget(chatId, messageThreadId),
2848
+ text: chunk,
2849
+ parseMode: "HTML",
2850
+ ...(isLast && replyMarkup ? { replyMarkup } : {}),
2851
+ });
2852
+ } catch (error) {
2853
+ this.logError(error, "Telegram HTML chunk send failed; retrying chunk as plain text");
2854
+ await this.sendPlainToChat(
2855
+ chatId,
2856
+ messageThreadId,
2857
+ telegramHtmlToPlainText(chunk),
2858
+ isLast ? replyMarkup : undefined,
2859
+ );
2860
+ }
2861
+ }
2862
+ }
2863
+
2864
+ private logError(error: unknown, message: string): void {
2865
+ this.input.logger?.warn?.(
2866
+ { err: error instanceof Error ? error.message : String(error) },
2867
+ message,
2868
+ );
2869
+ }
2870
+ }