@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.
- package/README.md +1 -1
- package/dist/actions.d.ts +1 -0
- package/dist/actions.d.ts.map +1 -1
- package/dist/bridge.d.ts +3 -10
- package/dist/bridge.d.ts.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/form-session.d.ts.map +1 -1
- package/dist/grammy-telegram-client.d.ts +17 -41
- package/dist/grammy-telegram-client.d.ts.map +1 -1
- package/dist/index.js +3722 -52
- package/dist/index.js.map +1 -1
- package/dist/launch-session.d.ts +1 -1
- package/dist/launch-session.d.ts.map +1 -1
- package/dist/types.d.ts +5 -6
- package/dist/types.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/actions.ts +14 -5
- package/src/bridge.ts +113 -303
- package/src/config.ts +2 -4
- package/src/form-session.ts +10 -12
- package/src/grammy-telegram-client.ts +23 -43
- package/src/launch-session.ts +30 -55
- package/src/types.ts +4 -7
- package/dist/actions.js +0 -32
- package/dist/actions.js.map +0 -1
- package/dist/actor.js +0 -7
- package/dist/actor.js.map +0 -1
- package/dist/bridge.js +0 -2032
- package/dist/bridge.js.map +0 -1
- package/dist/config.js +0 -70
- package/dist/config.js.map +0 -1
- package/dist/fake-telegram-client.js +0 -107
- package/dist/fake-telegram-client.js.map +0 -1
- package/dist/form-session.js +0 -218
- package/dist/form-session.js.map +0 -1
- package/dist/grammy-telegram-client.js +0 -195
- package/dist/grammy-telegram-client.js.map +0 -1
- package/dist/launch-session.js +0 -435
- package/dist/launch-session.js.map +0 -1
- package/dist/markdown-html.js +0 -259
- package/dist/markdown-html.js.map +0 -1
- package/dist/mermaid-image.js +0 -99
- package/dist/mermaid-image.js.map +0 -1
- package/dist/process-feed.js +0 -165
- package/dist/process-feed.js.map +0 -1
- package/dist/process-thread-store.js +0 -74
- package/dist/process-thread-store.js.map +0 -1
- package/dist/topic-title.js +0 -29
- package/dist/topic-title.js.map +0 -1
- package/dist/types.js +0 -19
- package/dist/types.js.map +0 -1
package/dist/bridge.js
DELETED
|
@@ -1,2032 +0,0 @@
|
|
|
1
|
-
import { randomBytes } from "node:crypto";
|
|
2
|
-
import { buildActionKeyboard, continuableFailedTurnRecordId } from "./actions.js";
|
|
3
|
-
import { TELEGRAM_ACTOR } from "./actor.js";
|
|
4
|
-
import { applyFormSkip, applyFormText, applyQuestionText, buildActionFormSession, buildActionModelPrompt, buildActionModelSession, buildActionModelSwitchWarning, buildContinueSession, buildFieldPrompt, buildQuestionPrompt, buildQuestionSession, buildRecoveryModelPrompt, buildRecoveryModelSession, canSkipActionFormField, currentField, } from "./form-session.js";
|
|
5
|
-
import { applyLaunchFieldText, applyLaunchFieldValue, applyLaunchModelStepAction, applyLaunchModelStepText, beginLaunchModelEdit, buildLaunchFieldPrompt, buildLaunchInput, buildLaunchModelConfig, buildLaunchModelStepPrompt, buildLaunchModelSummary, buildLaunchReview, createLaunchSession, currentLaunchField, currentLaunchModelStep, finishLaunchModelEdit, getLaunchFieldOptions, hasLaunchModelControls, moveLaunchSessionToValidationField, seedLaunchModelConfigFromPlan, } from "./launch-session.js";
|
|
6
|
-
import { escapeTelegramHtml as escapeHtml, renderResultMarkdownForTelegram, splitPlainTelegramText, splitTelegramHtml, telegramHtmlToPlainText, } from "./markdown-html.js";
|
|
7
|
-
import { renderMermaidPng } from "./mermaid-image.js";
|
|
8
|
-
import { buildActionSubmittedMessage, buildActionsPromptMessage, buildLeafOutcomeMessage, buildLifecycleMessage, buildProcessCreatedMessage, buildStatusMessage, buildTurnOutcomeMessage, buildTurnStartedMessage, formatTurnIdLabel, } from "./process-feed.js";
|
|
9
|
-
import { ProcessThreadStore, threadKey } from "./process-thread-store.js";
|
|
10
|
-
import { buildTopicTitle } from "./topic-title.js";
|
|
11
|
-
const LAUNCH_CALLBACK_PREFIX = "launch:";
|
|
12
|
-
const LAUNCH_SESSION_TTL_MS = 20 * 60 * 1000;
|
|
13
|
-
const MAX_LAUNCHER_BUTTONS = 30;
|
|
14
|
-
const MAX_FIELD_OPTION_BUTTONS = 20;
|
|
15
|
-
const MAX_MODEL_PROFILE_BUTTONS = 20;
|
|
16
|
-
const CONTINUE_PROMPT = "Send an optional continuation instruction, or send /skip to continue with the default prompt.";
|
|
17
|
-
function commandName(text) {
|
|
18
|
-
return /^\/(\w+)(?:@\w+)?(?:\s|$)/.exec(text.trim())?.[1]?.toLowerCase() ?? null;
|
|
19
|
-
}
|
|
20
|
-
function commandArgs(text) {
|
|
21
|
-
return text
|
|
22
|
-
.trim()
|
|
23
|
-
.replace(/^\/\w+(?:@\w+)?\s*/, "")
|
|
24
|
-
.trim();
|
|
25
|
-
}
|
|
26
|
-
function rows(items, size) {
|
|
27
|
-
return Array.from({ length: Math.ceil(items.length / size) }, (_, index) => [
|
|
28
|
-
...items.slice(index * size, index * size + size),
|
|
29
|
-
]);
|
|
30
|
-
}
|
|
31
|
-
function messageTarget(chatId, messageThreadId) {
|
|
32
|
-
return { chatId, ...(messageThreadId !== undefined ? { messageThreadId } : {}) };
|
|
33
|
-
}
|
|
34
|
-
function launchSessionKey(input) {
|
|
35
|
-
return typeof input.from?.id === "number"
|
|
36
|
-
? `${input.chatId}:${input.messageThreadId ?? 0}:${input.from.id}`
|
|
37
|
-
: null;
|
|
38
|
-
}
|
|
39
|
-
function splitScopedCallbackPayload(payload) {
|
|
40
|
-
const separator = payload.indexOf(":");
|
|
41
|
-
if (separator <= 0 || separator === payload.length - 1)
|
|
42
|
-
return null;
|
|
43
|
-
return {
|
|
44
|
-
instanceId: payload.slice(0, separator),
|
|
45
|
-
value: payload.slice(separator + 1),
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
function parseTripleCallbackPayload(payload) {
|
|
49
|
-
const parts = payload.split(":");
|
|
50
|
-
const [instanceId, sessionId, ...rest] = parts;
|
|
51
|
-
if (!instanceId || !sessionId)
|
|
52
|
-
return null;
|
|
53
|
-
return { instanceId, sessionId, value: rest.join(":") };
|
|
54
|
-
}
|
|
55
|
-
function parseActionFormSkipCallbackPayload(payload) {
|
|
56
|
-
const parsed = parseTripleCallbackPayload(payload);
|
|
57
|
-
if (!parsed)
|
|
58
|
-
return null;
|
|
59
|
-
return {
|
|
60
|
-
kind: "action_form_skip",
|
|
61
|
-
instanceId: parsed.instanceId,
|
|
62
|
-
sessionId: parsed.sessionId,
|
|
63
|
-
fieldId: parsed.value,
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
function parseCallbackCommand(data) {
|
|
67
|
-
if (data.startsWith("a:")) {
|
|
68
|
-
const scoped = splitScopedCallbackPayload(data.slice("a:".length));
|
|
69
|
-
return scoped
|
|
70
|
-
? { kind: "process_action", instanceId: scoped.instanceId, actionId: scoped.value }
|
|
71
|
-
: null;
|
|
72
|
-
}
|
|
73
|
-
if (data.startsWith("fs:")) {
|
|
74
|
-
return parseActionFormSkipCallbackPayload(data.slice("fs:".length));
|
|
75
|
-
}
|
|
76
|
-
if (data.startsWith("ams:")) {
|
|
77
|
-
return parseActionModelSelectCallbackPayload(data.slice("ams:".length));
|
|
78
|
-
}
|
|
79
|
-
if (data.startsWith("amk:")) {
|
|
80
|
-
return parseActionModelSkipCallbackPayload(data.slice("amk:".length));
|
|
81
|
-
}
|
|
82
|
-
if (data.startsWith("r:")) {
|
|
83
|
-
const instanceId = data.slice("r:".length);
|
|
84
|
-
return instanceId ? { kind: "retry", instanceId } : null;
|
|
85
|
-
}
|
|
86
|
-
if (data.startsWith("c:")) {
|
|
87
|
-
const instanceId = data.slice("c:".length);
|
|
88
|
-
return instanceId ? { kind: "continue", instanceId } : null;
|
|
89
|
-
}
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
function parseActionModelSelectCallbackPayload(payload) {
|
|
93
|
-
const parsed = parseTripleCallbackPayload(payload);
|
|
94
|
-
if (!parsed)
|
|
95
|
-
return null;
|
|
96
|
-
const profileIndex = Number(parsed.value);
|
|
97
|
-
if (!Number.isInteger(profileIndex) || profileIndex < 1)
|
|
98
|
-
return null;
|
|
99
|
-
return {
|
|
100
|
-
kind: "action_model_select",
|
|
101
|
-
instanceId: parsed.instanceId,
|
|
102
|
-
sessionId: parsed.sessionId,
|
|
103
|
-
profileIndex,
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
function parseActionModelSkipCallbackPayload(payload) {
|
|
107
|
-
const parsed = parseTripleCallbackPayload(payload);
|
|
108
|
-
if (!parsed)
|
|
109
|
-
return null;
|
|
110
|
-
return {
|
|
111
|
-
kind: "action_model_skip",
|
|
112
|
-
instanceId: parsed.instanceId,
|
|
113
|
-
sessionId: parsed.sessionId,
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
function resolveProfileByTextOrIndex(text, profiles) {
|
|
117
|
-
const byIdOrLabel = profiles.find((p) => p.id === text || p.label.toLowerCase() === text.toLowerCase());
|
|
118
|
-
if (byIdOrLabel)
|
|
119
|
-
return byIdOrLabel;
|
|
120
|
-
const index = Number(text);
|
|
121
|
-
if (Number.isInteger(index) && index >= 1 && index <= profiles.length) {
|
|
122
|
-
return profiles[index - 1] ?? null;
|
|
123
|
-
}
|
|
124
|
-
return null;
|
|
125
|
-
}
|
|
126
|
-
function resolveModelProfileFromSession(session, profileIndex) {
|
|
127
|
-
const profiles = session?.kind === "action_model"
|
|
128
|
-
? session.profiles
|
|
129
|
-
: session?.kind === "recovery_model"
|
|
130
|
-
? session.profiles
|
|
131
|
-
: null;
|
|
132
|
-
if (!profiles)
|
|
133
|
-
return null;
|
|
134
|
-
return profiles[profileIndex - 1] ?? null;
|
|
135
|
-
}
|
|
136
|
-
function processCanAcceptFreeText(process) {
|
|
137
|
-
return !["completed", "aborted", "error"].includes(process.lifecycleStatus);
|
|
138
|
-
}
|
|
139
|
-
function processIsFinished(process) {
|
|
140
|
-
return process.lifecycleStatus === "completed" || process.lifecycleStatus === "aborted";
|
|
141
|
-
}
|
|
142
|
-
function resultTurnRecordKey(instanceId, turnRecordId) {
|
|
143
|
-
return `${instanceId}:${turnRecordId}`;
|
|
144
|
-
}
|
|
145
|
-
function recoveryActionLabels(process) {
|
|
146
|
-
if (process.lifecycleStatus !== "error" || !process.currentExecution)
|
|
147
|
-
return [];
|
|
148
|
-
return ["Retry", ...(continuableFailedTurnRecordId(process) ? ["Continue"] : [])];
|
|
149
|
-
}
|
|
150
|
-
function readActionPreview(action) {
|
|
151
|
-
const preview = action.preview;
|
|
152
|
-
if (!isRecord(preview))
|
|
153
|
-
return null;
|
|
154
|
-
return {
|
|
155
|
-
...(typeof preview.kind === "string" ? { kind: preview.kind } : {}),
|
|
156
|
-
...(typeof preview.turnId === "string" ? { turnId: preview.turnId } : {}),
|
|
157
|
-
...(typeof preview.lifecycleStatus === "string"
|
|
158
|
-
? { lifecycleStatus: preview.lifecycleStatus }
|
|
159
|
-
: {}),
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
function shouldDeferActionPromptUntilTurnTerminalEvent(changedFields) {
|
|
163
|
-
return changedFields.includes("currentExecution");
|
|
164
|
-
}
|
|
165
|
-
function shouldDeferCompletedLifecycleUntilTurnOutcome(input) {
|
|
166
|
-
return (input.process.lifecycleStatus === "completed" &&
|
|
167
|
-
input.changedFields.includes("currentExecution"));
|
|
168
|
-
}
|
|
169
|
-
function isRecord(value) {
|
|
170
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
171
|
-
}
|
|
172
|
-
function readClaimedLaunchThread(process, expectedChatId) {
|
|
173
|
-
const telegram = isRecord(process.metadata?.telegram) ? process.metadata.telegram : null;
|
|
174
|
-
const thread = isRecord(telegram?.launchThread) ? telegram.launchThread : null;
|
|
175
|
-
return thread?.mode === "forum_topic" &&
|
|
176
|
-
thread.chatId === expectedChatId &&
|
|
177
|
-
typeof thread.messageThreadId === "number"
|
|
178
|
-
? { mode: "forum_topic", chatId: thread.chatId, messageThreadId: thread.messageThreadId }
|
|
179
|
-
: null;
|
|
180
|
-
}
|
|
181
|
-
function createActionFormSessionId() {
|
|
182
|
-
return randomBytes(4).toString("hex");
|
|
183
|
-
}
|
|
184
|
-
function attachLaunchThreadMetadata(launchPlan, thread) {
|
|
185
|
-
const metadata = launchPlan.processInput.metadata ?? {};
|
|
186
|
-
const telegram = isRecord(metadata.telegram) ? metadata.telegram : {};
|
|
187
|
-
return {
|
|
188
|
-
...launchPlan,
|
|
189
|
-
processInput: {
|
|
190
|
-
...launchPlan.processInput,
|
|
191
|
-
metadata: {
|
|
192
|
-
...metadata,
|
|
193
|
-
telegram: {
|
|
194
|
-
...telegram,
|
|
195
|
-
launchThread: { ...thread },
|
|
196
|
-
},
|
|
197
|
-
},
|
|
198
|
-
},
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
export class TelegramBridge {
|
|
202
|
-
input;
|
|
203
|
-
store;
|
|
204
|
-
sessions = new Map();
|
|
205
|
-
launchSessions = new Map();
|
|
206
|
-
launchCallbacks = new Map();
|
|
207
|
-
nextLaunchCallbackId = 1;
|
|
208
|
-
processModelSelection;
|
|
209
|
-
threadEligibleInstanceIds = new Set();
|
|
210
|
-
introSentInstanceIds = new Set();
|
|
211
|
-
closedThreadKeys = new Set();
|
|
212
|
-
sentResultTurnRecordKeys = new Set();
|
|
213
|
-
deferredCompletedLifecycleProcesses = new Map();
|
|
214
|
-
queues = new Map();
|
|
215
|
-
lastTurnInfo = new Map();
|
|
216
|
-
constructor(input) {
|
|
217
|
-
this.input = input;
|
|
218
|
-
this.store = new ProcessThreadStore(input.deps);
|
|
219
|
-
this.processModelSelection = input.deps.processModelSelection ?? null;
|
|
220
|
-
input.client.onText((update) => this.handleText(update));
|
|
221
|
-
input.client.onCallback((update) => this.handleCallback(update));
|
|
222
|
-
input.client.onForumTopicCreated((update) => this.handleForumTopicCreated(update));
|
|
223
|
-
input.client.onForumTopicClosed((update) => this.handleForumTopicClosed(update));
|
|
224
|
-
}
|
|
225
|
-
async start() {
|
|
226
|
-
for (const instanceId of this.store.rebuildFromEvents()) {
|
|
227
|
-
this.threadEligibleInstanceIds.add(instanceId);
|
|
228
|
-
this.introSentInstanceIds.add(instanceId);
|
|
229
|
-
}
|
|
230
|
-
this.seedLastTurnInfoFromEvents();
|
|
231
|
-
await this.input.client.start();
|
|
232
|
-
for (const request of this.input.deps.processQuestions?.listOpen() ?? []) {
|
|
233
|
-
await this.onQuestionRequested({ instanceId: request.instanceId, request });
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* After a server restart the in-memory lastTurnInfo map is empty.
|
|
238
|
-
* Rebuild it from the most recent turn_started event for every non-terminal
|
|
239
|
-
* process that already has a Telegram thread, so that /status and actions
|
|
240
|
-
* prompts show the correct path label without waiting for the next turn.
|
|
241
|
-
*/
|
|
242
|
-
seedLastTurnInfoFromEvents() {
|
|
243
|
-
for (const process of this.input.deps.processes.listAll()) {
|
|
244
|
-
if (["completed", "aborted"].includes(process.lifecycleStatus))
|
|
245
|
-
continue;
|
|
246
|
-
if (!this.store.getByInstanceId(process.id))
|
|
247
|
-
continue;
|
|
248
|
-
if (this.lastTurnInfo.has(process.id))
|
|
249
|
-
continue;
|
|
250
|
-
const events = this.input.deps.events.listByInstance(process.id, 50);
|
|
251
|
-
const turnStartedEvent = events.find((e) => e.eventType === "turn_started");
|
|
252
|
-
if (!turnStartedEvent)
|
|
253
|
-
continue;
|
|
254
|
-
const pathType = turnStartedEvent.data.pathType;
|
|
255
|
-
const turnId = turnStartedEvent.data.turnId;
|
|
256
|
-
if (pathType && turnId) {
|
|
257
|
-
this.lastTurnInfo.set(process.id, { pathType, turnId });
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
async stop() {
|
|
262
|
-
await this.input.client.stop();
|
|
263
|
-
}
|
|
264
|
-
register(events) {
|
|
265
|
-
const on = (event, handler) => events.on(event, (payload) => void this.enqueue(payload.instanceId, () => handler(payload)));
|
|
266
|
-
on("process_created", (payload) => this.onProcessCreated(payload));
|
|
267
|
-
on("process_updated", (payload) => this.onProcessUpdated(payload));
|
|
268
|
-
on("turn_started", (payload) => this.onTurnStarted(payload.turnRecord));
|
|
269
|
-
on("turn_failed", (payload) => this.onTurnFailed(payload));
|
|
270
|
-
on("leaf_outcome_captured", (payload) => this.onLeafOutcome(payload.snapshot));
|
|
271
|
-
on("question_requested", (payload) => this.onQuestionRequested(payload));
|
|
272
|
-
on("turn_outcome", (payload) => this.onTurnOutcome(payload));
|
|
273
|
-
}
|
|
274
|
-
enqueue(instanceId, task) {
|
|
275
|
-
const previous = this.queues.get(instanceId) ?? Promise.resolve();
|
|
276
|
-
const next = previous
|
|
277
|
-
.catch(() => undefined)
|
|
278
|
-
.then(task)
|
|
279
|
-
.catch((error) => this.logError(error, "Telegram bridge task failed"));
|
|
280
|
-
const stored = next.finally(() => {
|
|
281
|
-
if (this.queues.get(instanceId) === stored)
|
|
282
|
-
this.queues.delete(instanceId);
|
|
283
|
-
});
|
|
284
|
-
this.queues.set(instanceId, stored);
|
|
285
|
-
return stored;
|
|
286
|
-
}
|
|
287
|
-
async onProcessCreated(payload) {
|
|
288
|
-
this.threadEligibleInstanceIds.add(payload.process.id);
|
|
289
|
-
const thread = await this.ensureThread(payload.process);
|
|
290
|
-
if (!thread)
|
|
291
|
-
return;
|
|
292
|
-
await this.sendProcessIntro(thread, payload.process);
|
|
293
|
-
if (processIsFinished(payload.process)) {
|
|
294
|
-
await this.closeThread(thread);
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
if (["waiting", "error"].includes(payload.process.lifecycleStatus)) {
|
|
298
|
-
await this.sendActionsForProcess(payload.process);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
async onProcessUpdated(payload) {
|
|
302
|
-
const thread = await this.getThread(payload.process);
|
|
303
|
-
if (!thread)
|
|
304
|
-
return;
|
|
305
|
-
if (payload.changedFields.includes("title")) {
|
|
306
|
-
await this.syncThreadTitle(thread, payload.process);
|
|
307
|
-
}
|
|
308
|
-
const deferCompletedLifecycle = shouldDeferCompletedLifecycleUntilTurnOutcome({
|
|
309
|
-
process: payload.process,
|
|
310
|
-
changedFields: payload.changedFields,
|
|
311
|
-
});
|
|
312
|
-
if (deferCompletedLifecycle) {
|
|
313
|
-
this.deferredCompletedLifecycleProcesses.set(payload.process.id, payload.process);
|
|
314
|
-
}
|
|
315
|
-
else if (payload.changedFields.includes("lifecycleStatus")) {
|
|
316
|
-
this.deferredCompletedLifecycleProcesses.delete(payload.process.id);
|
|
317
|
-
const lifecycleMessage = buildLifecycleMessage({
|
|
318
|
-
process: payload.process,
|
|
319
|
-
status: payload.process.lifecycleStatus,
|
|
320
|
-
});
|
|
321
|
-
if (lifecycleMessage)
|
|
322
|
-
await this.sendHtml(thread, lifecycleMessage);
|
|
323
|
-
if (processIsFinished(payload.process)) {
|
|
324
|
-
await this.closeThread(thread);
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
if ((payload.process.lifecycleStatus === "waiting" ||
|
|
329
|
-
payload.process.lifecycleStatus === "error" ||
|
|
330
|
-
payload.changedFields.includes("selectedTurnId")) &&
|
|
331
|
-
!shouldDeferActionPromptUntilTurnTerminalEvent(payload.changedFields)) {
|
|
332
|
-
await this.sendActionsForProcess(payload.process);
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
async onTurnStarted(turnRecord) {
|
|
336
|
-
const thread = await this.getThread(turnRecord.instanceId);
|
|
337
|
-
if (!thread)
|
|
338
|
-
return;
|
|
339
|
-
const modelLabel = this.resolveTurnModelLabel(turnRecord);
|
|
340
|
-
const turnDescription = formatTurnIdLabel(turnRecord.turnId);
|
|
341
|
-
this.lastTurnInfo.set(turnRecord.instanceId, {
|
|
342
|
-
pathType: turnRecord.pathType,
|
|
343
|
-
turnId: turnRecord.turnId,
|
|
344
|
-
});
|
|
345
|
-
await this.sendHtml(thread, buildTurnStartedMessage(turnRecord, { turnDescription, modelLabel }));
|
|
346
|
-
}
|
|
347
|
-
async onQuestionRequested(payload) {
|
|
348
|
-
const thread = await this.getThread(payload.instanceId);
|
|
349
|
-
if (!thread)
|
|
350
|
-
return;
|
|
351
|
-
const key = threadKey(thread.chatId, thread.messageThreadId);
|
|
352
|
-
const existing = this.sessions.get(key);
|
|
353
|
-
if (existing?.kind === "question" && existing.request.id === payload.request.id)
|
|
354
|
-
return;
|
|
355
|
-
const session = buildQuestionSession(payload);
|
|
356
|
-
this.sessions.set(key, session);
|
|
357
|
-
await this.sendCurrentSessionPrompt(thread, session);
|
|
358
|
-
}
|
|
359
|
-
// Resolves the human-readable label for the model currently running in a turn.
|
|
360
|
-
// Intentionally queries unfiltered availableProfiles (not filtered through allowedModelProfileIds)
|
|
361
|
-
// because this describes what IS running, not what the user could have selected.
|
|
362
|
-
resolveTurnModelLabel(turnRecord) {
|
|
363
|
-
if (turnRecord.turnType !== "llm" || !turnRecord.modelProfileId)
|
|
364
|
-
return null;
|
|
365
|
-
const profile = this.processModelSelection
|
|
366
|
-
?.listAvailableProfiles(turnRecord.instanceId)
|
|
367
|
-
?.find((p) => p.id === turnRecord.modelProfileId);
|
|
368
|
-
return profile?.label ?? turnRecord.modelProfileId;
|
|
369
|
-
}
|
|
370
|
-
filterProfiles(profiles) {
|
|
371
|
-
const allowedIds = this.input.config.allowedModelProfileIds;
|
|
372
|
-
if (!allowedIds.length)
|
|
373
|
-
return profiles;
|
|
374
|
-
const allowed = new Set(allowedIds);
|
|
375
|
-
return profiles.filter((p) => allowed.has(p.id));
|
|
376
|
-
}
|
|
377
|
-
listSelectableProfiles(instanceId) {
|
|
378
|
-
if (!this.input.config.actionModelSelection.enabled || !this.processModelSelection)
|
|
379
|
-
return [];
|
|
380
|
-
return this.filterProfiles(this.processModelSelection.listAvailableProfiles(instanceId) ?? []);
|
|
381
|
-
}
|
|
382
|
-
filterLaunchSchemaAvailableProfiles(schema) {
|
|
383
|
-
return schema
|
|
384
|
-
? { ...schema, availableProfiles: this.filterProfiles(schema.availableProfiles) }
|
|
385
|
-
: null;
|
|
386
|
-
}
|
|
387
|
-
async onTurnFailed(payload) {
|
|
388
|
-
const { turnRecord } = payload;
|
|
389
|
-
const thread = await this.getThread(turnRecord.instanceId);
|
|
390
|
-
if (!thread)
|
|
391
|
-
return;
|
|
392
|
-
const errorSummary = payload.errorSummary.trim() || turnRecord.errorSummary || "Turn failed";
|
|
393
|
-
const errorClass = payload.errorClass ?? turnRecord.errorClass ?? null;
|
|
394
|
-
await this.sendHtml(thread, [
|
|
395
|
-
`⚠️ <b>Turn failed</b>: ${escapeHtml(turnRecord.turnId)}`,
|
|
396
|
-
`Error: ${escapeHtml(errorSummary)}`,
|
|
397
|
-
...(errorClass ? [`Class: ${escapeHtml(errorClass)}`] : []),
|
|
398
|
-
"",
|
|
399
|
-
"Use the recovery buttons for retry or continue options.",
|
|
400
|
-
].join("\n"));
|
|
401
|
-
const process = this.input.deps.processes.getById(turnRecord.instanceId);
|
|
402
|
-
if (process)
|
|
403
|
-
await this.sendActionsForProcess(process);
|
|
404
|
-
}
|
|
405
|
-
async sendPublishedResult(thread, input) {
|
|
406
|
-
const markdown = input.markdown.trim();
|
|
407
|
-
if (!markdown)
|
|
408
|
-
return;
|
|
409
|
-
const dedupeKey = resultTurnRecordKey(input.instanceId, input.turnRecordId);
|
|
410
|
-
if (this.sentResultTurnRecordKeys.has(dedupeKey))
|
|
411
|
-
return;
|
|
412
|
-
const parts = renderResultMarkdownForTelegram({
|
|
413
|
-
markdown,
|
|
414
|
-
instanceId: input.instanceId,
|
|
415
|
-
turnRecordId: input.turnRecordId,
|
|
416
|
-
});
|
|
417
|
-
const leadingHtml = parts[0]?.kind === "html" ? parts[0] : null;
|
|
418
|
-
await this.sendHtml(thread, input.buildMessage(leadingHtml?.html ?? ""));
|
|
419
|
-
await this.sendResultParts(thread, input.instanceId, input.turnRecordId, parts.slice(leadingHtml ? 1 : 0));
|
|
420
|
-
this.sentResultTurnRecordKeys.add(dedupeKey);
|
|
421
|
-
}
|
|
422
|
-
async onLeafOutcome(snapshot) {
|
|
423
|
-
const thread = await this.getThread(snapshot.instanceId);
|
|
424
|
-
if (!thread)
|
|
425
|
-
return;
|
|
426
|
-
const markdown = snapshot.fallbackMarkdown?.trim() ?? "";
|
|
427
|
-
if (markdown && snapshot.turnRecordId) {
|
|
428
|
-
await this.sendPublishedResult(thread, {
|
|
429
|
-
instanceId: snapshot.instanceId,
|
|
430
|
-
turnRecordId: snapshot.turnRecordId,
|
|
431
|
-
markdown,
|
|
432
|
-
buildMessage: (markdownHtml) => buildLeafOutcomeMessage({ snapshot, markdownHtml }),
|
|
433
|
-
});
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
await this.sendHtml(thread, buildLeafOutcomeMessage({ snapshot }));
|
|
437
|
-
}
|
|
438
|
-
async onTurnOutcome(payload) {
|
|
439
|
-
const thread = await this.getThread(payload.instanceId);
|
|
440
|
-
if (!thread)
|
|
441
|
-
return;
|
|
442
|
-
const pathType = this.lastTurnInfo.get(payload.instanceId)?.pathType ?? null;
|
|
443
|
-
await this.sendPublishedResult(thread, {
|
|
444
|
-
instanceId: payload.instanceId,
|
|
445
|
-
turnRecordId: payload.turnRecordId,
|
|
446
|
-
markdown: payload.turnResultMarkdown ?? "",
|
|
447
|
-
buildMessage: (markdownHtml) => buildTurnOutcomeMessage({
|
|
448
|
-
turnId: payload.turnId,
|
|
449
|
-
outcome: payload.outcome,
|
|
450
|
-
markdown: payload.turnResultMarkdown ?? "",
|
|
451
|
-
markdownHtml,
|
|
452
|
-
pathType,
|
|
453
|
-
}),
|
|
454
|
-
});
|
|
455
|
-
const deferredCompletedProcess = this.deferredCompletedLifecycleProcesses.get(payload.instanceId);
|
|
456
|
-
if (deferredCompletedProcess) {
|
|
457
|
-
this.deferredCompletedLifecycleProcesses.delete(payload.instanceId);
|
|
458
|
-
const process = this.input.deps.processes.getById(payload.instanceId) ?? deferredCompletedProcess;
|
|
459
|
-
const lifecycleMessage = buildLifecycleMessage({
|
|
460
|
-
process,
|
|
461
|
-
status: process.lifecycleStatus,
|
|
462
|
-
});
|
|
463
|
-
if (lifecycleMessage)
|
|
464
|
-
await this.sendHtml(thread, lifecycleMessage);
|
|
465
|
-
if (processIsFinished(process))
|
|
466
|
-
await this.closeThread(thread);
|
|
467
|
-
return;
|
|
468
|
-
}
|
|
469
|
-
const process = this.input.deps.processes.getById(payload.instanceId);
|
|
470
|
-
if (process && ["waiting", "error"].includes(process.lifecycleStatus)) {
|
|
471
|
-
await this.sendActionsForProcess(process);
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
async ensureThread(process) {
|
|
475
|
-
const existing = this.store.getByInstanceId(process.id);
|
|
476
|
-
if (existing)
|
|
477
|
-
return existing;
|
|
478
|
-
const topicName = buildTopicTitle({ process, template: this.input.config.topicTitleTemplate });
|
|
479
|
-
const claimedThread = readClaimedLaunchThread(process, this.input.config.delivery.forumChatId);
|
|
480
|
-
if (claimedThread) {
|
|
481
|
-
const thread = { ...claimedThread, topicName };
|
|
482
|
-
try {
|
|
483
|
-
await this.input.client.editForumTopic({
|
|
484
|
-
chatId: thread.chatId,
|
|
485
|
-
messageThreadId: thread.messageThreadId,
|
|
486
|
-
name: topicName,
|
|
487
|
-
});
|
|
488
|
-
}
|
|
489
|
-
catch (error) {
|
|
490
|
-
this.logError(error, "Failed to rename claimed Telegram launch topic");
|
|
491
|
-
}
|
|
492
|
-
this.store.record(process, thread);
|
|
493
|
-
return thread;
|
|
494
|
-
}
|
|
495
|
-
try {
|
|
496
|
-
const topic = await this.input.client.createForumTopic({
|
|
497
|
-
chatId: this.input.config.delivery.forumChatId,
|
|
498
|
-
name: topicName,
|
|
499
|
-
});
|
|
500
|
-
const thread = {
|
|
501
|
-
mode: "forum_topic",
|
|
502
|
-
chatId: this.input.config.delivery.forumChatId,
|
|
503
|
-
messageThreadId: topic.messageThreadId,
|
|
504
|
-
topicName,
|
|
505
|
-
};
|
|
506
|
-
this.store.record(process, thread);
|
|
507
|
-
return thread;
|
|
508
|
-
}
|
|
509
|
-
catch (error) {
|
|
510
|
-
this.logError(error, "Failed to create Telegram process topic");
|
|
511
|
-
return null;
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
async getThread(input) {
|
|
515
|
-
const instanceId = typeof input === "string" ? input : input.id;
|
|
516
|
-
const existing = this.store.getByInstanceId(instanceId);
|
|
517
|
-
if (existing)
|
|
518
|
-
return existing;
|
|
519
|
-
if (!this.threadEligibleInstanceIds.has(instanceId))
|
|
520
|
-
return null;
|
|
521
|
-
const process = typeof input === "string" ? this.input.deps.processes.getById(input) : input;
|
|
522
|
-
if (!process)
|
|
523
|
-
return null;
|
|
524
|
-
const thread = await this.ensureThread(process);
|
|
525
|
-
if (thread)
|
|
526
|
-
await this.sendProcessIntro(thread, process);
|
|
527
|
-
return thread;
|
|
528
|
-
}
|
|
529
|
-
async sendProcessIntro(thread, process) {
|
|
530
|
-
if (this.introSentInstanceIds.has(process.id))
|
|
531
|
-
return;
|
|
532
|
-
await this.sendHtml(thread, buildProcessCreatedMessage({ process, serverBaseUrl: this.input.deps.serverBaseUrl }));
|
|
533
|
-
this.introSentInstanceIds.add(process.id);
|
|
534
|
-
}
|
|
535
|
-
async closeThread(thread) {
|
|
536
|
-
if (this.closedThreadKeys.has(threadKey(thread.chatId, thread.messageThreadId)))
|
|
537
|
-
return;
|
|
538
|
-
try {
|
|
539
|
-
await this.input.client.closeForumTopic({
|
|
540
|
-
chatId: thread.chatId,
|
|
541
|
-
messageThreadId: thread.messageThreadId,
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
catch (error) {
|
|
545
|
-
this.logError(error, "Failed to close Telegram process topic");
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
async syncThreadTitle(thread, process) {
|
|
549
|
-
const topicName = buildTopicTitle({ process, template: this.input.config.topicTitleTemplate });
|
|
550
|
-
if (topicName === thread.topicName)
|
|
551
|
-
return;
|
|
552
|
-
try {
|
|
553
|
-
await this.input.client.editForumTopic({
|
|
554
|
-
chatId: thread.chatId,
|
|
555
|
-
messageThreadId: thread.messageThreadId,
|
|
556
|
-
name: topicName,
|
|
557
|
-
});
|
|
558
|
-
this.store.record(process, { ...thread, topicName });
|
|
559
|
-
}
|
|
560
|
-
catch (error) {
|
|
561
|
-
this.logError(error, "Failed to rename Telegram process topic");
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
async sendActionsForProcess(process, options = {}) {
|
|
565
|
-
const thread = this.store.getByInstanceId(process.id);
|
|
566
|
-
if (!thread)
|
|
567
|
-
return;
|
|
568
|
-
const actions = process.lifecycleStatus === "waiting"
|
|
569
|
-
? this.input.deps.processActions.listVisibleActions(process.id)
|
|
570
|
-
: [];
|
|
571
|
-
const isRecoveryOrHumanWait = ["waiting", "error"].includes(process.lifecycleStatus);
|
|
572
|
-
if (!options.explicit && !isRecoveryOrHumanWait && actions.length === 0)
|
|
573
|
-
return;
|
|
574
|
-
const keyboard = buildActionKeyboard({
|
|
575
|
-
process,
|
|
576
|
-
actions,
|
|
577
|
-
});
|
|
578
|
-
if (!keyboard) {
|
|
579
|
-
if (options.explicit)
|
|
580
|
-
await this.sendHtml(thread, "No actions are available for this process.");
|
|
581
|
-
return;
|
|
582
|
-
}
|
|
583
|
-
const turnInfo = this.lastTurnInfo.get(process.id);
|
|
584
|
-
await this.sendHtml(thread, buildActionsPromptMessage({
|
|
585
|
-
process,
|
|
586
|
-
actions,
|
|
587
|
-
recoveryActions: recoveryActionLabels(process),
|
|
588
|
-
currentTurnDescription: turnInfo ? formatTurnIdLabel(turnInfo.turnId) : null,
|
|
589
|
-
currentTurnPathType: turnInfo?.pathType ?? null,
|
|
590
|
-
}), keyboard);
|
|
591
|
-
}
|
|
592
|
-
async handleForumTopicCreated(update) {
|
|
593
|
-
if (!this.isAllowed(update.from))
|
|
594
|
-
return;
|
|
595
|
-
if (update.chatId !== this.input.config.delivery.forumChatId)
|
|
596
|
-
return;
|
|
597
|
-
if (this.store.getInstanceIdForThread(update.chatId, update.messageThreadId))
|
|
598
|
-
return;
|
|
599
|
-
await this.sendUnmappedTopicHelp(update.chatId, update.messageThreadId);
|
|
600
|
-
}
|
|
601
|
-
async handleForumTopicClosed(update) {
|
|
602
|
-
if (update.chatId !== this.input.config.delivery.forumChatId)
|
|
603
|
-
return;
|
|
604
|
-
const instanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
|
|
605
|
-
if (!instanceId)
|
|
606
|
-
return;
|
|
607
|
-
this.closedThreadKeys.add(threadKey(update.chatId, update.messageThreadId));
|
|
608
|
-
await this.enqueue(instanceId, () => this.abortProcessForClosedTopic(instanceId));
|
|
609
|
-
}
|
|
610
|
-
async abortProcessForClosedTopic(instanceId) {
|
|
611
|
-
const process = this.input.deps.processes.getById(instanceId);
|
|
612
|
-
if (!process || processIsFinished(process))
|
|
613
|
-
return;
|
|
614
|
-
const result = await this.input.deps.commands.abortProcess(instanceId, {
|
|
615
|
-
actor: TELEGRAM_ACTOR,
|
|
616
|
-
});
|
|
617
|
-
if (!result.ok) {
|
|
618
|
-
this.logError(result.message ?? result.code ?? "Abort failed", "Failed to abort closed Telegram topic");
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
async handleText(update) {
|
|
622
|
-
if (!this.isAllowed(update.from))
|
|
623
|
-
return;
|
|
624
|
-
const name = commandName(update.text);
|
|
625
|
-
const instanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
|
|
626
|
-
if (!instanceId) {
|
|
627
|
-
await this.handleUnmappedTopicText(update, name);
|
|
628
|
-
return;
|
|
629
|
-
}
|
|
630
|
-
await this.enqueue(instanceId, () => this.handleProcessText(instanceId, update, name));
|
|
631
|
-
}
|
|
632
|
-
async handleUnmappedTopicText(update, name) {
|
|
633
|
-
const key = launchSessionKey(update);
|
|
634
|
-
if (!key)
|
|
635
|
-
return;
|
|
636
|
-
const inConfiguredForum = update.chatId === this.input.config.delivery.forumChatId;
|
|
637
|
-
if (!inConfiguredForum) {
|
|
638
|
-
if (name === "help") {
|
|
639
|
-
await this.sendPlainToChat(update.chatId, update.messageThreadId, "This bot is operated from the configured process forum chat.");
|
|
640
|
-
}
|
|
641
|
-
return;
|
|
642
|
-
}
|
|
643
|
-
if (name === "cancel") {
|
|
644
|
-
this.launchSessions.delete(key);
|
|
645
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Cancelled.");
|
|
646
|
-
return;
|
|
647
|
-
}
|
|
648
|
-
if (name === "help") {
|
|
649
|
-
await this.sendUnmappedTopicHelp(update.chatId, update.messageThreadId);
|
|
650
|
-
return;
|
|
651
|
-
}
|
|
652
|
-
if (name === "launchers") {
|
|
653
|
-
await this.sendLauncherList(update, key, { includeButtons: false });
|
|
654
|
-
return;
|
|
655
|
-
}
|
|
656
|
-
if (name === "launch") {
|
|
657
|
-
if (update.messageThreadId === undefined) {
|
|
658
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Create a new forum topic first, then send /launch in that topic.");
|
|
659
|
-
return;
|
|
660
|
-
}
|
|
661
|
-
const launcherId = commandArgs(update.text);
|
|
662
|
-
if (launcherId) {
|
|
663
|
-
await this.startLaunchSession(update, key, launcherId);
|
|
664
|
-
return;
|
|
665
|
-
}
|
|
666
|
-
await this.sendLauncherList(update, key, { includeButtons: true });
|
|
667
|
-
return;
|
|
668
|
-
}
|
|
669
|
-
const session = this.launchSessions.get(key);
|
|
670
|
-
if (session) {
|
|
671
|
-
await this.handleLaunchSessionText(key, session, update, name);
|
|
672
|
-
return;
|
|
673
|
-
}
|
|
674
|
-
if (name) {
|
|
675
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Unknown command. Use /help for available commands.");
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
async handleProcessText(instanceId, update, name) {
|
|
679
|
-
const thread = this.store.getByInstanceId(instanceId);
|
|
680
|
-
if (!thread)
|
|
681
|
-
return;
|
|
682
|
-
const key = threadKey(update.chatId, update.messageThreadId);
|
|
683
|
-
if (name === "cancel") {
|
|
684
|
-
if (this.sessions.get(key)?.kind === "question") {
|
|
685
|
-
await this.sendHtml(thread, "The active turn is still waiting for this answer. Answer here, use the Web UI, or stop the turn.");
|
|
686
|
-
return;
|
|
687
|
-
}
|
|
688
|
-
this.sessions.delete(key);
|
|
689
|
-
await this.sendHtml(thread, "Cancelled.");
|
|
690
|
-
return;
|
|
691
|
-
}
|
|
692
|
-
if (name === "actions") {
|
|
693
|
-
const process = this.input.deps.processes.getById(instanceId);
|
|
694
|
-
if (process)
|
|
695
|
-
await this.sendActionsForProcess(process, { explicit: true });
|
|
696
|
-
return;
|
|
697
|
-
}
|
|
698
|
-
if (name === "status") {
|
|
699
|
-
const process = this.input.deps.processes.getById(instanceId);
|
|
700
|
-
if (process) {
|
|
701
|
-
const actions = process.lifecycleStatus === "waiting"
|
|
702
|
-
? this.input.deps.processActions.listVisibleActions(process.id)
|
|
703
|
-
: [];
|
|
704
|
-
const turnInfo = this.lastTurnInfo.get(instanceId);
|
|
705
|
-
await this.sendHtml(thread, buildStatusMessage({
|
|
706
|
-
process,
|
|
707
|
-
actions,
|
|
708
|
-
currentTurnDescription: turnInfo ? formatTurnIdLabel(turnInfo.turnId) : null,
|
|
709
|
-
currentTurnPathType: turnInfo?.pathType ?? null,
|
|
710
|
-
}));
|
|
711
|
-
}
|
|
712
|
-
return;
|
|
713
|
-
}
|
|
714
|
-
if (name === "help") {
|
|
715
|
-
await this.sendHtml(thread, "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.");
|
|
716
|
-
return;
|
|
717
|
-
}
|
|
718
|
-
if (name === "launch") {
|
|
719
|
-
await this.sendHtml(thread, "This topic is already linked to a process. Create a new forum topic and send /launch there to start another process.");
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
const session = this.sessions.get(key);
|
|
723
|
-
if (session) {
|
|
724
|
-
await this.handleSessionText(key, session, update.text, thread, name);
|
|
725
|
-
return;
|
|
726
|
-
}
|
|
727
|
-
if (name) {
|
|
728
|
-
await this.sendHtml(thread, "Unknown command. Use /help for available commands.");
|
|
729
|
-
return;
|
|
730
|
-
}
|
|
731
|
-
const process = this.input.deps.processes.getById(instanceId);
|
|
732
|
-
if (!process)
|
|
733
|
-
return;
|
|
734
|
-
if (!processCanAcceptFreeText(process)) {
|
|
735
|
-
await this.sendHtml(thread, "This process is not accepting free-text input right now. Use /actions for available options.");
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
const result = await this.input.deps.commands.queueInputs(instanceId, [{ source: "external_comment", kind: "instruction", bodyMarkdown: update.text }], {
|
|
739
|
-
dispatchErrorMessage: "Failed to deliver the Telegram input to the worker",
|
|
740
|
-
actor: TELEGRAM_ACTOR,
|
|
741
|
-
});
|
|
742
|
-
await this.sendCommandResult(thread, result, "💬 Sent to process.", "Failed to send input");
|
|
743
|
-
}
|
|
744
|
-
async handleCallback(update) {
|
|
745
|
-
if (!this.isAllowed(update.from)) {
|
|
746
|
-
await this.answerCallback(update.id, "Not allowed", true);
|
|
747
|
-
return;
|
|
748
|
-
}
|
|
749
|
-
const launchCallback = this.readLaunchCallbackCommand(update.data);
|
|
750
|
-
if (launchCallback) {
|
|
751
|
-
const key = launchSessionKey(update);
|
|
752
|
-
if (!key || key !== launchCallback.command.sessionKey) {
|
|
753
|
-
await this.answerCallback(update.id, "This launch button belongs to another session.", true);
|
|
754
|
-
return;
|
|
755
|
-
}
|
|
756
|
-
this.launchCallbacks.delete(launchCallback.token);
|
|
757
|
-
await this.answerCallback(update.id);
|
|
758
|
-
await this.executeLaunchCallbackCommand(key, update, launchCallback.command);
|
|
759
|
-
return;
|
|
760
|
-
}
|
|
761
|
-
if (update.data.startsWith(LAUNCH_CALLBACK_PREFIX)) {
|
|
762
|
-
await this.answerCallback(update.id, "This launch button expired. Send /launch to start again.", true);
|
|
763
|
-
return;
|
|
764
|
-
}
|
|
765
|
-
const command = parseCallbackCommand(update.data);
|
|
766
|
-
if (!command) {
|
|
767
|
-
await this.answerCallback(update.id, "Unknown button. Send /actions to refresh.", true);
|
|
768
|
-
return;
|
|
769
|
-
}
|
|
770
|
-
const resolved = this.resolveCallbackInstance(update, command);
|
|
771
|
-
if (!resolved.ok) {
|
|
772
|
-
await this.answerCallback(update.id, resolved.message, true);
|
|
773
|
-
return;
|
|
774
|
-
}
|
|
775
|
-
await this.answerCallback(update.id);
|
|
776
|
-
await this.enqueue(resolved.instanceId, () => this.executeCallbackCommand(resolved.instanceId, command));
|
|
777
|
-
}
|
|
778
|
-
resolveCallbackInstance(update, command) {
|
|
779
|
-
const threadInstanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
|
|
780
|
-
if (!threadInstanceId) {
|
|
781
|
-
return { ok: false, message: "This button is not in a process topic." };
|
|
782
|
-
}
|
|
783
|
-
if (command.instanceId !== threadInstanceId) {
|
|
784
|
-
return { ok: false, message: "This button belongs to another process topic." };
|
|
785
|
-
}
|
|
786
|
-
return { ok: true, instanceId: threadInstanceId };
|
|
787
|
-
}
|
|
788
|
-
async answerCallback(id, text, showAlert) {
|
|
789
|
-
await this.input.client.answerCallbackQuery({
|
|
790
|
-
callbackQueryId: id,
|
|
791
|
-
...(text ? { text } : {}),
|
|
792
|
-
...(showAlert !== undefined ? { showAlert } : {}),
|
|
793
|
-
});
|
|
794
|
-
}
|
|
795
|
-
getLauncher(launcherId) {
|
|
796
|
-
return (this.input.deps.launcherService
|
|
797
|
-
.listUiLaunchers()
|
|
798
|
-
.find((launcher) => launcher.id === launcherId) ?? null);
|
|
799
|
-
}
|
|
800
|
-
async sendUnmappedTopicHelp(chatId, messageThreadId) {
|
|
801
|
-
await this.sendHtmlToChat(chatId, messageThreadId, [
|
|
802
|
-
"This topic can become a new leitwerk process.",
|
|
803
|
-
"Send /launch to choose a process launcher, then answer the prompts here.",
|
|
804
|
-
"Required fields are asked first; optional fields come after and can be skipped with /skip.",
|
|
805
|
-
"Use /launchers to list launcher ids, or /cancel to discard a pending launch draft.",
|
|
806
|
-
].join("\n"));
|
|
807
|
-
}
|
|
808
|
-
async sendLauncherList(update, sessionKey, options) {
|
|
809
|
-
const launchers = this.input.deps.launcherService.listUiLaunchers();
|
|
810
|
-
if (launchers.length === 0) {
|
|
811
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "No launchers are available.");
|
|
812
|
-
return;
|
|
813
|
-
}
|
|
814
|
-
const lines = ["Available launchers:", ""];
|
|
815
|
-
for (const launcher of launchers) {
|
|
816
|
-
const description = launcher.description.trim();
|
|
817
|
-
lines.push(description
|
|
818
|
-
? `- ${launcher.label} (${launcher.id}) — ${description}`
|
|
819
|
-
: `- ${launcher.label} (${launcher.id})`);
|
|
820
|
-
}
|
|
821
|
-
if (launchers.length > MAX_LAUNCHER_BUTTONS && options.includeButtons) {
|
|
822
|
-
lines.push("", `Showing buttons for the first ${MAX_LAUNCHER_BUTTONS}. Use /launch <launcherId> for others.`);
|
|
823
|
-
}
|
|
824
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeHtml(lines.join("\n")), options.includeButtons ? this.buildLauncherListKeyboard(launchers, sessionKey) : undefined);
|
|
825
|
-
}
|
|
826
|
-
async startLaunchSession(update, sessionKey, launcherId) {
|
|
827
|
-
if (update.chatId !== this.input.config.delivery.forumChatId) {
|
|
828
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Launches are only available from the configured process forum chat.");
|
|
829
|
-
return;
|
|
830
|
-
}
|
|
831
|
-
if (update.messageThreadId === undefined) {
|
|
832
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Create a new forum topic first, then send /launch in that topic.");
|
|
833
|
-
return;
|
|
834
|
-
}
|
|
835
|
-
const launcher = this.getLauncher(launcherId);
|
|
836
|
-
if (!launcher) {
|
|
837
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, `Unknown launcher: ${escapeHtml(launcherId)}`);
|
|
838
|
-
return;
|
|
839
|
-
}
|
|
840
|
-
let defaults;
|
|
841
|
-
try {
|
|
842
|
-
defaults = await this.input.deps.launcherService.resolveUiDefaults(launcher.id);
|
|
843
|
-
}
|
|
844
|
-
catch (error) {
|
|
845
|
-
this.logError(error, "Failed to resolve Telegram launcher defaults");
|
|
846
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Couldn't load launcher defaults. Try /launch again later.");
|
|
847
|
-
return;
|
|
848
|
-
}
|
|
849
|
-
const session = createLaunchSession({
|
|
850
|
-
launcher,
|
|
851
|
-
defaults,
|
|
852
|
-
ttlMs: LAUNCH_SESSION_TTL_MS,
|
|
853
|
-
});
|
|
854
|
-
this.launchSessions.set(sessionKey, session);
|
|
855
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, `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.`);
|
|
856
|
-
await this.sendNextLaunchPrompt(sessionKey, session, update);
|
|
857
|
-
}
|
|
858
|
-
async handleLaunchSessionText(sessionKey, session, update, name) {
|
|
859
|
-
if (session.expiresAt < Date.now()) {
|
|
860
|
-
this.launchSessions.delete(sessionKey);
|
|
861
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "This launch draft expired. Send /launch to start again.");
|
|
862
|
-
return;
|
|
863
|
-
}
|
|
864
|
-
if (name && name !== "skip") {
|
|
865
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Finish this launch prompt, or send /cancel to discard it.");
|
|
866
|
-
return;
|
|
867
|
-
}
|
|
868
|
-
const launcher = this.getLauncher(session.launcherId);
|
|
869
|
-
if (!launcher) {
|
|
870
|
-
this.launchSessions.delete(sessionKey);
|
|
871
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "This launcher is no longer available. Send /launch to choose another.");
|
|
872
|
-
return;
|
|
873
|
-
}
|
|
874
|
-
if (session.modelEdit) {
|
|
875
|
-
await this.handleLaunchModelText(sessionKey, session, update);
|
|
876
|
-
return;
|
|
877
|
-
}
|
|
878
|
-
const optionsById = await this.resolveLaunchOptions(session);
|
|
879
|
-
const step = applyLaunchFieldText(session, launcher, update.text, optionsById);
|
|
880
|
-
if (!step.ok) {
|
|
881
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeHtml(step.prompt));
|
|
882
|
-
return;
|
|
883
|
-
}
|
|
884
|
-
if (step.done) {
|
|
885
|
-
await this.sendLaunchReview(sessionKey, session, launcher, update);
|
|
886
|
-
return;
|
|
887
|
-
}
|
|
888
|
-
await this.sendNextLaunchPrompt(sessionKey, session, update);
|
|
889
|
-
}
|
|
890
|
-
async executeLaunchCallbackCommand(sessionKey, update, command) {
|
|
891
|
-
switch (command.kind) {
|
|
892
|
-
case "select_launcher":
|
|
893
|
-
await this.startLaunchSession(update, sessionKey, command.launcherId);
|
|
894
|
-
return;
|
|
895
|
-
case "cancel_launch":
|
|
896
|
-
this.launchSessions.delete(sessionKey);
|
|
897
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Cancelled.");
|
|
898
|
-
return;
|
|
899
|
-
case "edit_models":
|
|
900
|
-
await this.startLaunchModelEdit(sessionKey, update);
|
|
901
|
-
return;
|
|
902
|
-
case "model_step":
|
|
903
|
-
await this.executeLaunchModelCallbackCommand(sessionKey, update, command);
|
|
904
|
-
return;
|
|
905
|
-
case "finish_model_edit":
|
|
906
|
-
await this.finishLaunchModelEdit(sessionKey, update);
|
|
907
|
-
return;
|
|
908
|
-
case "confirm_launch": {
|
|
909
|
-
const session = await this.getActiveLaunchSession(sessionKey, update);
|
|
910
|
-
if (!session)
|
|
911
|
-
return;
|
|
912
|
-
if (session.modelEdit) {
|
|
913
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Finish model setup before starting this process.");
|
|
914
|
-
await this.sendNextLaunchModelPrompt(sessionKey, session, update);
|
|
915
|
-
return;
|
|
916
|
-
}
|
|
917
|
-
await this.executeLaunchSession(sessionKey, session, update);
|
|
918
|
-
return;
|
|
919
|
-
}
|
|
920
|
-
case "field_value":
|
|
921
|
-
case "skip_field": {
|
|
922
|
-
const context = await this.getLaunchContext(sessionKey, update);
|
|
923
|
-
if (!context)
|
|
924
|
-
return;
|
|
925
|
-
const { session, launcher } = context;
|
|
926
|
-
const field = currentLaunchField(session, launcher);
|
|
927
|
-
if (!field || field.id !== command.fieldId) {
|
|
928
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "That launch button is stale. Continue with the latest prompt or send /cancel.");
|
|
929
|
-
return;
|
|
930
|
-
}
|
|
931
|
-
const optionsById = await this.resolveLaunchOptions(session);
|
|
932
|
-
const step = command.kind === "skip_field"
|
|
933
|
-
? applyLaunchFieldText(session, launcher, "/skip", optionsById)
|
|
934
|
-
: applyLaunchFieldValue(session, launcher, command.value, optionsById);
|
|
935
|
-
if (!step.ok) {
|
|
936
|
-
await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeHtml(step.prompt));
|
|
937
|
-
return;
|
|
938
|
-
}
|
|
939
|
-
if (step.done) {
|
|
940
|
-
await this.sendLaunchReview(sessionKey, session, launcher, update);
|
|
941
|
-
return;
|
|
942
|
-
}
|
|
943
|
-
await this.sendNextLaunchPrompt(sessionKey, session, update);
|
|
944
|
-
return;
|
|
945
|
-
}
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
async getLaunchModelSchema(session) {
|
|
949
|
-
try {
|
|
950
|
-
const schema = await this.input.deps.launcherModelConfigs.getSchema(session.launcherId);
|
|
951
|
-
return this.filterLaunchSchemaAvailableProfiles(schema);
|
|
952
|
-
}
|
|
953
|
-
catch (error) {
|
|
954
|
-
this.logError(error, "Failed to resolve Telegram launcher model schema");
|
|
955
|
-
return null;
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
async getLaunchModelPreview(session) {
|
|
959
|
-
try {
|
|
960
|
-
return await this.input.deps.launcherModelConfigs.preview(session.launcherId, buildLaunchInput(session), { modelConfig: buildLaunchModelConfig(session) });
|
|
961
|
-
}
|
|
962
|
-
catch (error) {
|
|
963
|
-
this.logError(error, "Failed to resolve Telegram launcher model preview");
|
|
964
|
-
return null;
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
async getActiveLaunchSession(sessionKey, target) {
|
|
968
|
-
const session = this.launchSessions.get(sessionKey);
|
|
969
|
-
if (session && session.expiresAt >= Date.now())
|
|
970
|
-
return session;
|
|
971
|
-
if (session)
|
|
972
|
-
this.launchSessions.delete(sessionKey);
|
|
973
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, "This launch draft expired. Send /launch to start again.");
|
|
974
|
-
return null;
|
|
975
|
-
}
|
|
976
|
-
async getLaunchContext(sessionKey, target) {
|
|
977
|
-
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
978
|
-
if (!session)
|
|
979
|
-
return null;
|
|
980
|
-
const launcher = this.getLauncher(session.launcherId);
|
|
981
|
-
if (launcher)
|
|
982
|
-
return { session, launcher };
|
|
983
|
-
this.launchSessions.delete(sessionKey);
|
|
984
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, "This launcher is no longer available. Send /launch to choose another.");
|
|
985
|
-
return null;
|
|
986
|
-
}
|
|
987
|
-
async sendLaunchReviewForSession(sessionKey, session, target) {
|
|
988
|
-
const launcher = this.getLauncher(session.launcherId);
|
|
989
|
-
if (!launcher) {
|
|
990
|
-
this.launchSessions.delete(sessionKey);
|
|
991
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, "This launcher is no longer available. Send /launch to choose another.");
|
|
992
|
-
return;
|
|
993
|
-
}
|
|
994
|
-
await this.sendLaunchReview(sessionKey, session, launcher, target);
|
|
995
|
-
}
|
|
996
|
-
async finishLaunchModelEditAndReview(sessionKey, session, target) {
|
|
997
|
-
finishLaunchModelEdit(session);
|
|
998
|
-
await this.sendLaunchReviewForSession(sessionKey, session, target);
|
|
999
|
-
}
|
|
1000
|
-
async startLaunchModelEdit(sessionKey, target) {
|
|
1001
|
-
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
1002
|
-
if (!session)
|
|
1003
|
-
return;
|
|
1004
|
-
const schema = await this.getLaunchModelSchema(session);
|
|
1005
|
-
if (!hasLaunchModelControls(schema)) {
|
|
1006
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, "This launcher has no editable model setup.");
|
|
1007
|
-
return;
|
|
1008
|
-
}
|
|
1009
|
-
beginLaunchModelEdit(session, schema);
|
|
1010
|
-
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
1011
|
-
}
|
|
1012
|
-
async executeLaunchModelCallbackCommand(sessionKey, target, command) {
|
|
1013
|
-
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
1014
|
-
if (!session)
|
|
1015
|
-
return;
|
|
1016
|
-
const schema = await this.getLaunchModelSchema(session);
|
|
1017
|
-
if (!hasLaunchModelControls(schema)) {
|
|
1018
|
-
await this.finishLaunchModelEditAndReview(sessionKey, session, target);
|
|
1019
|
-
return;
|
|
1020
|
-
}
|
|
1021
|
-
const step = currentLaunchModelStep(session, schema);
|
|
1022
|
-
if (!step || step.key !== command.stepKey) {
|
|
1023
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, "That model button is stale. Continue with the latest prompt or send /cancel.");
|
|
1024
|
-
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
1025
|
-
return;
|
|
1026
|
-
}
|
|
1027
|
-
const action = command.action === "set"
|
|
1028
|
-
? { action: "set", value: command.value }
|
|
1029
|
-
: command.action === "inherit"
|
|
1030
|
-
? { action: "inherit" }
|
|
1031
|
-
: { action: "skip" };
|
|
1032
|
-
await this.continueAfterLaunchModelResult(sessionKey, session, schema, applyLaunchModelStepAction(session, schema, action), target);
|
|
1033
|
-
}
|
|
1034
|
-
async finishLaunchModelEdit(sessionKey, target) {
|
|
1035
|
-
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
1036
|
-
if (session)
|
|
1037
|
-
await this.finishLaunchModelEditAndReview(sessionKey, session, target);
|
|
1038
|
-
}
|
|
1039
|
-
async handleLaunchModelText(sessionKey, session, update) {
|
|
1040
|
-
const schema = await this.getLaunchModelSchema(session);
|
|
1041
|
-
if (!hasLaunchModelControls(schema)) {
|
|
1042
|
-
await this.finishLaunchModelEditAndReview(sessionKey, session, update);
|
|
1043
|
-
return;
|
|
1044
|
-
}
|
|
1045
|
-
await this.continueAfterLaunchModelResult(sessionKey, session, schema, applyLaunchModelStepText(session, schema, update.text), update);
|
|
1046
|
-
}
|
|
1047
|
-
async continueAfterLaunchModelResult(sessionKey, session, schema, result, target) {
|
|
1048
|
-
if (!result.ok) {
|
|
1049
|
-
const step = currentLaunchModelStep(session, schema);
|
|
1050
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, escapeHtml(result.prompt), step ? this.buildLaunchModelReplyMarkup({ sessionKey, step, schema }) : undefined);
|
|
1051
|
-
return;
|
|
1052
|
-
}
|
|
1053
|
-
if (result.done) {
|
|
1054
|
-
await this.sendLaunchReviewForSession(sessionKey, session, target);
|
|
1055
|
-
return;
|
|
1056
|
-
}
|
|
1057
|
-
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
1058
|
-
}
|
|
1059
|
-
resolveLaunchRecentValues(session) {
|
|
1060
|
-
try {
|
|
1061
|
-
return this.input.deps.launcherRecentValues.list(session.launcherId);
|
|
1062
|
-
}
|
|
1063
|
-
catch (error) {
|
|
1064
|
-
this.logError(error, "Failed to resolve Telegram launcher recent values");
|
|
1065
|
-
return {};
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
recordLaunchRecentValuesBestEffort(session) {
|
|
1069
|
-
try {
|
|
1070
|
-
this.input.deps.launcherRecentValues.record(session.launcherId, buildLaunchInput(session));
|
|
1071
|
-
}
|
|
1072
|
-
catch (error) {
|
|
1073
|
-
this.logError(error, "Failed to record Telegram launcher recent values");
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
async resolveLaunchOptions(session) {
|
|
1077
|
-
const launcher = this.getLauncher(session.launcherId);
|
|
1078
|
-
if (!launcher?.launchConfigSchema.fields.some((field) => field.kind === "select")) {
|
|
1079
|
-
return {};
|
|
1080
|
-
}
|
|
1081
|
-
try {
|
|
1082
|
-
return await this.input.deps.launcherService.resolveUiOptions(session.launcherId, buildLaunchInput(session));
|
|
1083
|
-
}
|
|
1084
|
-
catch (error) {
|
|
1085
|
-
this.logError(error, "Failed to resolve Telegram launch field options");
|
|
1086
|
-
return {};
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
async sendNextLaunchModelPrompt(sessionKey, session, target) {
|
|
1090
|
-
const schema = await this.getLaunchModelSchema(session);
|
|
1091
|
-
if (!hasLaunchModelControls(schema)) {
|
|
1092
|
-
await this.finishLaunchModelEditAndReview(sessionKey, session, target);
|
|
1093
|
-
return;
|
|
1094
|
-
}
|
|
1095
|
-
const step = currentLaunchModelStep(session, schema);
|
|
1096
|
-
if (!step) {
|
|
1097
|
-
await this.sendLaunchReviewForSession(sessionKey, session, target);
|
|
1098
|
-
return;
|
|
1099
|
-
}
|
|
1100
|
-
const preview = await this.getLaunchModelPreview(session);
|
|
1101
|
-
const prompt = buildLaunchModelStepPrompt({ step, schema, session, preview });
|
|
1102
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, escapeHtml(prompt), this.buildLaunchModelReplyMarkup({ sessionKey, step, schema }));
|
|
1103
|
-
}
|
|
1104
|
-
async sendNextLaunchPrompt(sessionKey, session, target) {
|
|
1105
|
-
if (session.modelEdit) {
|
|
1106
|
-
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
1107
|
-
return;
|
|
1108
|
-
}
|
|
1109
|
-
const launcher = this.getLauncher(session.launcherId);
|
|
1110
|
-
if (!launcher)
|
|
1111
|
-
return;
|
|
1112
|
-
const field = currentLaunchField(session, launcher);
|
|
1113
|
-
if (!field) {
|
|
1114
|
-
await this.sendLaunchReview(sessionKey, session, launcher, target);
|
|
1115
|
-
return;
|
|
1116
|
-
}
|
|
1117
|
-
const optionsById = await this.resolveLaunchOptions(session);
|
|
1118
|
-
const recentValuesById = this.resolveLaunchRecentValues(session);
|
|
1119
|
-
const fieldOptions = getLaunchFieldOptions(field, optionsById);
|
|
1120
|
-
const fieldRecentValues = recentValuesById[field.id] ?? [];
|
|
1121
|
-
const prompt = buildLaunchFieldPrompt({
|
|
1122
|
-
field,
|
|
1123
|
-
currentValue: session.values[field.id],
|
|
1124
|
-
options: fieldOptions,
|
|
1125
|
-
recentValues: fieldRecentValues,
|
|
1126
|
-
});
|
|
1127
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, escapeHtml(prompt), this.buildLaunchFieldReplyMarkup({
|
|
1128
|
-
sessionKey,
|
|
1129
|
-
fieldId: field.id,
|
|
1130
|
-
fieldKind: field.kind,
|
|
1131
|
-
currentValue: session.values[field.id],
|
|
1132
|
-
options: fieldOptions,
|
|
1133
|
-
recentValues: fieldRecentValues,
|
|
1134
|
-
required: field.required,
|
|
1135
|
-
}));
|
|
1136
|
-
}
|
|
1137
|
-
async sendLaunchReview(sessionKey, session, launcher, target) {
|
|
1138
|
-
const prepared = await this.prepareLaunchSession(session, launcher);
|
|
1139
|
-
if (!prepared.ok) {
|
|
1140
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, escapeHtml(prepared.message));
|
|
1141
|
-
if (prepared.reprompt)
|
|
1142
|
-
await this.sendNextLaunchPrompt(sessionKey, session, target);
|
|
1143
|
-
return;
|
|
1144
|
-
}
|
|
1145
|
-
const schema = await this.getLaunchModelSchema(session);
|
|
1146
|
-
const modelSummary = hasLaunchModelControls(schema)
|
|
1147
|
-
? buildLaunchModelSummary({
|
|
1148
|
-
schema,
|
|
1149
|
-
session,
|
|
1150
|
-
preview: await this.getLaunchModelPreview(session),
|
|
1151
|
-
})
|
|
1152
|
-
: null;
|
|
1153
|
-
await this.sendHtmlToChat(target.chatId, target.messageThreadId, escapeHtml([
|
|
1154
|
-
buildLaunchReview({ launcher, session }),
|
|
1155
|
-
...(modelSummary ? ["", modelSummary] : []),
|
|
1156
|
-
].join("\n")), this.buildLaunchConfirmationKeyboard(sessionKey, Boolean(modelSummary)));
|
|
1157
|
-
}
|
|
1158
|
-
async prepareLaunchSession(session, launcher) {
|
|
1159
|
-
let resolved;
|
|
1160
|
-
try {
|
|
1161
|
-
resolved = await this.input.deps.launcherService.resolveUiLauncher(launcher.id, buildLaunchInput(session));
|
|
1162
|
-
}
|
|
1163
|
-
catch (error) {
|
|
1164
|
-
this.logError(error, "Failed to resolve Telegram launcher input");
|
|
1165
|
-
return {
|
|
1166
|
-
ok: false,
|
|
1167
|
-
message: "Couldn't validate launcher input. Try again or send /cancel.",
|
|
1168
|
-
reprompt: false,
|
|
1169
|
-
};
|
|
1170
|
-
}
|
|
1171
|
-
if (!resolved.ok) {
|
|
1172
|
-
const field = moveLaunchSessionToValidationField(session, launcher, resolved.errors);
|
|
1173
|
-
return {
|
|
1174
|
-
ok: false,
|
|
1175
|
-
message: resolved.errors.map((error) => error.message).join("\n") || "Launcher input is invalid.",
|
|
1176
|
-
reprompt: Boolean(field),
|
|
1177
|
-
};
|
|
1178
|
-
}
|
|
1179
|
-
let prepared;
|
|
1180
|
-
try {
|
|
1181
|
-
prepared = await this.input.deps.launchPlans.prepare(resolved.launcher.launchPlan, {
|
|
1182
|
-
...(session.modelConfigTouched
|
|
1183
|
-
? { modelConfig: buildLaunchModelConfig(session), replaceModelConfig: true }
|
|
1184
|
-
: {}),
|
|
1185
|
-
});
|
|
1186
|
-
}
|
|
1187
|
-
catch (error) {
|
|
1188
|
-
this.logError(error, "Failed to prepare Telegram launch plan");
|
|
1189
|
-
return {
|
|
1190
|
-
ok: false,
|
|
1191
|
-
message: "Couldn't prepare this launch. Try again or send /cancel.",
|
|
1192
|
-
reprompt: false,
|
|
1193
|
-
};
|
|
1194
|
-
}
|
|
1195
|
-
if (!prepared.ok) {
|
|
1196
|
-
return {
|
|
1197
|
-
ok: false,
|
|
1198
|
-
message: prepared.errors.map((error) => error.message).join("\n") ||
|
|
1199
|
-
"Launch configuration is invalid.",
|
|
1200
|
-
reprompt: false,
|
|
1201
|
-
};
|
|
1202
|
-
}
|
|
1203
|
-
seedLaunchModelConfigFromPlan(session, prepared.launchPlan);
|
|
1204
|
-
return { ok: true, launchPlan: prepared.launchPlan };
|
|
1205
|
-
}
|
|
1206
|
-
async executeLaunchSession(sessionKey, session, target) {
|
|
1207
|
-
const { chatId, messageThreadId } = target;
|
|
1208
|
-
const launcher = this.getLauncher(session.launcherId);
|
|
1209
|
-
if (!launcher) {
|
|
1210
|
-
this.launchSessions.delete(sessionKey);
|
|
1211
|
-
await this.sendHtmlToChat(chatId, messageThreadId, "This launcher is no longer available. Send /launch to choose another.");
|
|
1212
|
-
return;
|
|
1213
|
-
}
|
|
1214
|
-
const prepared = await this.prepareLaunchSession(session, launcher);
|
|
1215
|
-
if (!prepared.ok) {
|
|
1216
|
-
await this.sendHtmlToChat(chatId, messageThreadId, escapeHtml(prepared.message));
|
|
1217
|
-
if (prepared.reprompt)
|
|
1218
|
-
await this.sendNextLaunchPrompt(sessionKey, session, target);
|
|
1219
|
-
return;
|
|
1220
|
-
}
|
|
1221
|
-
if (messageThreadId === undefined) {
|
|
1222
|
-
await this.sendHtmlToChat(chatId, messageThreadId, "Create a new forum topic first, then send /launch in that topic.");
|
|
1223
|
-
return;
|
|
1224
|
-
}
|
|
1225
|
-
const launchPlan = attachLaunchThreadMetadata(prepared.launchPlan, {
|
|
1226
|
-
mode: "forum_topic",
|
|
1227
|
-
chatId,
|
|
1228
|
-
messageThreadId,
|
|
1229
|
-
});
|
|
1230
|
-
let result;
|
|
1231
|
-
try {
|
|
1232
|
-
result = await this.input.deps.processLaunches.createProcessFromLaunchPlan(launchPlan, {
|
|
1233
|
-
actor: TELEGRAM_ACTOR,
|
|
1234
|
-
});
|
|
1235
|
-
}
|
|
1236
|
-
catch (error) {
|
|
1237
|
-
this.logError(error, "Failed to create Telegram-launched process");
|
|
1238
|
-
await this.sendHtmlToChat(chatId, messageThreadId, "Couldn't create this process. Try again or send /cancel.");
|
|
1239
|
-
return;
|
|
1240
|
-
}
|
|
1241
|
-
if (result.ok) {
|
|
1242
|
-
this.recordLaunchRecentValuesBestEffort(session);
|
|
1243
|
-
this.launchSessions.delete(sessionKey);
|
|
1244
|
-
await this.sendHtmlToChat(chatId, messageThreadId, `✅ Process launched. Web UI: ${escapeHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${result.process.id}`)}`);
|
|
1245
|
-
return;
|
|
1246
|
-
}
|
|
1247
|
-
const process = "process" in result ? result.process : null;
|
|
1248
|
-
if (process) {
|
|
1249
|
-
this.recordLaunchRecentValuesBestEffort(session);
|
|
1250
|
-
this.launchSessions.delete(sessionKey);
|
|
1251
|
-
await this.sendHtmlToChat(chatId, messageThreadId, `⚠️ Process was created but launch had a follow-up problem. Web UI: ${escapeHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${process.id}`)}`);
|
|
1252
|
-
return;
|
|
1253
|
-
}
|
|
1254
|
-
await this.sendHtmlToChat(chatId, messageThreadId, `⚠️ ${escapeHtml(String(result.body.error ?? "Launch failed"))}`);
|
|
1255
|
-
}
|
|
1256
|
-
createLaunchCallbackCommand(command) {
|
|
1257
|
-
const token = `${Date.now().toString(36)}_${(this.nextLaunchCallbackId++).toString(36)}`;
|
|
1258
|
-
this.launchCallbacks.set(token, {
|
|
1259
|
-
command,
|
|
1260
|
-
expiresAt: Date.now() + LAUNCH_SESSION_TTL_MS,
|
|
1261
|
-
});
|
|
1262
|
-
return `${LAUNCH_CALLBACK_PREFIX}${token}`;
|
|
1263
|
-
}
|
|
1264
|
-
readLaunchCallbackCommand(data) {
|
|
1265
|
-
if (!data.startsWith(LAUNCH_CALLBACK_PREFIX))
|
|
1266
|
-
return null;
|
|
1267
|
-
const token = data.slice(LAUNCH_CALLBACK_PREFIX.length);
|
|
1268
|
-
const stored = this.launchCallbacks.get(token);
|
|
1269
|
-
if (!stored)
|
|
1270
|
-
return null;
|
|
1271
|
-
if (stored.expiresAt < Date.now()) {
|
|
1272
|
-
this.launchCallbacks.delete(token);
|
|
1273
|
-
return null;
|
|
1274
|
-
}
|
|
1275
|
-
return { token, command: stored.command };
|
|
1276
|
-
}
|
|
1277
|
-
buildLauncherListKeyboard(launchers, sessionKey) {
|
|
1278
|
-
const buttons = launchers.slice(0, MAX_LAUNCHER_BUTTONS).map((launcher) => ({
|
|
1279
|
-
text: launcher.label,
|
|
1280
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1281
|
-
kind: "select_launcher",
|
|
1282
|
-
sessionKey,
|
|
1283
|
-
launcherId: launcher.id,
|
|
1284
|
-
}),
|
|
1285
|
-
}));
|
|
1286
|
-
return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
|
|
1287
|
-
}
|
|
1288
|
-
buildLaunchConfirmationKeyboard(sessionKey, includeModelControls) {
|
|
1289
|
-
return {
|
|
1290
|
-
inlineKeyboard: [
|
|
1291
|
-
[
|
|
1292
|
-
{
|
|
1293
|
-
text: "Start process",
|
|
1294
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1295
|
-
kind: "confirm_launch",
|
|
1296
|
-
sessionKey,
|
|
1297
|
-
}),
|
|
1298
|
-
},
|
|
1299
|
-
{
|
|
1300
|
-
text: "Cancel",
|
|
1301
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1302
|
-
kind: "cancel_launch",
|
|
1303
|
-
sessionKey,
|
|
1304
|
-
}),
|
|
1305
|
-
},
|
|
1306
|
-
],
|
|
1307
|
-
...(includeModelControls
|
|
1308
|
-
? [
|
|
1309
|
-
[
|
|
1310
|
-
{
|
|
1311
|
-
text: "Change models",
|
|
1312
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1313
|
-
kind: "edit_models",
|
|
1314
|
-
sessionKey,
|
|
1315
|
-
}),
|
|
1316
|
-
},
|
|
1317
|
-
],
|
|
1318
|
-
]
|
|
1319
|
-
: []),
|
|
1320
|
-
],
|
|
1321
|
-
};
|
|
1322
|
-
}
|
|
1323
|
-
buildLaunchModelReplyMarkup(input) {
|
|
1324
|
-
const buttons = [];
|
|
1325
|
-
for (const profile of input.schema.availableProfiles.slice(0, MAX_MODEL_PROFILE_BUTTONS)) {
|
|
1326
|
-
buttons.push({
|
|
1327
|
-
text: profile.id,
|
|
1328
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1329
|
-
kind: "model_step",
|
|
1330
|
-
sessionKey: input.sessionKey,
|
|
1331
|
-
stepKey: input.step.key,
|
|
1332
|
-
action: "set",
|
|
1333
|
-
value: profile.id,
|
|
1334
|
-
}),
|
|
1335
|
-
});
|
|
1336
|
-
}
|
|
1337
|
-
buttons.push({
|
|
1338
|
-
text: "Inherit",
|
|
1339
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1340
|
-
kind: "model_step",
|
|
1341
|
-
sessionKey: input.sessionKey,
|
|
1342
|
-
stepKey: input.step.key,
|
|
1343
|
-
action: "inherit",
|
|
1344
|
-
}),
|
|
1345
|
-
}, {
|
|
1346
|
-
text: "Keep current",
|
|
1347
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1348
|
-
kind: "model_step",
|
|
1349
|
-
sessionKey: input.sessionKey,
|
|
1350
|
-
stepKey: input.step.key,
|
|
1351
|
-
action: "skip",
|
|
1352
|
-
}),
|
|
1353
|
-
}, {
|
|
1354
|
-
text: "Done",
|
|
1355
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1356
|
-
kind: "finish_model_edit",
|
|
1357
|
-
sessionKey: input.sessionKey,
|
|
1358
|
-
}),
|
|
1359
|
-
});
|
|
1360
|
-
return { inlineKeyboard: rows(buttons, 1) };
|
|
1361
|
-
}
|
|
1362
|
-
buildLaunchFieldReplyMarkup(input) {
|
|
1363
|
-
const buttons = [];
|
|
1364
|
-
if (input.fieldKind === "boolean") {
|
|
1365
|
-
buttons.push({
|
|
1366
|
-
text: "Yes",
|
|
1367
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1368
|
-
kind: "field_value",
|
|
1369
|
-
sessionKey: input.sessionKey,
|
|
1370
|
-
fieldId: input.fieldId,
|
|
1371
|
-
value: true,
|
|
1372
|
-
}),
|
|
1373
|
-
}, {
|
|
1374
|
-
text: "No",
|
|
1375
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1376
|
-
kind: "field_value",
|
|
1377
|
-
sessionKey: input.sessionKey,
|
|
1378
|
-
fieldId: input.fieldId,
|
|
1379
|
-
value: false,
|
|
1380
|
-
}),
|
|
1381
|
-
});
|
|
1382
|
-
}
|
|
1383
|
-
else if (input.fieldKind === "select") {
|
|
1384
|
-
for (const option of input.options.slice(0, MAX_FIELD_OPTION_BUTTONS)) {
|
|
1385
|
-
buttons.push({
|
|
1386
|
-
text: option.label,
|
|
1387
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1388
|
-
kind: "field_value",
|
|
1389
|
-
sessionKey: input.sessionKey,
|
|
1390
|
-
fieldId: input.fieldId,
|
|
1391
|
-
value: option.value,
|
|
1392
|
-
}),
|
|
1393
|
-
});
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
else {
|
|
1397
|
-
for (const value of input.recentValues.slice(0, MAX_FIELD_OPTION_BUTTONS)) {
|
|
1398
|
-
buttons.push({
|
|
1399
|
-
text: this.formatRecentValueButtonText(value),
|
|
1400
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1401
|
-
kind: "field_value",
|
|
1402
|
-
sessionKey: input.sessionKey,
|
|
1403
|
-
fieldId: input.fieldId,
|
|
1404
|
-
value,
|
|
1405
|
-
}),
|
|
1406
|
-
});
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
const hasCurrentValue = typeof input.currentValue === "boolean" ||
|
|
1410
|
-
(typeof input.currentValue === "number" && Number.isFinite(input.currentValue)) ||
|
|
1411
|
-
(typeof input.currentValue === "string" && input.currentValue.trim() !== "");
|
|
1412
|
-
if (input.fieldKind !== "boolean" &&
|
|
1413
|
-
input.fieldKind !== "select" &&
|
|
1414
|
-
input.required &&
|
|
1415
|
-
!hasCurrentValue &&
|
|
1416
|
-
buttons.length === 0) {
|
|
1417
|
-
return {
|
|
1418
|
-
forceReply: true,
|
|
1419
|
-
selective: true,
|
|
1420
|
-
inputFieldPlaceholder: "Reply with this field value",
|
|
1421
|
-
};
|
|
1422
|
-
}
|
|
1423
|
-
if (!input.required || hasCurrentValue) {
|
|
1424
|
-
buttons.push({
|
|
1425
|
-
text: hasCurrentValue ? "Use default" : "Skip",
|
|
1426
|
-
callbackData: this.createLaunchCallbackCommand({
|
|
1427
|
-
kind: "skip_field",
|
|
1428
|
-
sessionKey: input.sessionKey,
|
|
1429
|
-
fieldId: input.fieldId,
|
|
1430
|
-
}),
|
|
1431
|
-
});
|
|
1432
|
-
}
|
|
1433
|
-
if (buttons.length > 0)
|
|
1434
|
-
return { inlineKeyboard: rows(buttons, 1) };
|
|
1435
|
-
return {
|
|
1436
|
-
forceReply: true,
|
|
1437
|
-
selective: true,
|
|
1438
|
-
inputFieldPlaceholder: "Reply with this field value",
|
|
1439
|
-
};
|
|
1440
|
-
}
|
|
1441
|
-
formatRecentValueButtonText(value) {
|
|
1442
|
-
const normalized = value.replace(/\s+/g, " ").trim();
|
|
1443
|
-
return normalized.length > 56 ? `${normalized.slice(0, 55)}…` : normalized;
|
|
1444
|
-
}
|
|
1445
|
-
buildActionFormFieldReplyMarkup(session, field) {
|
|
1446
|
-
if (!canSkipActionFormField(field)) {
|
|
1447
|
-
return undefined;
|
|
1448
|
-
}
|
|
1449
|
-
return {
|
|
1450
|
-
inlineKeyboard: [
|
|
1451
|
-
[
|
|
1452
|
-
{
|
|
1453
|
-
text: "Skip",
|
|
1454
|
-
callbackData: `fs:${session.instanceId}:${session.sessionId}:${field.id}`,
|
|
1455
|
-
},
|
|
1456
|
-
],
|
|
1457
|
-
],
|
|
1458
|
-
};
|
|
1459
|
-
}
|
|
1460
|
-
async sendActionFormFieldPrompt(thread, session, field, prompt = buildFieldPrompt(field)) {
|
|
1461
|
-
await this.sendHtml(thread, escapeHtml(prompt), this.buildActionFormFieldReplyMarkup(session, field));
|
|
1462
|
-
}
|
|
1463
|
-
async executeCallbackCommand(instanceId, command) {
|
|
1464
|
-
const process = this.input.deps.processes.getById(instanceId);
|
|
1465
|
-
if (!process)
|
|
1466
|
-
return;
|
|
1467
|
-
const thread = this.store.getByInstanceId(process.id);
|
|
1468
|
-
if (!thread)
|
|
1469
|
-
return;
|
|
1470
|
-
const key = threadKey(thread.chatId, thread.messageThreadId);
|
|
1471
|
-
switch (command.kind) {
|
|
1472
|
-
case "process_action": {
|
|
1473
|
-
if (process.lifecycleStatus !== "waiting") {
|
|
1474
|
-
await this.sendHtml(thread, "That action is no longer available. Use /actions to refresh.");
|
|
1475
|
-
return;
|
|
1476
|
-
}
|
|
1477
|
-
const action = this.input.deps.processActions
|
|
1478
|
-
.listVisibleActions(process.id)
|
|
1479
|
-
.find((candidate) => candidate.id === command.actionId);
|
|
1480
|
-
if (!action) {
|
|
1481
|
-
await this.sendHtml(thread, "That action is no longer available. Use /actions to refresh.");
|
|
1482
|
-
return;
|
|
1483
|
-
}
|
|
1484
|
-
if (action.form?.fields.length) {
|
|
1485
|
-
const session = buildActionFormSession({
|
|
1486
|
-
instanceId: process.id,
|
|
1487
|
-
actionId: action.id,
|
|
1488
|
-
actionLabel: action.label,
|
|
1489
|
-
actionPreview: readActionPreview(action),
|
|
1490
|
-
sessionId: createActionFormSessionId(),
|
|
1491
|
-
form: action.form,
|
|
1492
|
-
});
|
|
1493
|
-
this.sessions.set(key, session);
|
|
1494
|
-
const field = currentField(session);
|
|
1495
|
-
if (field)
|
|
1496
|
-
await this.sendActionFormFieldPrompt(thread, session, field);
|
|
1497
|
-
return;
|
|
1498
|
-
}
|
|
1499
|
-
await this.maybeSelectActionModel({
|
|
1500
|
-
instanceId: process.id,
|
|
1501
|
-
action,
|
|
1502
|
-
formValues: {},
|
|
1503
|
-
sessionKey: key,
|
|
1504
|
-
thread,
|
|
1505
|
-
});
|
|
1506
|
-
return;
|
|
1507
|
-
}
|
|
1508
|
-
case "action_form_skip": {
|
|
1509
|
-
await this.skipCurrentActionFormField(key, command.sessionId, command.fieldId, thread);
|
|
1510
|
-
return;
|
|
1511
|
-
}
|
|
1512
|
-
case "action_model_select": {
|
|
1513
|
-
const modelSession = this.sessions.get(key);
|
|
1514
|
-
const modelProfile = resolveModelProfileFromSession(modelSession, command.profileIndex);
|
|
1515
|
-
if (!modelProfile) {
|
|
1516
|
-
await this.sendHtml(thread, "That model option is no longer available. Use /actions to start again.");
|
|
1517
|
-
return;
|
|
1518
|
-
}
|
|
1519
|
-
if (modelSession?.kind === "recovery_model") {
|
|
1520
|
-
await this.handleRecoveryModelSelect(key, command.sessionId, modelProfile.id, modelSession, thread);
|
|
1521
|
-
return;
|
|
1522
|
-
}
|
|
1523
|
-
await this.handleActionModelSelect(key, command.sessionId, modelProfile.id, thread);
|
|
1524
|
-
return;
|
|
1525
|
-
}
|
|
1526
|
-
case "action_model_skip": {
|
|
1527
|
-
const modelSession = this.sessions.get(key);
|
|
1528
|
-
if (modelSession?.kind === "recovery_model") {
|
|
1529
|
-
await this.handleRecoveryModelSkip(key, command.sessionId, modelSession, thread);
|
|
1530
|
-
return;
|
|
1531
|
-
}
|
|
1532
|
-
await this.handleActionModelSkip(key, command.sessionId, thread);
|
|
1533
|
-
return;
|
|
1534
|
-
}
|
|
1535
|
-
case "retry": {
|
|
1536
|
-
await this.maybeSelectRecoveryModel({
|
|
1537
|
-
instanceId: process.id,
|
|
1538
|
-
recoveryKind: "retry",
|
|
1539
|
-
sessionKey: key,
|
|
1540
|
-
thread,
|
|
1541
|
-
execute: (opts) => this.input.deps.commands
|
|
1542
|
-
.retryProcess(process.id, {
|
|
1543
|
-
...(opts?.nextTurnModelProfileId !== undefined ? opts : {}),
|
|
1544
|
-
actor: TELEGRAM_ACTOR,
|
|
1545
|
-
})
|
|
1546
|
-
.then((result) => {
|
|
1547
|
-
this.sendCommandResult(thread, result, "Retry started.", "Retry failed");
|
|
1548
|
-
}),
|
|
1549
|
-
});
|
|
1550
|
-
return;
|
|
1551
|
-
}
|
|
1552
|
-
case "continue": {
|
|
1553
|
-
const turnRecordId = continuableFailedTurnRecordId(process);
|
|
1554
|
-
if (!turnRecordId) {
|
|
1555
|
-
await this.sendHtml(thread, "No failed turn is available to continue.");
|
|
1556
|
-
return;
|
|
1557
|
-
}
|
|
1558
|
-
await this.maybeSelectRecoveryModel({
|
|
1559
|
-
instanceId: process.id,
|
|
1560
|
-
recoveryKind: "continue",
|
|
1561
|
-
turnRecordId,
|
|
1562
|
-
sessionKey: key,
|
|
1563
|
-
thread,
|
|
1564
|
-
execute: (opts) => {
|
|
1565
|
-
const session = buildContinueSession({
|
|
1566
|
-
instanceId: process.id,
|
|
1567
|
-
turnRecordId,
|
|
1568
|
-
nextTurnModelProfileId: opts?.nextTurnModelProfileId,
|
|
1569
|
-
});
|
|
1570
|
-
this.sessions.set(key, session);
|
|
1571
|
-
this.sendCurrentSessionPrompt(thread, session);
|
|
1572
|
-
},
|
|
1573
|
-
});
|
|
1574
|
-
return;
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
async sendCurrentSessionPrompt(thread, session) {
|
|
1579
|
-
if (session.kind === "continue") {
|
|
1580
|
-
await this.sendHtml(thread, CONTINUE_PROMPT);
|
|
1581
|
-
return true;
|
|
1582
|
-
}
|
|
1583
|
-
if (session.kind === "question") {
|
|
1584
|
-
await this.sendHtml(thread, escapeHtml(buildQuestionPrompt(session)));
|
|
1585
|
-
return true;
|
|
1586
|
-
}
|
|
1587
|
-
if (session.kind === "action_model") {
|
|
1588
|
-
await this.sendActionModelPrompt(thread, session);
|
|
1589
|
-
return true;
|
|
1590
|
-
}
|
|
1591
|
-
if (session.kind === "recovery_model") {
|
|
1592
|
-
await this.sendRecoveryModelPrompt(thread, session);
|
|
1593
|
-
return true;
|
|
1594
|
-
}
|
|
1595
|
-
const field = currentField(session);
|
|
1596
|
-
if (!field)
|
|
1597
|
-
return false;
|
|
1598
|
-
if (session.kind === "action_form") {
|
|
1599
|
-
await this.sendActionFormFieldPrompt(thread, session, field);
|
|
1600
|
-
return true;
|
|
1601
|
-
}
|
|
1602
|
-
await this.sendHtml(thread, escapeHtml(buildFieldPrompt(field)));
|
|
1603
|
-
return true;
|
|
1604
|
-
}
|
|
1605
|
-
async maybeSelectActionModel(input) {
|
|
1606
|
-
const fallback = () => this.executeProcessAction(input.instanceId, { id: input.action.id, label: input.action.label, preview: input.action.preview }, input.formValues, input.thread);
|
|
1607
|
-
try {
|
|
1608
|
-
const profiles = this.listSelectableProfiles(input.instanceId);
|
|
1609
|
-
if (!profiles.length)
|
|
1610
|
-
return fallback();
|
|
1611
|
-
const result = await this.processModelSelection?.preview(input.instanceId, input.action.id, input.formValues);
|
|
1612
|
-
if (!result)
|
|
1613
|
-
return fallback();
|
|
1614
|
-
if (result.kind === "operational_failure") {
|
|
1615
|
-
this.input.logger?.warn?.({ code: result.code }, "Action model preview unavailable; falling back to direct execution");
|
|
1616
|
-
return fallback();
|
|
1617
|
-
}
|
|
1618
|
-
if (result.kind !== "llm_turn")
|
|
1619
|
-
return fallback();
|
|
1620
|
-
const sessionId = createActionFormSessionId();
|
|
1621
|
-
const session = buildActionModelSession({
|
|
1622
|
-
instanceId: input.instanceId,
|
|
1623
|
-
actionId: input.action.id,
|
|
1624
|
-
actionLabel: input.action.label,
|
|
1625
|
-
actionPreview: input.action.preview,
|
|
1626
|
-
sessionId,
|
|
1627
|
-
formValues: input.formValues,
|
|
1628
|
-
preview: result,
|
|
1629
|
-
profiles,
|
|
1630
|
-
});
|
|
1631
|
-
this.sessions.set(input.sessionKey, session);
|
|
1632
|
-
await this.sendActionModelPrompt(input.thread, session);
|
|
1633
|
-
}
|
|
1634
|
-
catch (error) {
|
|
1635
|
-
this.logError(error, "Action model preview failed; falling back to direct execution");
|
|
1636
|
-
return fallback();
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
async resolveActionModelSession(sessionKey, sessionId, thread) {
|
|
1640
|
-
const session = this.sessions.get(sessionKey);
|
|
1641
|
-
if (!session || session.kind !== "action_model" || session.sessionId !== sessionId) {
|
|
1642
|
-
await this.sendHtml(thread, "That model selection expired. Use /actions to start again.");
|
|
1643
|
-
return null;
|
|
1644
|
-
}
|
|
1645
|
-
if (session.expiresAt < Date.now()) {
|
|
1646
|
-
this.sessions.delete(sessionKey);
|
|
1647
|
-
await this.sendHtml(thread, "That model selection expired. Use /actions to start again.");
|
|
1648
|
-
return null;
|
|
1649
|
-
}
|
|
1650
|
-
this.sessions.delete(sessionKey);
|
|
1651
|
-
return session;
|
|
1652
|
-
}
|
|
1653
|
-
executeActionModelSession(session, thread, opts) {
|
|
1654
|
-
return this.executeProcessAction(session.instanceId, { id: session.actionId, label: session.actionLabel, preview: session.actionPreview }, session.formValues, thread, opts);
|
|
1655
|
-
}
|
|
1656
|
-
async sendActionModelSwitchWarning(session, effectiveModelProfileId, thread) {
|
|
1657
|
-
if (!effectiveModelProfileId)
|
|
1658
|
-
return;
|
|
1659
|
-
const warning = buildActionModelSwitchWarning({ session, effectiveModelProfileId });
|
|
1660
|
-
if (warning)
|
|
1661
|
-
await this.sendHtml(thread, escapeHtml(warning));
|
|
1662
|
-
}
|
|
1663
|
-
async handleActionModelSelect(sessionKey, sessionId, modelProfileId, thread) {
|
|
1664
|
-
const session = await this.resolveActionModelSession(sessionKey, sessionId, thread);
|
|
1665
|
-
if (!session)
|
|
1666
|
-
return;
|
|
1667
|
-
await this.sendActionModelSwitchWarning(session, modelProfileId, thread);
|
|
1668
|
-
await this.executeActionModelSession(session, thread, {
|
|
1669
|
-
nextTurnModelProfileId: modelProfileId,
|
|
1670
|
-
});
|
|
1671
|
-
}
|
|
1672
|
-
async handleActionModelSkip(sessionKey, sessionId, thread) {
|
|
1673
|
-
const session = await this.resolveActionModelSession(sessionKey, sessionId, thread);
|
|
1674
|
-
if (!session)
|
|
1675
|
-
return;
|
|
1676
|
-
const resolved = session.preview.resolvedModel;
|
|
1677
|
-
await this.sendActionModelSwitchWarning(session, resolved?.status === "resolved" ? resolved.modelProfileId : null, thread);
|
|
1678
|
-
await this.executeActionModelSession(session, thread);
|
|
1679
|
-
}
|
|
1680
|
-
async sendActionModelPrompt(thread, session) {
|
|
1681
|
-
await this.sendHtml(thread, escapeHtml(buildActionModelPrompt({ session })), this.buildActionModelReplyMarkup(session));
|
|
1682
|
-
}
|
|
1683
|
-
buildActionModelReplyMarkup(session) {
|
|
1684
|
-
const buttons = [];
|
|
1685
|
-
let index = 0;
|
|
1686
|
-
for (const profile of session.profiles.slice(0, 20)) {
|
|
1687
|
-
index += 1;
|
|
1688
|
-
const switchesModel = buildActionModelSwitchWarning({
|
|
1689
|
-
session,
|
|
1690
|
-
effectiveModelProfileId: profile.id,
|
|
1691
|
-
});
|
|
1692
|
-
buttons.push({
|
|
1693
|
-
text: `${switchesModel ? "⚠ " : ""}${profile.id}`,
|
|
1694
|
-
callbackData: `ams:${session.instanceId}:${session.sessionId}:${index}`,
|
|
1695
|
-
});
|
|
1696
|
-
}
|
|
1697
|
-
const resolved = session.preview.resolvedModel;
|
|
1698
|
-
const resolvedProfileId = resolved?.status === "resolved" ? resolved.modelProfileId : null;
|
|
1699
|
-
const keepingCurrentSwitchesModel = resolvedProfileId
|
|
1700
|
-
? buildActionModelSwitchWarning({ session, effectiveModelProfileId: resolvedProfileId })
|
|
1701
|
-
: null;
|
|
1702
|
-
buttons.push({
|
|
1703
|
-
text: `${keepingCurrentSwitchesModel ? "⚠ " : ""}Keep current`,
|
|
1704
|
-
callbackData: `amk:${session.instanceId}:${session.sessionId}`,
|
|
1705
|
-
});
|
|
1706
|
-
return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
|
|
1707
|
-
}
|
|
1708
|
-
async applyActionFormStep(key, session, step, thread) {
|
|
1709
|
-
if (!step.ok || !step.done) {
|
|
1710
|
-
const field = currentField(session);
|
|
1711
|
-
if (field) {
|
|
1712
|
-
await this.sendActionFormFieldPrompt(thread, session, field, step.prompt);
|
|
1713
|
-
}
|
|
1714
|
-
else {
|
|
1715
|
-
await this.sendHtml(thread, escapeHtml(step.prompt));
|
|
1716
|
-
}
|
|
1717
|
-
return;
|
|
1718
|
-
}
|
|
1719
|
-
this.sessions.delete(key);
|
|
1720
|
-
await this.maybeSelectActionModel({
|
|
1721
|
-
instanceId: session.instanceId,
|
|
1722
|
-
action: {
|
|
1723
|
-
id: session.actionId,
|
|
1724
|
-
label: session.actionLabel,
|
|
1725
|
-
form: session.form,
|
|
1726
|
-
preview: session.actionPreview,
|
|
1727
|
-
},
|
|
1728
|
-
formValues: step.values,
|
|
1729
|
-
sessionKey: key,
|
|
1730
|
-
thread,
|
|
1731
|
-
});
|
|
1732
|
-
}
|
|
1733
|
-
async applyActionFormText(key, session, text, thread) {
|
|
1734
|
-
await this.applyActionFormStep(key, session, applyFormText(session, text), thread);
|
|
1735
|
-
}
|
|
1736
|
-
async applyActionFormSkip(key, session, thread) {
|
|
1737
|
-
await this.applyActionFormStep(key, session, applyFormSkip(session), thread);
|
|
1738
|
-
}
|
|
1739
|
-
async skipCurrentActionFormField(key, sessionId, fieldId, thread) {
|
|
1740
|
-
const session = this.sessions.get(key);
|
|
1741
|
-
if (!session || session.kind !== "action_form") {
|
|
1742
|
-
await this.sendHtml(thread, "This form prompt expired. Use /actions to start again.");
|
|
1743
|
-
return;
|
|
1744
|
-
}
|
|
1745
|
-
if (session.expiresAt < Date.now()) {
|
|
1746
|
-
this.sessions.delete(key);
|
|
1747
|
-
await this.sendHtml(thread, "This form prompt expired. Use /actions to start again.");
|
|
1748
|
-
return;
|
|
1749
|
-
}
|
|
1750
|
-
const field = currentField(session);
|
|
1751
|
-
if (session.sessionId !== sessionId || !field || field.id !== fieldId) {
|
|
1752
|
-
await this.sendHtml(thread, "That skip button is stale. Continue with the latest prompt or send /cancel.");
|
|
1753
|
-
return;
|
|
1754
|
-
}
|
|
1755
|
-
if (!canSkipActionFormField(field)) {
|
|
1756
|
-
await this.sendActionFormFieldPrompt(thread, session, field, `${field.label} is required and cannot be skipped.\n${buildFieldPrompt(field)}`);
|
|
1757
|
-
return;
|
|
1758
|
-
}
|
|
1759
|
-
await this.applyActionFormSkip(key, session, thread);
|
|
1760
|
-
}
|
|
1761
|
-
async handleSessionText(key, session, text, thread, name) {
|
|
1762
|
-
if (session.expiresAt < Date.now()) {
|
|
1763
|
-
this.sessions.delete(key);
|
|
1764
|
-
await this.sendHtml(thread, "This prompt expired. Use /actions to start again.");
|
|
1765
|
-
return;
|
|
1766
|
-
}
|
|
1767
|
-
if (session.kind === "continue") {
|
|
1768
|
-
const prompt = name === "skip" ? null : text;
|
|
1769
|
-
this.sessions.delete(key);
|
|
1770
|
-
const result = await this.input.deps.commands.continueFailedTurn(session.instanceId, session.turnRecordId, {
|
|
1771
|
-
prompt,
|
|
1772
|
-
...(session.nextTurnModelProfileId !== undefined &&
|
|
1773
|
-
session.nextTurnModelProfileId !== null
|
|
1774
|
-
? { nextTurnModelProfileId: session.nextTurnModelProfileId }
|
|
1775
|
-
: {}),
|
|
1776
|
-
actor: TELEGRAM_ACTOR,
|
|
1777
|
-
});
|
|
1778
|
-
await this.sendCommandResult(thread, result, "Continue started.", "Continue failed");
|
|
1779
|
-
return;
|
|
1780
|
-
}
|
|
1781
|
-
if (session.kind === "question") {
|
|
1782
|
-
if (name) {
|
|
1783
|
-
await this.sendHtml(thread, escapeHtml(buildQuestionPrompt(session)));
|
|
1784
|
-
return;
|
|
1785
|
-
}
|
|
1786
|
-
const step = applyQuestionText(session, text);
|
|
1787
|
-
if (!step.done) {
|
|
1788
|
-
await this.sendHtml(thread, escapeHtml(step.prompt ?? buildQuestionPrompt(session)));
|
|
1789
|
-
return;
|
|
1790
|
-
}
|
|
1791
|
-
const service = this.input.deps.processQuestions;
|
|
1792
|
-
const result = service
|
|
1793
|
-
? await service.submitAnswers(session.instanceId, session.request.id, step.draft, TELEGRAM_ACTOR)
|
|
1794
|
-
: { ok: false, message: "Answers cannot be submitted through Telegram." };
|
|
1795
|
-
this.sessions.delete(key);
|
|
1796
|
-
await this.sendHtml(thread, result.ok ? "✅ Answers sent. The active turn is continuing." : escapeHtml(result.message));
|
|
1797
|
-
return;
|
|
1798
|
-
}
|
|
1799
|
-
if (session.kind === "action_model") {
|
|
1800
|
-
if (name === "skip") {
|
|
1801
|
-
await this.handleActionModelSkip(key, session.sessionId, thread);
|
|
1802
|
-
return;
|
|
1803
|
-
}
|
|
1804
|
-
if (name === "cancel") {
|
|
1805
|
-
this.sessions.delete(key);
|
|
1806
|
-
await this.sendHtml(thread, "Cancelled.");
|
|
1807
|
-
return;
|
|
1808
|
-
}
|
|
1809
|
-
await this.handleActionModelText(key, session, text, thread);
|
|
1810
|
-
return;
|
|
1811
|
-
}
|
|
1812
|
-
if (session.kind === "recovery_model") {
|
|
1813
|
-
if (name === "skip") {
|
|
1814
|
-
await this.handleRecoveryModelSkip(key, session.sessionId, session, thread);
|
|
1815
|
-
return;
|
|
1816
|
-
}
|
|
1817
|
-
if (name === "cancel") {
|
|
1818
|
-
this.sessions.delete(key);
|
|
1819
|
-
await this.sendHtml(thread, "Cancelled.");
|
|
1820
|
-
return;
|
|
1821
|
-
}
|
|
1822
|
-
await this.handleRecoveryModelText(key, session, text, thread);
|
|
1823
|
-
return;
|
|
1824
|
-
}
|
|
1825
|
-
if (name === "skip") {
|
|
1826
|
-
const field = currentField(session);
|
|
1827
|
-
if (!canSkipActionFormField(field)) {
|
|
1828
|
-
if (field) {
|
|
1829
|
-
await this.sendActionFormFieldPrompt(thread, session, field, `${field.label} is required and cannot be skipped.\n${buildFieldPrompt(field)}`);
|
|
1830
|
-
}
|
|
1831
|
-
return;
|
|
1832
|
-
}
|
|
1833
|
-
await this.applyActionFormSkip(key, session, thread);
|
|
1834
|
-
return;
|
|
1835
|
-
}
|
|
1836
|
-
await this.applyActionFormText(key, session, text, thread);
|
|
1837
|
-
}
|
|
1838
|
-
async handleActionModelText(sessionKey, session, text, thread) {
|
|
1839
|
-
const profile = resolveProfileByTextOrIndex(text.trim(), session.profiles);
|
|
1840
|
-
if (profile) {
|
|
1841
|
-
this.sessions.delete(sessionKey);
|
|
1842
|
-
await this.sendActionModelSwitchWarning(session, profile.id, thread);
|
|
1843
|
-
return this.executeActionModelSession(session, thread, {
|
|
1844
|
-
nextTurnModelProfileId: profile.id,
|
|
1845
|
-
});
|
|
1846
|
-
}
|
|
1847
|
-
await this.sendHtml(thread, escapeHtml(`Model must match an available profile.\n${buildActionModelPrompt({ session })}`), this.buildActionModelReplyMarkup(session));
|
|
1848
|
-
}
|
|
1849
|
-
async maybeSelectRecoveryModel(input) {
|
|
1850
|
-
try {
|
|
1851
|
-
const profiles = this.listSelectableProfiles(input.instanceId);
|
|
1852
|
-
if (!profiles.length)
|
|
1853
|
-
return input.execute();
|
|
1854
|
-
const sessionId = createActionFormSessionId();
|
|
1855
|
-
const session = buildRecoveryModelSession({
|
|
1856
|
-
instanceId: input.instanceId,
|
|
1857
|
-
recoveryKind: input.recoveryKind,
|
|
1858
|
-
turnRecordId: input.turnRecordId,
|
|
1859
|
-
sessionId,
|
|
1860
|
-
profiles,
|
|
1861
|
-
});
|
|
1862
|
-
this.sessions.set(input.sessionKey, session);
|
|
1863
|
-
await this.sendRecoveryModelPrompt(input.thread, session);
|
|
1864
|
-
}
|
|
1865
|
-
catch (error) {
|
|
1866
|
-
this.logError(error, "Recovery model selection failed; falling back to direct execution");
|
|
1867
|
-
return input.execute();
|
|
1868
|
-
}
|
|
1869
|
-
}
|
|
1870
|
-
async handleRecoveryModelSelect(sessionKey, _sessionId, modelProfileId, session, thread) {
|
|
1871
|
-
this.sessions.delete(sessionKey);
|
|
1872
|
-
await this.executeRecoveryModelSession(session, thread, {
|
|
1873
|
-
nextTurnModelProfileId: modelProfileId,
|
|
1874
|
-
});
|
|
1875
|
-
}
|
|
1876
|
-
async handleRecoveryModelSkip(sessionKey, _sessionId, session, thread) {
|
|
1877
|
-
this.sessions.delete(sessionKey);
|
|
1878
|
-
await this.executeRecoveryModelSession(session, thread);
|
|
1879
|
-
}
|
|
1880
|
-
async handleRecoveryModelText(sessionKey, session, text, thread) {
|
|
1881
|
-
const profile = resolveProfileByTextOrIndex(text.trim(), session.profiles);
|
|
1882
|
-
if (profile) {
|
|
1883
|
-
this.sessions.delete(sessionKey);
|
|
1884
|
-
await this.executeRecoveryModelSession(session, thread, {
|
|
1885
|
-
nextTurnModelProfileId: profile.id,
|
|
1886
|
-
});
|
|
1887
|
-
return;
|
|
1888
|
-
}
|
|
1889
|
-
await this.sendHtml(thread, escapeHtml(`Model must match an available profile.\n${buildRecoveryModelPrompt({ session })}`), this.buildRecoveryModelReplyMarkup(session));
|
|
1890
|
-
}
|
|
1891
|
-
async executeRecoveryModelSession(session, thread, opts) {
|
|
1892
|
-
if (session.recoveryKind === "retry") {
|
|
1893
|
-
const retryOpts = {
|
|
1894
|
-
...(opts?.nextTurnModelProfileId !== undefined ? opts : {}),
|
|
1895
|
-
actor: TELEGRAM_ACTOR,
|
|
1896
|
-
};
|
|
1897
|
-
void this.input.deps.commands.retryProcess(session.instanceId, retryOpts).then((result) => {
|
|
1898
|
-
this.sendCommandResult(thread, result, "Retry started.", "Retry failed");
|
|
1899
|
-
});
|
|
1900
|
-
}
|
|
1901
|
-
else {
|
|
1902
|
-
const continueSession = buildContinueSession({
|
|
1903
|
-
instanceId: session.instanceId,
|
|
1904
|
-
turnRecordId: session.turnRecordId ?? "",
|
|
1905
|
-
nextTurnModelProfileId: opts?.nextTurnModelProfileId,
|
|
1906
|
-
});
|
|
1907
|
-
const key = threadKey(thread.chatId, thread.messageThreadId);
|
|
1908
|
-
this.sessions.set(key, continueSession);
|
|
1909
|
-
await this.sendCurrentSessionPrompt(thread, continueSession);
|
|
1910
|
-
}
|
|
1911
|
-
}
|
|
1912
|
-
async sendRecoveryModelPrompt(thread, session) {
|
|
1913
|
-
await this.sendHtml(thread, escapeHtml(buildRecoveryModelPrompt({ session })), this.buildRecoveryModelReplyMarkup(session));
|
|
1914
|
-
}
|
|
1915
|
-
buildRecoveryModelReplyMarkup(session) {
|
|
1916
|
-
const buttons = [];
|
|
1917
|
-
let index = 0;
|
|
1918
|
-
for (const profile of session.profiles.slice(0, 20)) {
|
|
1919
|
-
index += 1;
|
|
1920
|
-
buttons.push({
|
|
1921
|
-
text: profile.id,
|
|
1922
|
-
callbackData: `ams:${session.instanceId}:${session.sessionId}:${index}`,
|
|
1923
|
-
});
|
|
1924
|
-
}
|
|
1925
|
-
buttons.push({
|
|
1926
|
-
text: "Keep current",
|
|
1927
|
-
callbackData: `amk:${session.instanceId}:${session.sessionId}`,
|
|
1928
|
-
});
|
|
1929
|
-
return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : undefined;
|
|
1930
|
-
}
|
|
1931
|
-
async executeProcessAction(instanceId, action, input, thread, opts) {
|
|
1932
|
-
const executeOpts = {
|
|
1933
|
-
source: "ui",
|
|
1934
|
-
origin: "external_interface",
|
|
1935
|
-
actor: TELEGRAM_ACTOR,
|
|
1936
|
-
};
|
|
1937
|
-
if (opts?.nextTurnModelProfileId !== undefined) {
|
|
1938
|
-
executeOpts.nextTurnModelProfileId = opts.nextTurnModelProfileId;
|
|
1939
|
-
}
|
|
1940
|
-
const result = await this.input.deps.processActions.executeAction(instanceId, action.id, input, executeOpts);
|
|
1941
|
-
await this.sendCommandResult(thread, result, buildActionSubmittedMessage({ action, values: input }), `Action failed: ${action.label}`);
|
|
1942
|
-
}
|
|
1943
|
-
async sendCommandResult(thread, result, successText, fallbackError) {
|
|
1944
|
-
await this.sendHtml(thread, result.ok ? successText : `⚠️ ${escapeHtml(result.error ?? result.message ?? fallbackError)}`);
|
|
1945
|
-
}
|
|
1946
|
-
isAllowed(from) {
|
|
1947
|
-
return typeof from?.id === "number" && this.input.config.allowUserIds.includes(from.id);
|
|
1948
|
-
}
|
|
1949
|
-
async sendHtml(thread, text, replyMarkup) {
|
|
1950
|
-
await this.sendHtmlToChat(thread.chatId, thread.messageThreadId, text, replyMarkup);
|
|
1951
|
-
}
|
|
1952
|
-
async sendResultParts(thread, instanceId, turnRecordId, parts) {
|
|
1953
|
-
for (const [index, part] of parts.entries()) {
|
|
1954
|
-
if (part.kind === "html") {
|
|
1955
|
-
await this.sendHtml(thread, part.html);
|
|
1956
|
-
continue;
|
|
1957
|
-
}
|
|
1958
|
-
if (part.kind === "mermaid") {
|
|
1959
|
-
try {
|
|
1960
|
-
await this.sendPhotoWithDocumentFallback(thread, {
|
|
1961
|
-
bytes: await renderMermaidPng(part.source),
|
|
1962
|
-
filename: `diagram-${index + 1}.png`,
|
|
1963
|
-
caption: "Mermaid diagram",
|
|
1964
|
-
});
|
|
1965
|
-
}
|
|
1966
|
-
catch (error) {
|
|
1967
|
-
this.logError(error, "Telegram Mermaid rendering failed; sending diagram source");
|
|
1968
|
-
await this.sendHtml(thread, `⚠️ <b>Diagram could not be rendered</b>\n<pre><code>${escapeHtml(part.source)}</code></pre>`);
|
|
1969
|
-
}
|
|
1970
|
-
continue;
|
|
1971
|
-
}
|
|
1972
|
-
try {
|
|
1973
|
-
const bytes = await this.input.deps.resultImages?.get(instanceId, turnRecordId, part.imageId);
|
|
1974
|
-
if (!bytes)
|
|
1975
|
-
throw new Error("Managed result image is unavailable");
|
|
1976
|
-
await this.sendPhotoWithDocumentFallback(thread, {
|
|
1977
|
-
bytes,
|
|
1978
|
-
filename: part.imageId,
|
|
1979
|
-
...(part.alt.trim() ? { caption: part.alt.trim().slice(0, 900) } : {}),
|
|
1980
|
-
});
|
|
1981
|
-
}
|
|
1982
|
-
catch (error) {
|
|
1983
|
-
this.logError(error, "Telegram result image delivery failed");
|
|
1984
|
-
const label = part.alt.trim() || part.imageId;
|
|
1985
|
-
await this.sendHtml(thread, `⚠️ Image unavailable: ${escapeHtml(label)}`);
|
|
1986
|
-
}
|
|
1987
|
-
}
|
|
1988
|
-
}
|
|
1989
|
-
async sendPhotoWithDocumentFallback(thread, file) {
|
|
1990
|
-
const input = { ...messageTarget(thread.chatId, thread.messageThreadId), ...file };
|
|
1991
|
-
try {
|
|
1992
|
-
await this.input.client.sendPhoto(input);
|
|
1993
|
-
}
|
|
1994
|
-
catch (error) {
|
|
1995
|
-
this.logError(error, "Telegram photo send failed; retrying as a document");
|
|
1996
|
-
await this.input.client.sendDocument(input);
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
async sendPlainToChat(chatId, messageThreadId, text, replyMarkup) {
|
|
2000
|
-
const chunks = splitPlainTelegramText(text, this.input.config.markdown.maxChars);
|
|
2001
|
-
for (const [index, chunk] of chunks.entries()) {
|
|
2002
|
-
const isLast = index === chunks.length - 1;
|
|
2003
|
-
await this.input.client.sendMessage({
|
|
2004
|
-
...messageTarget(chatId, messageThreadId),
|
|
2005
|
-
text: chunk,
|
|
2006
|
-
...(isLast && replyMarkup ? { replyMarkup } : {}),
|
|
2007
|
-
});
|
|
2008
|
-
}
|
|
2009
|
-
}
|
|
2010
|
-
async sendHtmlToChat(chatId, messageThreadId, text, replyMarkup) {
|
|
2011
|
-
const chunks = splitTelegramHtml(text, this.input.config.markdown.maxChars);
|
|
2012
|
-
for (const [index, chunk] of chunks.entries()) {
|
|
2013
|
-
const isLast = index === chunks.length - 1;
|
|
2014
|
-
try {
|
|
2015
|
-
await this.input.client.sendMessage({
|
|
2016
|
-
...messageTarget(chatId, messageThreadId),
|
|
2017
|
-
text: chunk,
|
|
2018
|
-
parseMode: "HTML",
|
|
2019
|
-
...(isLast && replyMarkup ? { replyMarkup } : {}),
|
|
2020
|
-
});
|
|
2021
|
-
}
|
|
2022
|
-
catch (error) {
|
|
2023
|
-
this.logError(error, "Telegram HTML chunk send failed; retrying chunk as plain text");
|
|
2024
|
-
await this.sendPlainToChat(chatId, messageThreadId, telegramHtmlToPlainText(chunk), isLast ? replyMarkup : undefined);
|
|
2025
|
-
}
|
|
2026
|
-
}
|
|
2027
|
-
}
|
|
2028
|
-
logError(error, message) {
|
|
2029
|
-
this.input.logger?.warn?.({ err: error instanceof Error ? error.message : String(error) }, message);
|
|
2030
|
-
}
|
|
2031
|
-
}
|
|
2032
|
-
//# sourceMappingURL=bridge.js.map
|