@leitwerk-dev/telegram 0.1.9 → 0.2.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 (51) hide show
  1. package/README.md +1 -1
  2. package/dist/actions.d.ts +1 -0
  3. package/dist/actions.d.ts.map +1 -1
  4. package/dist/bridge.d.ts +3 -10
  5. package/dist/bridge.d.ts.map +1 -1
  6. package/dist/config.d.ts.map +1 -1
  7. package/dist/form-session.d.ts.map +1 -1
  8. package/dist/grammy-telegram-client.d.ts +17 -41
  9. package/dist/grammy-telegram-client.d.ts.map +1 -1
  10. package/dist/index.js +3722 -52
  11. package/dist/index.js.map +1 -1
  12. package/dist/launch-session.d.ts +1 -1
  13. package/dist/launch-session.d.ts.map +1 -1
  14. package/dist/types.d.ts +5 -6
  15. package/dist/types.d.ts.map +1 -1
  16. package/package.json +7 -7
  17. package/src/actions.ts +14 -5
  18. package/src/bridge.ts +113 -303
  19. package/src/config.ts +2 -4
  20. package/src/form-session.ts +10 -12
  21. package/src/grammy-telegram-client.ts +23 -43
  22. package/src/launch-session.ts +30 -55
  23. package/src/types.ts +4 -7
  24. package/dist/actions.js +0 -32
  25. package/dist/actions.js.map +0 -1
  26. package/dist/actor.js +0 -7
  27. package/dist/actor.js.map +0 -1
  28. package/dist/bridge.js +0 -2032
  29. package/dist/bridge.js.map +0 -1
  30. package/dist/config.js +0 -70
  31. package/dist/config.js.map +0 -1
  32. package/dist/fake-telegram-client.js +0 -107
  33. package/dist/fake-telegram-client.js.map +0 -1
  34. package/dist/form-session.js +0 -218
  35. package/dist/form-session.js.map +0 -1
  36. package/dist/grammy-telegram-client.js +0 -195
  37. package/dist/grammy-telegram-client.js.map +0 -1
  38. package/dist/launch-session.js +0 -435
  39. package/dist/launch-session.js.map +0 -1
  40. package/dist/markdown-html.js +0 -259
  41. package/dist/markdown-html.js.map +0 -1
  42. package/dist/mermaid-image.js +0 -99
  43. package/dist/mermaid-image.js.map +0 -1
  44. package/dist/process-feed.js +0 -165
  45. package/dist/process-feed.js.map +0 -1
  46. package/dist/process-thread-store.js +0 -74
  47. package/dist/process-thread-store.js.map +0 -1
  48. package/dist/topic-title.js +0 -29
  49. package/dist/topic-title.js.map +0 -1
  50. package/dist/types.js +0 -19
  51. package/dist/types.js.map +0 -1
package/src/bridge.ts CHANGED
@@ -5,6 +5,7 @@ import type {
5
5
  ProcessTurnRecord,
6
6
  ProcessTurnRecordPathType,
7
7
  } from "@leitwerk-dev/domain";
8
+ import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
8
9
  import type {
9
10
  CoreServerSetupDeps,
10
11
  FormDefinition,
@@ -19,7 +20,7 @@ import type {
19
20
  ServerExtensionLogger,
20
21
  UiLauncherSummary,
21
22
  } from "@leitwerk-dev/process-sdk";
22
- import { buildActionKeyboard, continuableFailedTurnRecordId } from "./actions.js";
23
+ import { buildActionKeyboard, continuableFailedTurnRecordId, rows } from "./actions.js";
23
24
  import { TELEGRAM_ACTOR } from "./actor.js";
24
25
  import type { TelegramExtensionConfig } from "./config.js";
25
26
  import {
@@ -159,12 +160,6 @@ function commandArgs(text: string): string {
159
160
  .trim();
160
161
  }
161
162
 
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
163
  function messageTarget(chatId: string, messageThreadId: number | undefined) {
169
164
  return { chatId, ...(messageThreadId !== undefined ? { messageThreadId } : {}) };
170
165
  }
@@ -179,89 +174,39 @@ function launchSessionKey(input: {
179
174
  : null;
180
175
  }
181
176
 
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
177
  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;
178
+ const separator = data.indexOf(":");
179
+ if (separator < 0) return null;
180
+ const prefix = data.slice(0, separator);
181
+ const payload = data.slice(separator + 1);
182
+ if (prefix === "r" || prefix === "c") {
183
+ return payload ? { kind: prefix === "r" ? "retry" : "continue", instanceId: payload } : null;
184
+ }
185
+ if (prefix === "a") {
186
+ const separator = payload.indexOf(":");
187
+ if (separator <= 0 || separator === payload.length - 1) return null;
188
+ return {
189
+ kind: "process_action",
190
+ instanceId: payload.slice(0, separator),
191
+ actionId: payload.slice(separator + 1),
192
+ };
232
193
  }
233
- if (data.startsWith("c:")) {
234
- const instanceId = data.slice("c:".length);
235
- return instanceId ? { kind: "continue", instanceId } : null;
194
+ const [instanceId, sessionId, ...rest] = payload.split(":");
195
+ if (!instanceId || !sessionId) return null;
196
+ switch (prefix) {
197
+ case "fs":
198
+ return { kind: "action_form_skip", instanceId, sessionId, fieldId: rest.join(":") };
199
+ case "amk":
200
+ return { kind: "action_model_skip", instanceId, sessionId };
201
+ case "ams": {
202
+ const profileIndex = Number(rest.join(":"));
203
+ return Number.isInteger(profileIndex) && profileIndex >= 1
204
+ ? { kind: "action_model_select", instanceId, sessionId, profileIndex }
205
+ : null;
206
+ }
207
+ default:
208
+ return null;
236
209
  }
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
210
  }
266
211
 
267
212
  function resolveProfileByTextOrIndex(
@@ -283,14 +228,9 @@ function resolveModelProfileFromSession(
283
228
  session: PendingTelegramSession | undefined,
284
229
  profileIndex: number,
285
230
  ): 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;
231
+ return session?.kind === "action_model" || session?.kind === "recovery_model"
232
+ ? (session.profiles?.[profileIndex - 1] ?? null)
233
+ : null;
294
234
  }
295
235
 
296
236
  function processCanAcceptFreeText(process: ProcessInstance): boolean {
@@ -336,10 +276,6 @@ function shouldDeferCompletedLifecycleUntilTurnOutcome(input: {
336
276
  );
337
277
  }
338
278
 
339
- function isRecord(value: unknown): value is Record<string, unknown> {
340
- return typeof value === "object" && value !== null && !Array.isArray(value);
341
- }
342
-
343
279
  function readClaimedLaunchThread(
344
280
  process: ProcessInstance,
345
281
  expectedChatId: string,
@@ -357,27 +293,6 @@ function createActionFormSessionId(): string {
357
293
  return randomBytes(4).toString("hex");
358
294
  }
359
295
 
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
296
  export class TelegramBridge {
382
297
  private readonly store: ProcessThreadStore;
383
298
  private readonly sessions = new Map<string, PendingTelegramSession>();
@@ -1740,20 +1655,26 @@ export class TelegramBridge {
1740
1655
  );
1741
1656
  return;
1742
1657
  }
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
- >;
1658
+ let result: Awaited<ReturnType<CoreServerSetupDeps["launchRuns"]["startProgrammatic"]>>;
1751
1659
  try {
1752
- result = await this.input.deps.processLaunches.createProcessFromLaunchPlan(launchPlan, {
1753
- actor: TELEGRAM_ACTOR,
1754
- });
1660
+ result = await this.input.deps.launchRuns.startProgrammatic(
1661
+ {
1662
+ launcherId: launcher.id,
1663
+ launcherInput: buildLaunchInput(session),
1664
+ ...(session.modelConfigTouched ? { modelConfig: buildLaunchModelConfig(session) } : {}),
1665
+ processMetadata: {
1666
+ telegram: {
1667
+ launchThread: { mode: "forum_topic", chatId, messageThreadId },
1668
+ },
1669
+ },
1670
+ },
1671
+ {
1672
+ actor: TELEGRAM_ACTOR,
1673
+ idempotencyKey: `telegram:${sessionKey}:${session.expiresAt}`,
1674
+ },
1675
+ );
1755
1676
  } catch (error) {
1756
- this.logError(error, "Failed to create Telegram-launched process");
1677
+ this.logError(error, "Failed to admit Telegram-launched process");
1757
1678
  await this.sendHtmlToChat(
1758
1679
  chatId,
1759
1680
  messageThreadId,
@@ -1761,31 +1682,22 @@ export class TelegramBridge {
1761
1682
  );
1762
1683
  return;
1763
1684
  }
1764
- if (result.ok) {
1685
+ if (result.process) {
1765
1686
  this.recordLaunchRecentValuesBestEffort(session);
1766
1687
  this.launchSessions.delete(sessionKey);
1767
1688
  await this.sendHtmlToChat(
1768
1689
  chatId,
1769
1690
  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}`)}`,
1691
+ result.error
1692
+ ? `⚠️ Process was created but launch had a follow-up problem. Web UI: ${escapeHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${result.process.id}`)}`
1693
+ : `✅ Process launched. Web UI: ${escapeHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${result.process.id}`)}`,
1782
1694
  );
1783
1695
  return;
1784
1696
  }
1785
1697
  await this.sendHtmlToChat(
1786
1698
  chatId,
1787
1699
  messageThreadId,
1788
- `⚠️ ${escapeHtml(String(result.body.error ?? "Launch failed"))}`,
1700
+ `⚠️ ${escapeHtml(result.error ?? "Launch failed")}`,
1789
1701
  );
1790
1702
  }
1791
1703
 
@@ -2107,13 +2019,9 @@ export class TelegramBridge {
2107
2019
  return;
2108
2020
  }
2109
2021
  if (modelSession?.kind === "recovery_model") {
2110
- await this.handleRecoveryModelSelect(
2111
- key,
2112
- command.sessionId,
2113
- modelProfile.id,
2114
- modelSession,
2115
- thread,
2116
- );
2022
+ await this.executeRecoveryModelSession(key, modelSession, thread, {
2023
+ nextTurnModelProfileId: modelProfile.id,
2024
+ });
2117
2025
  return;
2118
2026
  }
2119
2027
  await this.handleActionModelSelect(key, command.sessionId, modelProfile.id, thread);
@@ -2122,7 +2030,7 @@ export class TelegramBridge {
2122
2030
  case "action_model_skip": {
2123
2031
  const modelSession = this.sessions.get(key);
2124
2032
  if (modelSession?.kind === "recovery_model") {
2125
- await this.handleRecoveryModelSkip(key, command.sessionId, modelSession, thread);
2033
+ await this.executeRecoveryModelSession(key, modelSession, thread);
2126
2034
  return;
2127
2035
  }
2128
2036
  await this.handleActionModelSkip(key, command.sessionId, thread);
@@ -2185,21 +2093,13 @@ export class TelegramBridge {
2185
2093
  await this.sendHtml(thread, escapeHtml(buildQuestionPrompt(session)));
2186
2094
  return true;
2187
2095
  }
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);
2096
+ if (session.kind === "action_model" || session.kind === "recovery_model") {
2097
+ await this.sendModelPrompt(thread, session);
2194
2098
  return true;
2195
2099
  }
2196
2100
  const field = currentField(session);
2197
2101
  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)));
2102
+ await this.sendActionFormFieldPrompt(thread, session, field);
2203
2103
  return true;
2204
2104
  }
2205
2105
 
@@ -2251,7 +2151,7 @@ export class TelegramBridge {
2251
2151
  profiles,
2252
2152
  });
2253
2153
  this.sessions.set(input.sessionKey, session);
2254
- await this.sendActionModelPrompt(input.thread, session);
2154
+ await this.sendModelPrompt(input.thread, session);
2255
2155
  } catch (error) {
2256
2156
  this.logError(error, "Action model preview failed; falling back to direct execution");
2257
2157
  return fallback();
@@ -2331,43 +2231,51 @@ export class TelegramBridge {
2331
2231
  await this.executeActionModelSession(session, thread);
2332
2232
  }
2333
2233
 
2334
- private async sendActionModelPrompt(
2234
+ private async sendModelPrompt(
2335
2235
  thread: TelegramProcessThread,
2336
- session: PendingActionModelSession,
2236
+ session: PendingActionModelSession | PendingRecoveryModelSession,
2237
+ error = "",
2337
2238
  ): Promise<void> {
2239
+ const prompt =
2240
+ session.kind === "action_model"
2241
+ ? buildActionModelPrompt({ session })
2242
+ : buildRecoveryModelPrompt({ session });
2338
2243
  await this.sendHtml(
2339
2244
  thread,
2340
- escapeHtml(buildActionModelPrompt({ session })),
2341
- this.buildActionModelReplyMarkup(session),
2245
+ escapeHtml(`${error}${prompt}`),
2246
+ this.buildModelReplyMarkup(session),
2342
2247
  );
2343
2248
  }
2344
2249
 
2345
- private buildActionModelReplyMarkup(
2346
- session: PendingActionModelSession,
2347
- ): TelegramInlineKeyboard | undefined {
2250
+ private buildModelReplyMarkup(
2251
+ session: PendingActionModelSession | PendingRecoveryModelSession,
2252
+ ): TelegramInlineKeyboard {
2348
2253
  const buttons: Array<{ text: string; callbackData: string }> = [];
2349
2254
  let index = 0;
2350
2255
  for (const profile of session.profiles.slice(0, 20)) {
2351
2256
  index += 1;
2352
- const switchesModel = buildActionModelSwitchWarning({
2353
- session,
2354
- effectiveModelProfileId: profile.id,
2355
- });
2257
+ const switchesModel =
2258
+ session.kind === "action_model" &&
2259
+ buildActionModelSwitchWarning({
2260
+ session,
2261
+ effectiveModelProfileId: profile.id,
2262
+ });
2356
2263
  buttons.push({
2357
2264
  text: `${switchesModel ? "⚠ " : ""}${profile.id}`,
2358
2265
  callbackData: `ams:${session.instanceId}:${session.sessionId}:${index}`,
2359
2266
  });
2360
2267
  }
2361
- const resolved = session.preview.resolvedModel;
2268
+ const resolved = session.kind === "action_model" ? session.preview.resolvedModel : null;
2362
2269
  const resolvedProfileId = resolved?.status === "resolved" ? resolved.modelProfileId : null;
2363
- const keepingCurrentSwitchesModel = resolvedProfileId
2364
- ? buildActionModelSwitchWarning({ session, effectiveModelProfileId: resolvedProfileId })
2365
- : null;
2270
+ const keepingCurrentSwitchesModel =
2271
+ session.kind === "action_model" && resolvedProfileId
2272
+ ? buildActionModelSwitchWarning({ session, effectiveModelProfileId: resolvedProfileId })
2273
+ : null;
2366
2274
  buttons.push({
2367
2275
  text: `${keepingCurrentSwitchesModel ? "⚠ " : ""}Keep current`,
2368
2276
  callbackData: `amk:${session.instanceId}:${session.sessionId}`,
2369
2277
  });
2370
- return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
2278
+ return { inlineKeyboard: rows(buttons, 1) };
2371
2279
  }
2372
2280
 
2373
2281
  private async applyActionFormStep(
@@ -2400,23 +2308,6 @@ export class TelegramBridge {
2400
2308
  });
2401
2309
  }
2402
2310
 
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
2311
  private async skipCurrentActionFormField(
2421
2312
  key: string,
2422
2313
  sessionId: string,
@@ -2450,7 +2341,7 @@ export class TelegramBridge {
2450
2341
  );
2451
2342
  return;
2452
2343
  }
2453
- await this.applyActionFormSkip(key, session, thread);
2344
+ await this.applyActionFormStep(key, session, applyFormSkip(session), thread);
2454
2345
  }
2455
2346
 
2456
2347
  private async handleSessionText(
@@ -2509,22 +2400,13 @@ export class TelegramBridge {
2509
2400
  );
2510
2401
  return;
2511
2402
  }
2512
- if (session.kind === "action_model") {
2403
+ if (session.kind === "action_model" || session.kind === "recovery_model") {
2513
2404
  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);
2405
+ if (session.kind === "action_model") {
2406
+ await this.handleActionModelSkip(key, session.sessionId, thread);
2407
+ } else {
2408
+ await this.executeRecoveryModelSession(key, session, thread);
2409
+ }
2528
2410
  return;
2529
2411
  }
2530
2412
  if (name === "cancel") {
@@ -2532,7 +2414,7 @@ export class TelegramBridge {
2532
2414
  await this.sendHtml(thread, "Cancelled.");
2533
2415
  return;
2534
2416
  }
2535
- await this.handleRecoveryModelText(key, session, text, thread);
2417
+ await this.handleModelText(key, session, text, thread);
2536
2418
  return;
2537
2419
  }
2538
2420
  if (name === "skip") {
@@ -2548,31 +2430,33 @@ export class TelegramBridge {
2548
2430
  }
2549
2431
  return;
2550
2432
  }
2551
- await this.applyActionFormSkip(key, session as PendingActionFormSession, thread);
2433
+ await this.applyActionFormStep(key, session, applyFormSkip(session), thread);
2552
2434
  return;
2553
2435
  }
2554
- await this.applyActionFormText(key, session as PendingActionFormSession, text, thread);
2436
+ await this.applyActionFormStep(key, session, applyFormText(session, text), thread);
2555
2437
  }
2556
2438
 
2557
- private async handleActionModelText(
2439
+ private async handleModelText(
2558
2440
  sessionKey: string,
2559
- session: PendingActionModelSession,
2441
+ session: PendingActionModelSession | PendingRecoveryModelSession,
2560
2442
  text: string,
2561
2443
  thread: TelegramProcessThread,
2562
2444
  ): Promise<void> {
2563
2445
  const profile = resolveProfileByTextOrIndex(text.trim(), session.profiles);
2564
- if (profile) {
2446
+ if (!profile) {
2447
+ await this.sendModelPrompt(thread, session, "Model must match an available profile.\n");
2448
+ return;
2449
+ }
2450
+ if (session.kind === "action_model") {
2565
2451
  this.sessions.delete(sessionKey);
2566
2452
  await this.sendActionModelSwitchWarning(session, profile.id, thread);
2567
2453
  return this.executeActionModelSession(session, thread, {
2568
2454
  nextTurnModelProfileId: profile.id,
2569
2455
  });
2570
2456
  }
2571
- await this.sendHtml(
2572
- thread,
2573
- escapeHtml(`Model must match an available profile.\n${buildActionModelPrompt({ session })}`),
2574
- this.buildActionModelReplyMarkup(session),
2575
- );
2457
+ await this.executeRecoveryModelSession(sessionKey, session, thread, {
2458
+ nextTurnModelProfileId: profile.id,
2459
+ });
2576
2460
  }
2577
2461
 
2578
2462
  private async maybeSelectRecoveryModel(input: {
@@ -2595,64 +2479,20 @@ export class TelegramBridge {
2595
2479
  profiles,
2596
2480
  });
2597
2481
  this.sessions.set(input.sessionKey, session);
2598
- await this.sendRecoveryModelPrompt(input.thread, session);
2482
+ await this.sendModelPrompt(input.thread, session);
2599
2483
  } catch (error) {
2600
2484
  this.logError(error, "Recovery model selection failed; falling back to direct execution");
2601
2485
  return input.execute();
2602
2486
  }
2603
2487
  }
2604
2488
 
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
2489
  private async executeRecoveryModelSession(
2490
+ sessionKey: string,
2652
2491
  session: PendingRecoveryModelSession,
2653
2492
  thread: TelegramProcessThread,
2654
2493
  opts?: { nextTurnModelProfileId?: string | null },
2655
2494
  ): Promise<void> {
2495
+ this.sessions.delete(sessionKey);
2656
2496
  if (session.recoveryKind === "retry") {
2657
2497
  const retryOpts = {
2658
2498
  ...(opts?.nextTurnModelProfileId !== undefined ? opts : {}),
@@ -2673,36 +2513,6 @@ export class TelegramBridge {
2673
2513
  }
2674
2514
  }
2675
2515
 
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
2516
  private async executeProcessAction(
2707
2517
  instanceId: string,
2708
2518
  action: TelegramActionExecutionSummary,
package/src/config.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
2
+
1
3
  export interface TelegramExtensionConfig {
2
4
  enabled: boolean;
3
5
  botToken: string;
@@ -25,10 +27,6 @@ interface RawTelegramConfig {
25
27
  allowed_model_profile_ids?: unknown;
26
28
  }
27
29
 
28
- function isRecord(value: unknown): value is Record<string, unknown> {
29
- return typeof value === "object" && value !== null && !Array.isArray(value);
30
- }
31
-
32
30
  function normalizeUserIds(value: unknown): number[] {
33
31
  if (!Array.isArray(value)) return [];
34
32
  return [
@@ -179,6 +179,14 @@ export function canSkipActionFormField(field: FormFieldDefinition | null | undef
179
179
  return Boolean(field && !field.required);
180
180
  }
181
181
 
182
+ function advanceFormField(session: PendingActionFormSession): FormStepResult {
183
+ session.fieldIndex += 1;
184
+ const field = currentField(session);
185
+ return field
186
+ ? { ok: true, done: false, prompt: buildFieldPrompt(field) }
187
+ : { ok: true, done: true, values: session.values };
188
+ }
189
+
182
190
  export function applyFormSkip(session: PendingActionFormSession): FormStepResult {
183
191
  const field = currentField(session);
184
192
  if (!field) {
@@ -187,12 +195,7 @@ export function applyFormSkip(session: PendingActionFormSession): FormStepResult
187
195
  if (!canSkipActionFormField(field)) {
188
196
  return { ok: false, prompt: `${field.label} is required.\n${buildFieldPrompt(field)}` };
189
197
  }
190
- session.fieldIndex += 1;
191
- const next = currentField(session);
192
- if (!next) {
193
- return { ok: true, done: true, values: session.values };
194
- }
195
- return { ok: true, done: false, prompt: buildFieldPrompt(next) };
198
+ return advanceFormField(session);
196
199
  }
197
200
 
198
201
  function parseBoolean(value: string): boolean | null {
@@ -238,12 +241,7 @@ export function applyFormText(session: PendingActionFormSession, text: string):
238
241
  return { ok: false, prompt: `${parsed.error}\n${buildFieldPrompt(field)}` };
239
242
  }
240
243
  session.values[field.id] = parsed.value;
241
- session.fieldIndex += 1;
242
- const next = currentField(session);
243
- if (!next) {
244
- return { ok: true, done: true, values: session.values };
245
- }
246
- return { ok: true, done: false, prompt: buildFieldPrompt(next) };
244
+ return advanceFormField(session);
247
245
  }
248
246
 
249
247
  export function buildActionModelSession(input: {