@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/config.ts ADDED
@@ -0,0 +1,108 @@
1
+ export interface TelegramExtensionConfig {
2
+ enabled: boolean;
3
+ botToken: string;
4
+ allowUserIds: readonly number[];
5
+ delivery: { forumChatId: string };
6
+ markdown: { maxChars: number };
7
+ topicTitleTemplate: string;
8
+ actionModelSelection: { enabled: boolean };
9
+ allowedModelProfileIds: readonly string[];
10
+ }
11
+
12
+ export type TelegramConfigResult =
13
+ | { ok: true; config: TelegramExtensionConfig }
14
+ | { ok: false; errors: readonly string[] };
15
+
16
+ interface RawTelegramConfig {
17
+ enabled?: unknown;
18
+ bot_token?: unknown;
19
+ bot_token_env?: unknown;
20
+ allow_user_ids?: unknown;
21
+ delivery?: unknown;
22
+ markdown?: unknown;
23
+ topic_title_template?: unknown;
24
+ action_model_selection?: unknown;
25
+ allowed_model_profile_ids?: unknown;
26
+ }
27
+
28
+ function isRecord(value: unknown): value is Record<string, unknown> {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
31
+
32
+ function normalizeUserIds(value: unknown): number[] {
33
+ if (!Array.isArray(value)) return [];
34
+ return [
35
+ ...new Set(
36
+ value
37
+ .map((entry) =>
38
+ typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN,
39
+ )
40
+ .filter(Number.isSafeInteger),
41
+ ),
42
+ ];
43
+ }
44
+
45
+ function readInlineToken(raw: RawTelegramConfig): string {
46
+ return typeof raw.bot_token === "string" ? raw.bot_token.trim() : "";
47
+ }
48
+
49
+ function readToken(raw: RawTelegramConfig): string {
50
+ const envName = typeof raw.bot_token_env === "string" ? raw.bot_token_env.trim() : "";
51
+ return envName ? (process.env[envName]?.trim() ?? readInlineToken(raw)) : readInlineToken(raw);
52
+ }
53
+
54
+ function normalizeAllowedModelProfileIds(value: unknown): string[] {
55
+ if (!Array.isArray(value)) return [];
56
+ return [
57
+ ...new Set(
58
+ value
59
+ .filter((entry): entry is string => typeof entry === "string")
60
+ .map((entry) => entry.trim())
61
+ .filter(Boolean),
62
+ ),
63
+ ];
64
+ }
65
+
66
+ export function normalizeTelegramConfig(rawValue: unknown): TelegramConfigResult {
67
+ const raw = (isRecord(rawValue) ? rawValue : {}) as RawTelegramConfig;
68
+ const delivery = isRecord(raw.delivery) ? raw.delivery : {};
69
+ const markdown = isRecord(raw.markdown) ? raw.markdown : {};
70
+ const actionModelSelection = isRecord(raw.action_model_selection)
71
+ ? raw.action_model_selection
72
+ : {};
73
+ const config: TelegramExtensionConfig = {
74
+ enabled: raw.enabled === true,
75
+ botToken: readToken(raw),
76
+ allowUserIds: normalizeUserIds(raw.allow_user_ids),
77
+ delivery: {
78
+ forumChatId: typeof delivery.forum_chat_id === "string" ? delivery.forum_chat_id.trim() : "",
79
+ },
80
+ markdown: {
81
+ maxChars:
82
+ typeof markdown.max_chars === "number" && Number.isSafeInteger(markdown.max_chars)
83
+ ? Math.min(Math.max(markdown.max_chars, 500), 4096)
84
+ : 3900,
85
+ },
86
+ topicTitleTemplate:
87
+ typeof raw.topic_title_template === "string" && raw.topic_title_template.trim()
88
+ ? raw.topic_title_template.trim()
89
+ : "{title} · {shortId}",
90
+ actionModelSelection: {
91
+ enabled: actionModelSelection.enabled !== false,
92
+ },
93
+ allowedModelProfileIds: normalizeAllowedModelProfileIds(raw.allowed_model_profile_ids),
94
+ };
95
+
96
+ if (!config.enabled) return { ok: true, config };
97
+
98
+ const errors: string[] = [];
99
+ if (!config.botToken)
100
+ errors.push("extensions.telegram requires bot_token_env or bot_token when enabled");
101
+ if (config.allowUserIds.length === 0) {
102
+ errors.push("extensions.telegram.allow_user_ids must contain at least one Telegram user id");
103
+ }
104
+ if (!config.delivery.forumChatId) {
105
+ errors.push("extensions.telegram.delivery.forum_chat_id is required for forum topic delivery");
106
+ }
107
+ return errors.length ? { ok: false, errors } : { ok: true, config };
108
+ }
@@ -0,0 +1,167 @@
1
+ import {
2
+ BaseTelegramClientEventRegistrar,
3
+ type TelegramCallbackUpdate,
4
+ type TelegramClient,
5
+ type TelegramForumTopicClosedUpdate,
6
+ type TelegramForumTopicCreatedUpdate,
7
+ type TelegramSendFileInput,
8
+ type TelegramSendMessageInput,
9
+ type TelegramSentMessage,
10
+ type TelegramTextUpdate,
11
+ } from "./types.js";
12
+
13
+ export interface FakeTelegramTopic {
14
+ chatId: string;
15
+ name: string;
16
+ messageThreadId: number;
17
+ }
18
+
19
+ export interface FakeTelegramTopicEdit {
20
+ chatId: string;
21
+ messageThreadId: number;
22
+ name: string;
23
+ }
24
+
25
+ export interface FakeTelegramTopicClose {
26
+ chatId: string;
27
+ messageThreadId: number;
28
+ }
29
+
30
+ export interface FakeTelegramAnswerCallback {
31
+ callbackQueryId: string;
32
+ text?: string;
33
+ showAlert?: boolean;
34
+ }
35
+
36
+ export type FakeTelegramOperation =
37
+ | { kind: "createForumTopic"; input: FakeTelegramTopic }
38
+ | { kind: "editForumTopic"; input: FakeTelegramTopicEdit }
39
+ | { kind: "closeForumTopic"; input: FakeTelegramTopicClose }
40
+ | { kind: "sendMessage"; input: TelegramSendMessageInput }
41
+ | { kind: "sendPhoto"; input: TelegramSendFileInput }
42
+ | { kind: "sendDocument"; input: TelegramSendFileInput }
43
+ | { kind: "answerCallbackQuery"; input: FakeTelegramAnswerCallback };
44
+
45
+ export class FakeTelegramClient extends BaseTelegramClientEventRegistrar implements TelegramClient {
46
+ readonly operations: FakeTelegramOperation[] = [];
47
+ readonly createdTopics: FakeTelegramTopic[] = [];
48
+ readonly editedTopics: FakeTelegramTopicEdit[] = [];
49
+ readonly closedTopics: FakeTelegramTopicClose[] = [];
50
+ readonly sentMessages: TelegramSendMessageInput[] = [];
51
+ readonly sentPhotos: TelegramSendFileInput[] = [];
52
+ readonly sentDocuments: TelegramSendFileInput[] = [];
53
+ readonly answeredCallbacks: FakeTelegramAnswerCallback[] = [];
54
+ private nextThreadId = 100;
55
+ private nextMessageId = 1;
56
+ private createForumTopicFailures: Error[] = [];
57
+ private sendPhotoFailures: Error[] = [];
58
+ private sendDocumentFailures: Error[] = [];
59
+ private sendMessageFailure: { remainingSuccessfulSends: number; error: Error } | null = null;
60
+ started = false;
61
+
62
+ async start(): Promise<void> {
63
+ this.started = true;
64
+ }
65
+
66
+ async stop(): Promise<void> {
67
+ this.started = false;
68
+ }
69
+
70
+ failNextCreateForumTopic(error = new Error("createForumTopic failed")): void {
71
+ this.createForumTopicFailures.push(error);
72
+ }
73
+
74
+ failSendMessageAfter(successfulSends: number, error = new Error("sendMessage failed")): void {
75
+ this.sendMessageFailure = {
76
+ remainingSuccessfulSends: Math.max(0, successfulSends),
77
+ error,
78
+ };
79
+ }
80
+
81
+ failNextSendPhoto(error = new Error("sendPhoto failed")): void {
82
+ this.sendPhotoFailures.push(error);
83
+ }
84
+
85
+ failNextSendDocument(error = new Error("sendDocument failed")): void {
86
+ this.sendDocumentFailures.push(error);
87
+ }
88
+
89
+ async createForumTopic(input: {
90
+ chatId: string;
91
+ name: string;
92
+ }): Promise<{ messageThreadId: number }> {
93
+ const failure = this.createForumTopicFailures.shift();
94
+ if (failure) {
95
+ throw failure;
96
+ }
97
+ const topic = {
98
+ chatId: input.chatId,
99
+ name: input.name,
100
+ messageThreadId: this.nextThreadId++,
101
+ };
102
+ this.operations.push({ kind: "createForumTopic", input: topic });
103
+ this.createdTopics.push(topic);
104
+ return { messageThreadId: topic.messageThreadId };
105
+ }
106
+
107
+ async editForumTopic(input: FakeTelegramTopicEdit): Promise<void> {
108
+ this.operations.push({ kind: "editForumTopic", input });
109
+ this.editedTopics.push(input);
110
+ }
111
+
112
+ async closeForumTopic(input: FakeTelegramTopicClose): Promise<void> {
113
+ this.operations.push({ kind: "closeForumTopic", input });
114
+ this.closedTopics.push(input);
115
+ }
116
+
117
+ async sendMessage(input: TelegramSendMessageInput): Promise<TelegramSentMessage> {
118
+ const failure = this.sendMessageFailure;
119
+ if (failure) {
120
+ if (failure.remainingSuccessfulSends <= 0) {
121
+ this.sendMessageFailure = null;
122
+ throw failure.error;
123
+ }
124
+ failure.remainingSuccessfulSends -= 1;
125
+ }
126
+ this.operations.push({ kind: "sendMessage", input });
127
+ this.sentMessages.push(input);
128
+ return { messageId: this.nextMessageId++ };
129
+ }
130
+
131
+ async sendPhoto(input: TelegramSendFileInput): Promise<TelegramSentMessage> {
132
+ const failure = this.sendPhotoFailures.shift();
133
+ if (failure) throw failure;
134
+ this.operations.push({ kind: "sendPhoto", input });
135
+ this.sentPhotos.push(input);
136
+ return { messageId: this.nextMessageId++ };
137
+ }
138
+
139
+ async sendDocument(input: TelegramSendFileInput): Promise<TelegramSentMessage> {
140
+ const failure = this.sendDocumentFailures.shift();
141
+ if (failure) throw failure;
142
+ this.operations.push({ kind: "sendDocument", input });
143
+ this.sentDocuments.push(input);
144
+ return { messageId: this.nextMessageId++ };
145
+ }
146
+
147
+ async answerCallbackQuery(input: FakeTelegramAnswerCallback): Promise<void> {
148
+ this.operations.push({ kind: "answerCallbackQuery", input });
149
+ this.answeredCallbacks.push(input);
150
+ }
151
+
152
+ async simulateText(update: TelegramTextUpdate): Promise<void> {
153
+ await Promise.all([...this.textHandlers].map((handler) => handler(update)));
154
+ }
155
+
156
+ async simulateCallback(update: TelegramCallbackUpdate): Promise<void> {
157
+ await Promise.all([...this.callbackHandlers].map((handler) => handler(update)));
158
+ }
159
+
160
+ async simulateForumTopicCreated(update: TelegramForumTopicCreatedUpdate): Promise<void> {
161
+ await Promise.all([...this.forumTopicCreatedHandlers].map((handler) => handler(update)));
162
+ }
163
+
164
+ async simulateForumTopicClosed(update: TelegramForumTopicClosedUpdate): Promise<void> {
165
+ await Promise.all([...this.forumTopicClosedHandlers].map((handler) => handler(update)));
166
+ }
167
+ }
@@ -0,0 +1,359 @@
1
+ import {
2
+ emptyQuestionDrafts,
3
+ type ProcessQuestionRequest,
4
+ type QuestionAnswerDraft,
5
+ } from "@leitwerk-dev/domain";
6
+ import type {
7
+ FormDefinition,
8
+ FormFieldDefinition,
9
+ ModelProfileOptionSummaryLike,
10
+ ProcessActionModelPreviewLike,
11
+ } from "@leitwerk-dev/process-sdk";
12
+ import { resolvePromptCacheSwitch } from "@leitwerk-dev/protocol/http-contracts";
13
+
14
+ export interface ActionPreviewLike {
15
+ kind?: string;
16
+ turnId?: string;
17
+ lifecycleStatus?: string;
18
+ }
19
+
20
+ export type PendingTelegramSession =
21
+ | {
22
+ kind: "action_form";
23
+ instanceId: string;
24
+ actionId: string;
25
+ actionLabel: string;
26
+ actionPreview?: ActionPreviewLike | null;
27
+ sessionId: string;
28
+ form: FormDefinition;
29
+ fieldIndex: number;
30
+ values: Record<string, unknown>;
31
+ expiresAt: number;
32
+ }
33
+ | {
34
+ kind: "action_model";
35
+ instanceId: string;
36
+ actionId: string;
37
+ actionLabel: string;
38
+ actionPreview?: ActionPreviewLike | null;
39
+ sessionId: string;
40
+ formValues: Record<string, unknown>;
41
+ preview: ProcessActionModelPreviewLike;
42
+ profiles: readonly ModelProfileOptionSummaryLike[];
43
+ expiresAt: number;
44
+ }
45
+ | {
46
+ kind: "recovery_model";
47
+ instanceId: string;
48
+ recoveryKind: "retry" | "continue";
49
+ turnRecordId?: string;
50
+ sessionId: string;
51
+ profiles: readonly ModelProfileOptionSummaryLike[];
52
+ selectedModelProfileId?: string | null;
53
+ expiresAt: number;
54
+ }
55
+ | {
56
+ kind: "continue";
57
+ instanceId: string;
58
+ turnRecordId: string;
59
+ nextTurnModelProfileId?: string | null;
60
+ expiresAt: number;
61
+ }
62
+ | {
63
+ kind: "question";
64
+ instanceId: string;
65
+ request: ProcessQuestionRequest;
66
+ questionIndex: number;
67
+ draft: QuestionAnswerDraft[];
68
+ expiresAt: number;
69
+ };
70
+
71
+ export type PendingActionFormSession = Extract<PendingTelegramSession, { kind: "action_form" }>;
72
+ export type PendingActionModelSession = Extract<PendingTelegramSession, { kind: "action_model" }>;
73
+ export type PendingQuestionSession = Extract<PendingTelegramSession, { kind: "question" }>;
74
+
75
+ export type FormStepResult =
76
+ | { ok: true; done: false; prompt: string }
77
+ | { ok: true; done: true; values: Record<string, unknown> }
78
+ | { ok: false; prompt: string };
79
+
80
+ export function buildActionFormSession(input: {
81
+ instanceId: string;
82
+ actionId: string;
83
+ actionLabel?: string;
84
+ actionPreview?: ActionPreviewLike | null;
85
+ sessionId: string;
86
+ form: FormDefinition;
87
+ now?: number;
88
+ ttlMs?: number;
89
+ }): PendingActionFormSession {
90
+ return {
91
+ kind: "action_form",
92
+ instanceId: input.instanceId,
93
+ actionId: input.actionId,
94
+ actionLabel: input.actionLabel ?? input.actionId,
95
+ actionPreview: input.actionPreview ?? null,
96
+ sessionId: input.sessionId,
97
+ form: input.form,
98
+ fieldIndex: 0,
99
+ values: {},
100
+ expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1000),
101
+ };
102
+ }
103
+
104
+ export function buildQuestionSession(input: {
105
+ instanceId: string;
106
+ request: ProcessQuestionRequest;
107
+ }): PendingQuestionSession {
108
+ return {
109
+ kind: "question",
110
+ instanceId: input.instanceId,
111
+ request: input.request,
112
+ questionIndex: 0,
113
+ draft: emptyQuestionDrafts(input.request.questions),
114
+ expiresAt: Number.POSITIVE_INFINITY,
115
+ };
116
+ }
117
+
118
+ export function buildQuestionPrompt(session: PendingQuestionSession): string {
119
+ const question = session.request.questions[session.questionIndex];
120
+ if (!question) return "Send your answer.";
121
+ const options = question.options.map(
122
+ (option) => `• ${option.label}${option.details ? ` — ${option.details}` : ""}`,
123
+ );
124
+ return [
125
+ `❓ Question ${session.questionIndex + 1} of ${session.request.questions.length}`,
126
+ question.question,
127
+ ...options,
128
+ "Reply with your answer in free text.",
129
+ ].join("\n");
130
+ }
131
+
132
+ export function applyQuestionText(
133
+ session: PendingQuestionSession,
134
+ text: string,
135
+ ): { done: boolean; draft: QuestionAnswerDraft[]; prompt?: string } {
136
+ const answer = session.draft[session.questionIndex];
137
+ if (!answer || text.trim() === "") {
138
+ return {
139
+ done: false,
140
+ draft: session.draft,
141
+ prompt: `Answer must not be empty.\n${buildQuestionPrompt(session)}`,
142
+ };
143
+ }
144
+ answer.freeText = text.trim();
145
+ session.questionIndex += 1;
146
+ return session.questionIndex < session.request.questions.length
147
+ ? { done: false, draft: session.draft, prompt: buildQuestionPrompt(session) }
148
+ : { done: true, draft: session.draft };
149
+ }
150
+
151
+ export function buildContinueSession(input: {
152
+ instanceId: string;
153
+ turnRecordId: string;
154
+ nextTurnModelProfileId?: string | null;
155
+ now?: number;
156
+ ttlMs?: number;
157
+ }): Extract<PendingTelegramSession, { kind: "continue" }> {
158
+ return {
159
+ kind: "continue",
160
+ instanceId: input.instanceId,
161
+ turnRecordId: input.turnRecordId,
162
+ nextTurnModelProfileId: input.nextTurnModelProfileId ?? null,
163
+ expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1000),
164
+ };
165
+ }
166
+
167
+ export function currentField(session: PendingActionFormSession): FormFieldDefinition | null {
168
+ return session.form.fields[session.fieldIndex] ?? null;
169
+ }
170
+
171
+ export function buildFieldPrompt(field: FormFieldDefinition): string {
172
+ const required = field.required ? " required" : "";
173
+ const description = field.description ? `\n${field.description}` : "";
174
+ const hint = field.placeholder ? `\nHint: ${field.placeholder}` : "";
175
+ return `Enter ${field.label}${required}.${description}${hint}`;
176
+ }
177
+
178
+ export function canSkipActionFormField(field: FormFieldDefinition | null | undefined): boolean {
179
+ return Boolean(field && !field.required);
180
+ }
181
+
182
+ export function applyFormSkip(session: PendingActionFormSession): FormStepResult {
183
+ const field = currentField(session);
184
+ if (!field) {
185
+ return { ok: true, done: true, values: session.values };
186
+ }
187
+ if (!canSkipActionFormField(field)) {
188
+ return { ok: false, prompt: `${field.label} is required.\n${buildFieldPrompt(field)}` };
189
+ }
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) };
196
+ }
197
+
198
+ function parseBoolean(value: string): boolean | null {
199
+ const normalized = value.trim().toLowerCase();
200
+ if (["yes", "y", "true", "1"].includes(normalized)) return true;
201
+ if (["no", "n", "false", "0"].includes(normalized)) return false;
202
+ return null;
203
+ }
204
+
205
+ function parseFieldValue(
206
+ field: FormFieldDefinition,
207
+ text: string,
208
+ ): { ok: true; value: unknown } | { ok: false; error: string } {
209
+ const trimmed = text.trim();
210
+ if (!trimmed && field.required) {
211
+ return { ok: false, error: `${field.label} is required.` };
212
+ }
213
+ if (!trimmed) {
214
+ return { ok: true, value: "" };
215
+ }
216
+ if (field.kind === "number") {
217
+ const value = Number(trimmed);
218
+ return Number.isFinite(value)
219
+ ? { ok: true, value }
220
+ : { ok: false, error: `${field.label} must be a number.` };
221
+ }
222
+ if (field.kind === "boolean") {
223
+ const value = parseBoolean(trimmed);
224
+ return value === null
225
+ ? { ok: false, error: `${field.label} must be yes or no.` }
226
+ : { ok: true, value };
227
+ }
228
+ return { ok: true, value: text };
229
+ }
230
+
231
+ export function applyFormText(session: PendingActionFormSession, text: string): FormStepResult {
232
+ const field = currentField(session);
233
+ if (!field) {
234
+ return { ok: true, done: true, values: session.values };
235
+ }
236
+ const parsed = parseFieldValue(field, text);
237
+ if (!parsed.ok) {
238
+ return { ok: false, prompt: `${parsed.error}\n${buildFieldPrompt(field)}` };
239
+ }
240
+ 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) };
247
+ }
248
+
249
+ export function buildActionModelSession(input: {
250
+ instanceId: string;
251
+ actionId: string;
252
+ actionLabel: string;
253
+ actionPreview?: ActionPreviewLike | null;
254
+ sessionId: string;
255
+ formValues: Record<string, unknown>;
256
+ preview: ProcessActionModelPreviewLike;
257
+ profiles: readonly ModelProfileOptionSummaryLike[];
258
+ now?: number;
259
+ ttlMs?: number;
260
+ }): PendingActionModelSession {
261
+ return {
262
+ kind: "action_model",
263
+ instanceId: input.instanceId,
264
+ actionId: input.actionId,
265
+ actionLabel: input.actionLabel,
266
+ actionPreview: input.actionPreview ?? null,
267
+ sessionId: input.sessionId,
268
+ formValues: input.formValues,
269
+ preview: input.preview,
270
+ profiles: input.profiles,
271
+ expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1000),
272
+ };
273
+ }
274
+
275
+ export function buildActionModelSwitchWarning(input: {
276
+ session: PendingActionModelSession;
277
+ effectiveModelProfileId: string;
278
+ now?: number;
279
+ }): string | null {
280
+ const resolution = resolvePromptCacheSwitch({
281
+ context: input.session.preview.warmPromptCache,
282
+ effectiveModelProfileId: input.effectiveModelProfileId,
283
+ selectableModelProfileIds: input.session.profiles.map((profile) => profile.id),
284
+ now: input.now,
285
+ });
286
+ if (!resolution.switchingModelMayBypassPromptCache) return null;
287
+ const recommendedId = resolution.recommendedModelProfileId;
288
+ if (!recommendedId) {
289
+ return "⚠ Switching models may lose prompt-cache reuse and increase costs. No equivalent selectable profile is currently available.";
290
+ }
291
+ const recommendation =
292
+ input.session.profiles.find((profile) => profile.id === recommendedId)?.label ?? recommendedId;
293
+ return `⚠ Switching models may lose prompt-cache reuse and increase costs. To keep using the previous model, choose ${recommendation}.`;
294
+ }
295
+
296
+ export function buildActionModelPrompt(input: { session: PendingActionModelSession }): string {
297
+ const { session } = input;
298
+ const lines = [`Next-turn model for: ${session.actionLabel}`];
299
+ const preview = session.preview;
300
+ if (preview.description) {
301
+ lines.push(`Target turn: ${preview.description}`);
302
+ }
303
+ const resolved = preview.resolvedModel;
304
+ if (resolved?.status === "resolved" && resolved.modelProfileId) {
305
+ const label =
306
+ session.profiles.find((p) => p.id === resolved.modelProfileId)?.label ??
307
+ resolved.modelProfileId;
308
+ lines.push(`Default/resolved: ${label}`);
309
+ } else if (resolved?.status === "none") {
310
+ lines.push("No model is currently resolved.");
311
+ }
312
+ if (session.profiles.length === 0) {
313
+ lines.push("No model profiles are available.");
314
+ } else {
315
+ lines.push("Choose a model by button, number, or profile id.");
316
+ lines.push("Send /skip to keep the default/resolved model.");
317
+ }
318
+ lines.push("Send /cancel to discard.");
319
+ return lines.join("\n");
320
+ }
321
+
322
+ export type PendingRecoveryModelSession = Extract<
323
+ PendingTelegramSession,
324
+ { kind: "recovery_model" }
325
+ >;
326
+
327
+ export function buildRecoveryModelSession(input: {
328
+ instanceId: string;
329
+ recoveryKind: "retry" | "continue";
330
+ turnRecordId?: string;
331
+ sessionId: string;
332
+ profiles: readonly ModelProfileOptionSummaryLike[];
333
+ now?: number;
334
+ ttlMs?: number;
335
+ }): PendingRecoveryModelSession {
336
+ return {
337
+ kind: "recovery_model",
338
+ instanceId: input.instanceId,
339
+ recoveryKind: input.recoveryKind,
340
+ turnRecordId: input.turnRecordId,
341
+ sessionId: input.sessionId,
342
+ profiles: input.profiles,
343
+ expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1000),
344
+ };
345
+ }
346
+
347
+ export function buildRecoveryModelPrompt(input: { session: PendingRecoveryModelSession }): string {
348
+ const { session } = input;
349
+ const label = session.recoveryKind === "retry" ? "Retry" : "Continue";
350
+ const lines = [`Next-turn model for: ${label}`];
351
+ if (session.profiles.length === 0) {
352
+ lines.push("No model profiles are available.");
353
+ } else {
354
+ lines.push("Choose a model by button, number, or profile id.");
355
+ lines.push("Send /skip to keep the current model.");
356
+ }
357
+ lines.push("Send /cancel to discard.");
358
+ return lines.join("\n");
359
+ }