@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/index.js
CHANGED
|
@@ -1,56 +1,3726 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
coreHostCapabilities,
|
|
4
|
+
createCapabilityToken
|
|
5
|
+
} from "@leitwerk-dev/process-sdk";
|
|
6
|
+
|
|
7
|
+
// src/bridge.ts
|
|
8
|
+
import { randomBytes } from "crypto";
|
|
9
|
+
import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
|
|
10
|
+
|
|
11
|
+
// src/actions.ts
|
|
12
|
+
import {
|
|
13
|
+
FAILED_TURN_RECOVERY_METADATA_KEY,
|
|
14
|
+
readFailedTurnRecoveryContext
|
|
15
|
+
} from "@leitwerk-dev/domain";
|
|
16
|
+
var CALLBACKS = {
|
|
17
|
+
retry: "r",
|
|
18
|
+
continue: "c"
|
|
19
|
+
};
|
|
20
|
+
function rows(items, size) {
|
|
21
|
+
return Array.from({ length: Math.ceil(items.length / size) }, (_, index) => [
|
|
22
|
+
...items.slice(index * size, index * size + size)
|
|
23
|
+
]);
|
|
24
|
+
}
|
|
25
|
+
function continuableFailedTurnRecordId(process2) {
|
|
26
|
+
if (process2.lifecycleStatus !== "error" || process2.currentExecution?.kind !== "worker_start") {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
const recovery = process2.metadata?.[FAILED_TURN_RECOVERY_METADATA_KEY];
|
|
30
|
+
const turnRecordId = recovery && typeof recovery === "object" && !Array.isArray(recovery) ? recovery.turnRecordId : null;
|
|
31
|
+
return typeof turnRecordId === "string" && readFailedTurnRecoveryContext(process2.metadata, turnRecordId) ? turnRecordId : null;
|
|
32
|
+
}
|
|
33
|
+
function buildActionKeyboard(input) {
|
|
34
|
+
const buttons = input.actions.map((action) => ({
|
|
35
|
+
text: action.label,
|
|
36
|
+
callbackData: `a:${input.process.id}:${action.id}`
|
|
37
|
+
}));
|
|
38
|
+
if (input.process.lifecycleStatus === "error" && input.process.currentExecution) {
|
|
39
|
+
buttons.push({ text: "Retry", callbackData: `${CALLBACKS.retry}:${input.process.id}` });
|
|
40
|
+
if (continuableFailedTurnRecordId(input.process)) {
|
|
41
|
+
buttons.push({ text: "Continue", callbackData: `${CALLBACKS.continue}:${input.process.id}` });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return buttons.length ? { inlineKeyboard: rows(buttons, 2) } : void 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/actor.ts
|
|
48
|
+
var TELEGRAM_ACTOR = {
|
|
49
|
+
id: "telegram",
|
|
50
|
+
kind: "channel",
|
|
51
|
+
provider: "telegram"
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/form-session.ts
|
|
55
|
+
import {
|
|
56
|
+
emptyQuestionDrafts
|
|
57
|
+
} from "@leitwerk-dev/domain";
|
|
58
|
+
import { resolvePromptCacheSwitch } from "@leitwerk-dev/protocol/http-contracts";
|
|
59
|
+
function buildActionFormSession(input) {
|
|
60
|
+
return {
|
|
61
|
+
kind: "action_form",
|
|
62
|
+
instanceId: input.instanceId,
|
|
63
|
+
actionId: input.actionId,
|
|
64
|
+
actionLabel: input.actionLabel ?? input.actionId,
|
|
65
|
+
actionPreview: input.actionPreview ?? null,
|
|
66
|
+
sessionId: input.sessionId,
|
|
67
|
+
form: input.form,
|
|
68
|
+
fieldIndex: 0,
|
|
69
|
+
values: {},
|
|
70
|
+
expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1e3)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function buildQuestionSession(input) {
|
|
74
|
+
return {
|
|
75
|
+
kind: "question",
|
|
76
|
+
instanceId: input.instanceId,
|
|
77
|
+
request: input.request,
|
|
78
|
+
questionIndex: 0,
|
|
79
|
+
draft: emptyQuestionDrafts(input.request.questions),
|
|
80
|
+
expiresAt: Number.POSITIVE_INFINITY
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function buildQuestionPrompt(session) {
|
|
84
|
+
const question = session.request.questions[session.questionIndex];
|
|
85
|
+
if (!question) return "Send your answer.";
|
|
86
|
+
const options = question.options.map(
|
|
87
|
+
(option) => `\u2022 ${option.label}${option.details ? ` \u2014 ${option.details}` : ""}`
|
|
88
|
+
);
|
|
89
|
+
return [
|
|
90
|
+
`\u2753 Question ${session.questionIndex + 1} of ${session.request.questions.length}`,
|
|
91
|
+
question.question,
|
|
92
|
+
...options,
|
|
93
|
+
"Reply with your answer in free text."
|
|
94
|
+
].join("\n");
|
|
95
|
+
}
|
|
96
|
+
function applyQuestionText(session, text) {
|
|
97
|
+
const answer = session.draft[session.questionIndex];
|
|
98
|
+
if (!answer || text.trim() === "") {
|
|
99
|
+
return {
|
|
100
|
+
done: false,
|
|
101
|
+
draft: session.draft,
|
|
102
|
+
prompt: `Answer must not be empty.
|
|
103
|
+
${buildQuestionPrompt(session)}`
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
answer.freeText = text.trim();
|
|
107
|
+
session.questionIndex += 1;
|
|
108
|
+
return session.questionIndex < session.request.questions.length ? { done: false, draft: session.draft, prompt: buildQuestionPrompt(session) } : { done: true, draft: session.draft };
|
|
109
|
+
}
|
|
110
|
+
function buildContinueSession(input) {
|
|
111
|
+
return {
|
|
112
|
+
kind: "continue",
|
|
113
|
+
instanceId: input.instanceId,
|
|
114
|
+
turnRecordId: input.turnRecordId,
|
|
115
|
+
nextTurnModelProfileId: input.nextTurnModelProfileId ?? null,
|
|
116
|
+
expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1e3)
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function currentField(session) {
|
|
120
|
+
return session.form.fields[session.fieldIndex] ?? null;
|
|
121
|
+
}
|
|
122
|
+
function buildFieldPrompt(field) {
|
|
123
|
+
const required = field.required ? " required" : "";
|
|
124
|
+
const description = field.description ? `
|
|
125
|
+
${field.description}` : "";
|
|
126
|
+
const hint = field.placeholder ? `
|
|
127
|
+
Hint: ${field.placeholder}` : "";
|
|
128
|
+
return `Enter ${field.label}${required}.${description}${hint}`;
|
|
129
|
+
}
|
|
130
|
+
function canSkipActionFormField(field) {
|
|
131
|
+
return Boolean(field && !field.required);
|
|
132
|
+
}
|
|
133
|
+
function advanceFormField(session) {
|
|
134
|
+
session.fieldIndex += 1;
|
|
135
|
+
const field = currentField(session);
|
|
136
|
+
return field ? { ok: true, done: false, prompt: buildFieldPrompt(field) } : { ok: true, done: true, values: session.values };
|
|
137
|
+
}
|
|
138
|
+
function applyFormSkip(session) {
|
|
139
|
+
const field = currentField(session);
|
|
140
|
+
if (!field) {
|
|
141
|
+
return { ok: true, done: true, values: session.values };
|
|
142
|
+
}
|
|
143
|
+
if (!canSkipActionFormField(field)) {
|
|
144
|
+
return { ok: false, prompt: `${field.label} is required.
|
|
145
|
+
${buildFieldPrompt(field)}` };
|
|
146
|
+
}
|
|
147
|
+
return advanceFormField(session);
|
|
148
|
+
}
|
|
149
|
+
function parseBoolean(value) {
|
|
150
|
+
const normalized = value.trim().toLowerCase();
|
|
151
|
+
if (["yes", "y", "true", "1"].includes(normalized)) return true;
|
|
152
|
+
if (["no", "n", "false", "0"].includes(normalized)) return false;
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
function parseFieldValue(field, text) {
|
|
156
|
+
const trimmed = text.trim();
|
|
157
|
+
if (!trimmed && field.required) {
|
|
158
|
+
return { ok: false, error: `${field.label} is required.` };
|
|
159
|
+
}
|
|
160
|
+
if (!trimmed) {
|
|
161
|
+
return { ok: true, value: "" };
|
|
162
|
+
}
|
|
163
|
+
if (field.kind === "number") {
|
|
164
|
+
const value = Number(trimmed);
|
|
165
|
+
return Number.isFinite(value) ? { ok: true, value } : { ok: false, error: `${field.label} must be a number.` };
|
|
166
|
+
}
|
|
167
|
+
if (field.kind === "boolean") {
|
|
168
|
+
const value = parseBoolean(trimmed);
|
|
169
|
+
return value === null ? { ok: false, error: `${field.label} must be yes or no.` } : { ok: true, value };
|
|
170
|
+
}
|
|
171
|
+
return { ok: true, value: text };
|
|
172
|
+
}
|
|
173
|
+
function applyFormText(session, text) {
|
|
174
|
+
const field = currentField(session);
|
|
175
|
+
if (!field) {
|
|
176
|
+
return { ok: true, done: true, values: session.values };
|
|
177
|
+
}
|
|
178
|
+
const parsed = parseFieldValue(field, text);
|
|
179
|
+
if (!parsed.ok) {
|
|
180
|
+
return { ok: false, prompt: `${parsed.error}
|
|
181
|
+
${buildFieldPrompt(field)}` };
|
|
182
|
+
}
|
|
183
|
+
session.values[field.id] = parsed.value;
|
|
184
|
+
return advanceFormField(session);
|
|
185
|
+
}
|
|
186
|
+
function buildActionModelSession(input) {
|
|
187
|
+
return {
|
|
188
|
+
kind: "action_model",
|
|
189
|
+
instanceId: input.instanceId,
|
|
190
|
+
actionId: input.actionId,
|
|
191
|
+
actionLabel: input.actionLabel,
|
|
192
|
+
actionPreview: input.actionPreview ?? null,
|
|
193
|
+
sessionId: input.sessionId,
|
|
194
|
+
formValues: input.formValues,
|
|
195
|
+
preview: input.preview,
|
|
196
|
+
profiles: input.profiles,
|
|
197
|
+
expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1e3)
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function buildActionModelSwitchWarning(input) {
|
|
201
|
+
const resolution = resolvePromptCacheSwitch({
|
|
202
|
+
context: input.session.preview.warmPromptCache,
|
|
203
|
+
effectiveModelProfileId: input.effectiveModelProfileId,
|
|
204
|
+
selectableModelProfileIds: input.session.profiles.map((profile) => profile.id),
|
|
205
|
+
now: input.now
|
|
206
|
+
});
|
|
207
|
+
if (!resolution.switchingModelMayBypassPromptCache) return null;
|
|
208
|
+
const recommendedId = resolution.recommendedModelProfileId;
|
|
209
|
+
if (!recommendedId) {
|
|
210
|
+
return "\u26A0 Switching models may lose prompt-cache reuse and increase costs. No equivalent selectable profile is currently available.";
|
|
211
|
+
}
|
|
212
|
+
const recommendation = input.session.profiles.find((profile) => profile.id === recommendedId)?.label ?? recommendedId;
|
|
213
|
+
return `\u26A0 Switching models may lose prompt-cache reuse and increase costs. To keep using the previous model, choose ${recommendation}.`;
|
|
214
|
+
}
|
|
215
|
+
function buildActionModelPrompt(input) {
|
|
216
|
+
const { session } = input;
|
|
217
|
+
const lines = [`Next-turn model for: ${session.actionLabel}`];
|
|
218
|
+
const preview = session.preview;
|
|
219
|
+
if (preview.description) {
|
|
220
|
+
lines.push(`Target turn: ${preview.description}`);
|
|
221
|
+
}
|
|
222
|
+
const resolved = preview.resolvedModel;
|
|
223
|
+
if (resolved?.status === "resolved" && resolved.modelProfileId) {
|
|
224
|
+
const label = session.profiles.find((p) => p.id === resolved.modelProfileId)?.label ?? resolved.modelProfileId;
|
|
225
|
+
lines.push(`Default/resolved: ${label}`);
|
|
226
|
+
} else if (resolved?.status === "none") {
|
|
227
|
+
lines.push("No model is currently resolved.");
|
|
228
|
+
}
|
|
229
|
+
if (session.profiles.length === 0) {
|
|
230
|
+
lines.push("No model profiles are available.");
|
|
231
|
+
} else {
|
|
232
|
+
lines.push("Choose a model by button, number, or profile id.");
|
|
233
|
+
lines.push("Send /skip to keep the default/resolved model.");
|
|
234
|
+
}
|
|
235
|
+
lines.push("Send /cancel to discard.");
|
|
236
|
+
return lines.join("\n");
|
|
237
|
+
}
|
|
238
|
+
function buildRecoveryModelSession(input) {
|
|
239
|
+
return {
|
|
240
|
+
kind: "recovery_model",
|
|
241
|
+
instanceId: input.instanceId,
|
|
242
|
+
recoveryKind: input.recoveryKind,
|
|
243
|
+
turnRecordId: input.turnRecordId,
|
|
244
|
+
sessionId: input.sessionId,
|
|
245
|
+
profiles: input.profiles,
|
|
246
|
+
expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 10 * 60 * 1e3)
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function buildRecoveryModelPrompt(input) {
|
|
250
|
+
const { session } = input;
|
|
251
|
+
const label = session.recoveryKind === "retry" ? "Retry" : "Continue";
|
|
252
|
+
const lines = [`Next-turn model for: ${label}`];
|
|
253
|
+
if (session.profiles.length === 0) {
|
|
254
|
+
lines.push("No model profiles are available.");
|
|
255
|
+
} else {
|
|
256
|
+
lines.push("Choose a model by button, number, or profile id.");
|
|
257
|
+
lines.push("Send /skip to keep the current model.");
|
|
258
|
+
}
|
|
259
|
+
lines.push("Send /cancel to discard.");
|
|
260
|
+
return lines.join("\n");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// src/launch-session.ts
|
|
264
|
+
import {
|
|
265
|
+
normalizeLaunchModelConfigInput,
|
|
266
|
+
parseStrictInstanceTurnConfigsJson,
|
|
267
|
+
trimToNull
|
|
268
|
+
} from "@leitwerk-dev/domain";
|
|
269
|
+
function createLaunchSession(input) {
|
|
270
|
+
const values = {};
|
|
271
|
+
for (const field of input.launcher.launchConfigSchema.fields) {
|
|
272
|
+
const normalized = normalizeFieldValue(field, input.defaults?.[field.id]);
|
|
273
|
+
if (normalized.ok) {
|
|
274
|
+
values[field.id] = normalized.value;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
kind: "launch",
|
|
279
|
+
launcherId: input.launcher.id,
|
|
280
|
+
fieldIndex: 0,
|
|
281
|
+
fieldOrder: buildFieldOrder(input.launcher),
|
|
282
|
+
values,
|
|
283
|
+
modelConfig: { defaultModelProfileId: null, turnConfigs: {} },
|
|
284
|
+
modelConfigTouched: false,
|
|
285
|
+
modelEdit: null,
|
|
286
|
+
expiresAt: (input.now ?? Date.now()) + (input.ttlMs ?? 20 * 60 * 1e3)
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function buildLaunchInput(session) {
|
|
290
|
+
return { ...session.values };
|
|
291
|
+
}
|
|
292
|
+
function buildLaunchModelConfig(session) {
|
|
293
|
+
return normalizeLaunchModelConfigInput(session.modelConfig);
|
|
294
|
+
}
|
|
295
|
+
function seedLaunchModelConfigFromPlan(session, launchPlan) {
|
|
296
|
+
if (session.modelConfigTouched) return;
|
|
297
|
+
const parsedTurnConfigs = parseStrictInstanceTurnConfigsJson(
|
|
298
|
+
launchPlan.processId,
|
|
299
|
+
launchPlan.processInput.turnConfigsJson
|
|
300
|
+
);
|
|
301
|
+
session.modelConfig = normalizeLaunchModelConfigInput({
|
|
302
|
+
defaultModelProfileId: launchPlan.processInput.defaultModelProfileId ?? null,
|
|
303
|
+
turnConfigs: parsedTurnConfigs.ok ? parsedTurnConfigs.value : {}
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
function hasLaunchModelControls(schema) {
|
|
307
|
+
return Boolean(schema && schema.availableProfiles.length > 0 && schema.llmTurns.length > 0);
|
|
308
|
+
}
|
|
309
|
+
function buildLaunchModelStepOrder(schema) {
|
|
310
|
+
return [
|
|
311
|
+
{ kind: "default", key: "default", label: "Default model" },
|
|
312
|
+
...schema.llmTurns.map((turn) => ({
|
|
313
|
+
kind: "turn",
|
|
314
|
+
key: `turn:${turn.turnId}`,
|
|
315
|
+
turnId: turn.turnId,
|
|
316
|
+
label: turn.description || turn.turnId
|
|
317
|
+
}))
|
|
318
|
+
];
|
|
319
|
+
}
|
|
320
|
+
function beginLaunchModelEdit(session, schema) {
|
|
321
|
+
session.modelEdit = { stepIndex: 0 };
|
|
322
|
+
return { ok: true, done: false, step: buildLaunchModelStepOrder(schema)[0] };
|
|
323
|
+
}
|
|
324
|
+
function currentLaunchModelStep(session, schema) {
|
|
325
|
+
if (!session.modelEdit) return null;
|
|
326
|
+
return buildLaunchModelStepOrder(schema)[session.modelEdit.stepIndex] ?? null;
|
|
327
|
+
}
|
|
328
|
+
function finishLaunchModelEdit(session) {
|
|
329
|
+
session.modelEdit = null;
|
|
330
|
+
}
|
|
331
|
+
function currentLaunchField(session, launcher) {
|
|
332
|
+
const fieldId = session.fieldOrder[session.fieldIndex];
|
|
333
|
+
return fieldId ? launcher.launchConfigSchema.fields.find((field) => field.id === fieldId) ?? null : null;
|
|
334
|
+
}
|
|
335
|
+
function isLaunchSessionComplete(session) {
|
|
336
|
+
return session.fieldIndex >= session.fieldOrder.length;
|
|
337
|
+
}
|
|
338
|
+
function getLaunchFieldOptions(field, dynamicOptionsById) {
|
|
339
|
+
if (field.kind !== "select") return [];
|
|
340
|
+
return dynamicOptionsById[field.id] ?? field.options ?? [];
|
|
341
|
+
}
|
|
342
|
+
function buildLaunchFieldPrompt(input) {
|
|
343
|
+
const { field } = input;
|
|
344
|
+
const lines = [`${field.required ? "Required" : "Optional"} field: ${field.label}`];
|
|
345
|
+
if (field.description?.trim()) lines.push(field.description.trim());
|
|
346
|
+
const current = formatLaunchFieldValue(input.currentValue);
|
|
347
|
+
if (current) lines.push(`Current/default: ${current}`);
|
|
348
|
+
if (field.kind === "boolean") {
|
|
349
|
+
lines.push("Reply yes or no, or use the buttons.");
|
|
350
|
+
} else if (field.kind === "number") {
|
|
351
|
+
lines.push("Reply with a number.");
|
|
352
|
+
} else if (field.kind === "select") {
|
|
353
|
+
const options = input.options ?? [];
|
|
354
|
+
if (options.length > 0) {
|
|
355
|
+
lines.push("Choose one option by button, number, value, or label:");
|
|
356
|
+
const max = input.maxOptionsInPrompt ?? 12;
|
|
357
|
+
for (const [index, option] of options.slice(0, max).entries()) {
|
|
358
|
+
lines.push(
|
|
359
|
+
`${index + 1}. ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}`
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
if (options.length > max) {
|
|
363
|
+
lines.push(`\u2026and ${options.length - max} more. Use a button or type the exact value.`);
|
|
364
|
+
}
|
|
365
|
+
} else {
|
|
366
|
+
lines.push("Reply with a value for this field.");
|
|
367
|
+
}
|
|
368
|
+
} else if (input.recentValues?.length) {
|
|
369
|
+
lines.push("Choose a recent value or reply with a different value.");
|
|
370
|
+
} else {
|
|
371
|
+
lines.push("Reply with the value for this field.");
|
|
372
|
+
}
|
|
373
|
+
if (!field.required || hasPresentValue(input.currentValue)) {
|
|
374
|
+
lines.push("Send /skip to keep the current/default value or leave it blank.");
|
|
375
|
+
}
|
|
376
|
+
return lines.join("\n");
|
|
377
|
+
}
|
|
378
|
+
function buildLaunchModelSummary(input) {
|
|
379
|
+
const config = buildLaunchModelConfig(input.session);
|
|
380
|
+
const lines = ["Model setup:"];
|
|
381
|
+
const defaultProfileId = trimToNull(config.defaultModelProfileId);
|
|
382
|
+
const defaultPreview = input.preview?.defaultModel.profile;
|
|
383
|
+
lines.push(
|
|
384
|
+
`- Default: ${defaultProfileId ? formatLaunchModelProfile(input.schema, defaultProfileId) : defaultPreview?.label ?? "inherited/recommended"}${defaultProfileId ? " (override)" : ""}`
|
|
385
|
+
);
|
|
386
|
+
for (const turn of input.schema.llmTurns) {
|
|
387
|
+
const override = trimToNull(config.turnConfigs?.[turn.turnId]?.modelProfileId);
|
|
388
|
+
const preview = input.preview?.turns.find((candidate) => candidate.turnId === turn.turnId);
|
|
389
|
+
lines.push(
|
|
390
|
+
`- ${turn.description || turn.turnId}: ${override ? formatLaunchModelProfile(input.schema, override) : preview?.effective.profile?.label ?? "inherited/recommended"}${override ? " (override)" : ""}`
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
return lines.join("\n");
|
|
394
|
+
}
|
|
395
|
+
function buildLaunchModelStepPrompt(input) {
|
|
396
|
+
const currentOverride = getLaunchModelStepOverride(input.session, input.step);
|
|
397
|
+
const effective = getLaunchModelStepPreview(input.preview, input.step);
|
|
398
|
+
const lines = [`Model setup: ${input.step.label}`];
|
|
399
|
+
lines.push(
|
|
400
|
+
`Current override: ${currentOverride ? formatLaunchModelProfile(input.schema, currentOverride) : "inherited/recommended"}`
|
|
401
|
+
);
|
|
402
|
+
if (effective) lines.push(`Effective now: ${effective}`);
|
|
403
|
+
lines.push("Choose a model by button, number, or profile id.");
|
|
404
|
+
const max = input.maxOptionsInPrompt ?? 12;
|
|
405
|
+
for (const [index, profile] of input.schema.availableProfiles.slice(0, max).entries()) {
|
|
406
|
+
lines.push(`${index + 1}. ${profile.label}`);
|
|
407
|
+
}
|
|
408
|
+
if (input.schema.availableProfiles.length > max) {
|
|
409
|
+
lines.push(
|
|
410
|
+
`\u2026and ${input.schema.availableProfiles.length - max} more. Use a button or type the exact profile id.`
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
lines.push("Send /skip to keep this value, or use Inherit to clear an override.");
|
|
414
|
+
return lines.join("\n");
|
|
415
|
+
}
|
|
416
|
+
function applyLaunchModelStepText(session, schema, text) {
|
|
417
|
+
const step = currentLaunchModelStep(session, schema);
|
|
418
|
+
if (!step) return { ok: true, done: true };
|
|
419
|
+
const trimmed = text.trim();
|
|
420
|
+
const normalized = trimmed.toLowerCase();
|
|
421
|
+
if (/^\/skip(?:@\w+)?$/i.test(trimmed) || normalized === "skip" || !trimmed) {
|
|
422
|
+
return applyLaunchModelStepAction(session, schema, { action: "skip" });
|
|
423
|
+
}
|
|
424
|
+
if (["inherit", "inherited", "clear", "none"].includes(normalized)) {
|
|
425
|
+
return applyLaunchModelStepAction(session, schema, { action: "inherit" });
|
|
426
|
+
}
|
|
427
|
+
const matched = matchByNumberValueOrLabel(
|
|
428
|
+
trimmed,
|
|
429
|
+
schema.availableProfiles,
|
|
430
|
+
(profile) => profile.id
|
|
431
|
+
);
|
|
432
|
+
return matched ? applyLaunchModelStepAction(session, schema, { action: "set", value: matched.id }) : launchModelStepError(step, schema, session);
|
|
433
|
+
}
|
|
434
|
+
function applyLaunchModelStepAction(session, schema, action) {
|
|
435
|
+
const step = currentLaunchModelStep(session, schema);
|
|
436
|
+
if (!step) return { ok: true, done: true };
|
|
437
|
+
if (action.action === "skip") return advanceLaunchModelStep(session, schema);
|
|
438
|
+
if (action.action === "inherit") {
|
|
439
|
+
setLaunchModelStepOverride(session, step, null);
|
|
440
|
+
return advanceLaunchModelStep(session, schema);
|
|
441
|
+
}
|
|
442
|
+
const matched = schema.availableProfiles.find((profile) => profile.id === action.value);
|
|
443
|
+
if (!matched) return launchModelStepError(step, schema, session);
|
|
444
|
+
setLaunchModelStepOverride(session, step, matched.id);
|
|
445
|
+
return advanceLaunchModelStep(session, schema);
|
|
446
|
+
}
|
|
447
|
+
function advanceLaunchField(session, launcher) {
|
|
448
|
+
session.fieldIndex += 1;
|
|
449
|
+
const field = currentLaunchField(session, launcher);
|
|
450
|
+
return field ? { ok: true, done: false, field } : { ok: true, done: true, values: buildLaunchInput(session) };
|
|
451
|
+
}
|
|
452
|
+
function applyLaunchFieldText(session, launcher, text, dynamicOptionsById = {}) {
|
|
453
|
+
const field = currentLaunchField(session, launcher);
|
|
454
|
+
if (!field) {
|
|
455
|
+
return {
|
|
456
|
+
ok: true,
|
|
457
|
+
done: true,
|
|
458
|
+
values: buildLaunchInput(session)
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
const options = getLaunchFieldOptions(field, dynamicOptionsById);
|
|
462
|
+
const trimmed = text.trim();
|
|
463
|
+
const wantsSkip = /^\/skip(?:@\w+)?$/i.test(trimmed) || trimmed.toLowerCase() === "skip";
|
|
464
|
+
const parsed = wantsSkip ? skipField(field, session.values[field.id]) : parseFieldText(field, text, options);
|
|
465
|
+
if (!parsed.ok) {
|
|
466
|
+
return {
|
|
467
|
+
ok: false,
|
|
468
|
+
prompt: `${parsed.error}
|
|
469
|
+
${buildLaunchFieldPrompt({ field, currentValue: session.values[field.id], options })}`
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (parsed.setValue) {
|
|
473
|
+
session.values[field.id] = parsed.value;
|
|
474
|
+
}
|
|
475
|
+
return advanceLaunchField(session, launcher);
|
|
476
|
+
}
|
|
477
|
+
function applyLaunchFieldValue(session, launcher, value, dynamicOptionsById = {}) {
|
|
478
|
+
const field = currentLaunchField(session, launcher);
|
|
479
|
+
if (!field) {
|
|
480
|
+
return {
|
|
481
|
+
ok: true,
|
|
482
|
+
done: true,
|
|
483
|
+
values: buildLaunchInput(session)
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
const parsed = normalizeFieldValue(field, value);
|
|
487
|
+
if (!parsed.ok || field.required && !hasPresentValue(parsed.value)) {
|
|
488
|
+
const options = getLaunchFieldOptions(field, dynamicOptionsById);
|
|
489
|
+
return {
|
|
490
|
+
ok: false,
|
|
491
|
+
prompt: `${parsed.ok ? `${field.label} is required.` : parsed.error}
|
|
492
|
+
${buildLaunchFieldPrompt({ field, currentValue: session.values[field.id], options })}`
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
session.values[field.id] = parsed.value;
|
|
496
|
+
return advanceLaunchField(session, launcher);
|
|
497
|
+
}
|
|
498
|
+
function moveLaunchSessionToValidationField(session, launcher, errors) {
|
|
499
|
+
const fieldId = errors.find((error) => error.fieldId)?.fieldId;
|
|
500
|
+
if (!fieldId) return null;
|
|
501
|
+
const field = launcher.launchConfigSchema.fields.find((candidate) => candidate.id === fieldId);
|
|
502
|
+
if (!field) return null;
|
|
503
|
+
const index = session.fieldOrder.indexOf(fieldId);
|
|
504
|
+
if (index < 0) return null;
|
|
505
|
+
session.fieldIndex = index;
|
|
506
|
+
return field;
|
|
507
|
+
}
|
|
508
|
+
function buildFieldOrder(launcher) {
|
|
509
|
+
const fields = launcher.launchConfigSchema.fields;
|
|
510
|
+
return [
|
|
511
|
+
...fields.filter((field) => field.required).map((field) => field.id),
|
|
512
|
+
...fields.filter((field) => !field.required).map((field) => field.id)
|
|
513
|
+
];
|
|
514
|
+
}
|
|
515
|
+
function buildLaunchReview(input) {
|
|
516
|
+
const lines = [`Ready to start ${input.launcher.label}.`, "", "Launcher config:"];
|
|
517
|
+
for (const field of input.launcher.launchConfigSchema.fields) {
|
|
518
|
+
lines.push(
|
|
519
|
+
`- ${field.label}: ${formatLaunchFieldValue(input.session.values[field.id]) || "(empty)"}`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
lines.push("", "Use Start process to launch, or Cancel to discard this draft.");
|
|
523
|
+
return lines.join("\n");
|
|
524
|
+
}
|
|
525
|
+
function formatLaunchModelProfile(schema, modelProfileId) {
|
|
526
|
+
return schema.availableProfiles.find((profile) => profile.id === modelProfileId)?.label ?? modelProfileId;
|
|
527
|
+
}
|
|
528
|
+
function getLaunchModelStepOverride(session, step) {
|
|
529
|
+
const config = buildLaunchModelConfig(session);
|
|
530
|
+
return trimToNull(
|
|
531
|
+
step.kind === "default" ? config.defaultModelProfileId : config.turnConfigs?.[step.turnId]?.modelProfileId
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
function getLaunchModelStepPreview(preview, step) {
|
|
535
|
+
if (!preview) return null;
|
|
536
|
+
if (step.kind === "default") return preview.defaultModel.profile?.label ?? null;
|
|
537
|
+
return preview.turns.find((turn) => turn.turnId === step.turnId)?.effective.profile?.label ?? null;
|
|
538
|
+
}
|
|
539
|
+
function launchModelStepError(step, schema, session) {
|
|
540
|
+
return {
|
|
541
|
+
ok: false,
|
|
542
|
+
prompt: `${step.label} must match an available model profile.
|
|
543
|
+
${buildLaunchModelStepPrompt({ step, schema, session })}`
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function setLaunchModelStepOverride(session, step, modelProfileId) {
|
|
547
|
+
const current = buildLaunchModelConfig(session);
|
|
548
|
+
if (step.kind === "default") {
|
|
549
|
+
session.modelConfig = {
|
|
550
|
+
...current,
|
|
551
|
+
defaultModelProfileId: modelProfileId,
|
|
552
|
+
turnConfigs: current.turnConfigs ?? {}
|
|
553
|
+
};
|
|
554
|
+
} else if (modelProfileId !== null) {
|
|
555
|
+
session.modelConfig = {
|
|
556
|
+
...current,
|
|
557
|
+
turnConfigs: {
|
|
558
|
+
...current.turnConfigs ?? {},
|
|
559
|
+
[step.turnId]: { modelProfileId }
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
} else {
|
|
563
|
+
const turnConfigs = { ...current.turnConfigs ?? {} };
|
|
564
|
+
delete turnConfigs[step.turnId];
|
|
565
|
+
session.modelConfig = { ...current, turnConfigs };
|
|
566
|
+
}
|
|
567
|
+
session.modelConfigTouched = true;
|
|
568
|
+
}
|
|
569
|
+
function advanceLaunchModelStep(session, schema) {
|
|
570
|
+
if (!session.modelEdit) return { ok: true, done: true };
|
|
571
|
+
session.modelEdit = { stepIndex: session.modelEdit.stepIndex + 1 };
|
|
572
|
+
const next = currentLaunchModelStep(session, schema);
|
|
573
|
+
if (next) return { ok: true, done: false, step: next };
|
|
574
|
+
finishLaunchModelEdit(session);
|
|
575
|
+
return { ok: true, done: true };
|
|
576
|
+
}
|
|
577
|
+
function parseBoolean2(value) {
|
|
578
|
+
const normalized = value.trim().toLowerCase();
|
|
579
|
+
if (["yes", "y", "true", "1", "on"].includes(normalized)) return true;
|
|
580
|
+
if (["no", "n", "false", "0", "off"].includes(normalized)) return false;
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
function hasPresentValue(value) {
|
|
584
|
+
if (typeof value === "string") return value.trim() !== "";
|
|
585
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
586
|
+
if (typeof value === "boolean") return true;
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
function formatLaunchFieldValue(value) {
|
|
590
|
+
if (typeof value === "string") return value.trim();
|
|
591
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
592
|
+
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
593
|
+
return "";
|
|
594
|
+
}
|
|
595
|
+
function normalizeFieldValue(field, value) {
|
|
596
|
+
if (value === void 0 || value === null)
|
|
597
|
+
return { ok: false, error: `${field.label} is required.` };
|
|
598
|
+
if (field.kind === "boolean") {
|
|
599
|
+
if (typeof value === "boolean") return { ok: true, value };
|
|
600
|
+
if (typeof value === "string") {
|
|
601
|
+
const parsed = parseBoolean2(value);
|
|
602
|
+
if (parsed !== null) return { ok: true, value: parsed };
|
|
603
|
+
}
|
|
604
|
+
return { ok: false, error: `${field.label} must be yes or no.` };
|
|
605
|
+
}
|
|
606
|
+
if (field.kind === "number") {
|
|
607
|
+
const parsed = typeof value === "number" ? value : Number(String(value).trim());
|
|
608
|
+
return Number.isFinite(parsed) ? { ok: true, value: parsed } : { ok: false, error: `${field.label} must be a number.` };
|
|
609
|
+
}
|
|
610
|
+
return { ok: true, value: String(value) };
|
|
611
|
+
}
|
|
612
|
+
function skipField(field, currentValue) {
|
|
613
|
+
if (hasPresentValue(currentValue)) {
|
|
614
|
+
return { ok: true, setValue: false, value: currentValue };
|
|
615
|
+
}
|
|
616
|
+
if (field.required) {
|
|
617
|
+
return { ok: false, error: `${field.label} is required.` };
|
|
618
|
+
}
|
|
619
|
+
return { ok: true, setValue: true, value: field.kind === "boolean" ? false : "" };
|
|
620
|
+
}
|
|
621
|
+
function parseFieldText(field, text, options) {
|
|
622
|
+
const trimmed = text.trim();
|
|
623
|
+
if (!trimmed) {
|
|
624
|
+
return skipField(field, void 0);
|
|
625
|
+
}
|
|
626
|
+
if (field.kind === "select") {
|
|
627
|
+
const matched = matchByNumberValueOrLabel(trimmed, options, (option) => option.value);
|
|
628
|
+
if (matched) return { ok: true, setValue: true, value: matched.value };
|
|
629
|
+
if (options.length > 0) {
|
|
630
|
+
return { ok: false, error: `${field.label} must match one of the available options.` };
|
|
631
|
+
}
|
|
632
|
+
return { ok: true, setValue: true, value: trimmed };
|
|
633
|
+
}
|
|
634
|
+
const normalized = normalizeFieldValue(field, text);
|
|
635
|
+
if (!normalized.ok) return normalized;
|
|
636
|
+
if (field.required && !hasPresentValue(normalized.value)) {
|
|
637
|
+
return { ok: false, error: `${field.label} is required.` };
|
|
638
|
+
}
|
|
639
|
+
return { ok: true, setValue: true, value: normalized.value };
|
|
640
|
+
}
|
|
641
|
+
function matchByNumberValueOrLabel(text, options, getValue) {
|
|
642
|
+
const numeric = Number(text);
|
|
643
|
+
if (Number.isInteger(numeric) && numeric >= 1 && numeric <= options.length) {
|
|
644
|
+
return options[numeric - 1] ?? null;
|
|
645
|
+
}
|
|
646
|
+
const lower = text.toLowerCase();
|
|
647
|
+
return options.find((option) => getValue(option) === text) ?? options.find((option) => option.label.toLowerCase() === lower) ?? null;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/markdown-html.ts
|
|
651
|
+
import { parseManagedResultImagePath } from "@leitwerk-dev/worker-protocol";
|
|
652
|
+
import MarkdownIt from "markdown-it";
|
|
653
|
+
import { parseFragment } from "parse5";
|
|
654
|
+
var TELEGRAM_HARD_LIMIT = 4096;
|
|
655
|
+
var DEFAULT_TELEGRAM_SOFT_LIMIT = 3900;
|
|
656
|
+
var SAFE_LINK_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tg:"]);
|
|
657
|
+
var TELEGRAM_INLINE_TAGS = /* @__PURE__ */ new Map([
|
|
658
|
+
["b", "b"],
|
|
659
|
+
["strong", "b"],
|
|
660
|
+
["i", "i"],
|
|
661
|
+
["em", "i"],
|
|
662
|
+
["u", "u"],
|
|
663
|
+
["ins", "u"],
|
|
664
|
+
["s", "s"],
|
|
665
|
+
["strike", "s"],
|
|
666
|
+
["del", "s"]
|
|
667
|
+
]);
|
|
668
|
+
var BLOCK_TAGS = /* @__PURE__ */ new Set([
|
|
669
|
+
"article",
|
|
670
|
+
"aside",
|
|
671
|
+
"blockquote",
|
|
672
|
+
"body",
|
|
673
|
+
"dd",
|
|
674
|
+
"div",
|
|
675
|
+
"dl",
|
|
676
|
+
"dt",
|
|
677
|
+
"figcaption",
|
|
678
|
+
"figure",
|
|
679
|
+
"footer",
|
|
680
|
+
"form",
|
|
681
|
+
"header",
|
|
682
|
+
"main",
|
|
683
|
+
"nav",
|
|
684
|
+
"p",
|
|
685
|
+
"section",
|
|
686
|
+
"table",
|
|
687
|
+
"tbody",
|
|
688
|
+
"td",
|
|
689
|
+
"tfoot",
|
|
690
|
+
"th",
|
|
691
|
+
"thead",
|
|
692
|
+
"tr"
|
|
693
|
+
]);
|
|
694
|
+
var HEADING_TAG_PATTERN = /^h[1-6]$/;
|
|
695
|
+
var markdown = new MarkdownIt("commonmark", {
|
|
696
|
+
html: true,
|
|
697
|
+
linkify: false
|
|
698
|
+
});
|
|
699
|
+
markdown.renderer.rules.image = (tokens, index) => escapeTelegramHtml(tokens[index]?.content ?? "");
|
|
700
|
+
function escapeTelegramHtml(value) {
|
|
701
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
702
|
+
}
|
|
703
|
+
function escapeTelegramAttribute(value) {
|
|
704
|
+
return escapeTelegramHtml(value).replaceAll('"', """);
|
|
705
|
+
}
|
|
706
|
+
function isElement(node) {
|
|
707
|
+
return "tagName" in node;
|
|
708
|
+
}
|
|
709
|
+
function isTextNode(node) {
|
|
710
|
+
return node.nodeName === "#text";
|
|
711
|
+
}
|
|
712
|
+
function clampMaxChars(maxChars) {
|
|
713
|
+
return Math.min(Math.max(maxChars, 1), TELEGRAM_HARD_LIMIT);
|
|
714
|
+
}
|
|
715
|
+
function normalizeLineEndings(value) {
|
|
716
|
+
return value.replace(/\r\n?/g, "\n").trim();
|
|
717
|
+
}
|
|
718
|
+
function attr(element, name) {
|
|
719
|
+
return element.attrs.find((candidate) => candidate.name.toLowerCase() === name)?.value ?? null;
|
|
720
|
+
}
|
|
721
|
+
function safeHref(value) {
|
|
722
|
+
if (!value) return null;
|
|
723
|
+
try {
|
|
724
|
+
const parsed = new URL(value);
|
|
725
|
+
return SAFE_LINK_PROTOCOLS.has(parsed.protocol) ? value : null;
|
|
726
|
+
} catch {
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function renderChildren(element) {
|
|
731
|
+
return element.childNodes.map(renderNode).join("");
|
|
732
|
+
}
|
|
733
|
+
function collectText(node) {
|
|
734
|
+
if (isTextNode(node)) return node.value;
|
|
735
|
+
if (!isElement(node)) return "";
|
|
736
|
+
if (node.tagName.toLowerCase() === "br") return "\n";
|
|
737
|
+
return node.childNodes.map(collectText).join("");
|
|
738
|
+
}
|
|
739
|
+
function withTrailingNewline(value) {
|
|
740
|
+
const trimmed = value.trimEnd();
|
|
741
|
+
return trimmed ? `${trimmed}
|
|
742
|
+
` : "";
|
|
743
|
+
}
|
|
744
|
+
function renderNode(node) {
|
|
745
|
+
if (isTextNode(node)) return escapeTelegramHtml(node.value);
|
|
746
|
+
if (!isElement(node)) return "";
|
|
747
|
+
const tagName = node.tagName.toLowerCase();
|
|
748
|
+
if (tagName === "script" || tagName === "style") return "";
|
|
749
|
+
if (tagName === "br") return "\n";
|
|
750
|
+
if (tagName === "hr") return "\n\u2014\n";
|
|
751
|
+
if (tagName === "img") return escapeTelegramHtml(attr(node, "alt") ?? attr(node, "title") ?? "");
|
|
752
|
+
if (tagName === "pre") {
|
|
753
|
+
return withTrailingNewline(
|
|
754
|
+
`<pre><code>${escapeTelegramHtml(collectText(node).replace(/\n$/, ""))}</code></pre>`
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
if (tagName === "code") return `<code>${escapeTelegramHtml(collectText(node))}</code>`;
|
|
758
|
+
if (tagName === "a") {
|
|
759
|
+
const children = renderChildren(node);
|
|
760
|
+
const href = safeHref(attr(node, "href"));
|
|
761
|
+
return href ? `<a href="${escapeTelegramAttribute(href)}">${children}</a>` : children;
|
|
762
|
+
}
|
|
763
|
+
const inlineTag = TELEGRAM_INLINE_TAGS.get(tagName);
|
|
764
|
+
if (inlineTag) return `<${inlineTag}>${renderChildren(node)}</${inlineTag}>`;
|
|
765
|
+
if (HEADING_TAG_PATTERN.test(tagName))
|
|
766
|
+
return withTrailingNewline(`<b>${renderChildren(node)}</b>`);
|
|
767
|
+
if (tagName === "li") return withTrailingNewline(`\u2022 ${renderChildren(node).trim()}`);
|
|
768
|
+
if (tagName === "ul" || tagName === "ol") return withTrailingNewline(renderChildren(node));
|
|
769
|
+
if (BLOCK_TAGS.has(tagName)) return withTrailingNewline(renderChildren(node));
|
|
770
|
+
return renderChildren(node);
|
|
771
|
+
}
|
|
772
|
+
function normalizeTelegramHtml(html) {
|
|
773
|
+
return parseFragment(html).childNodes.map(renderNode).join("").trim();
|
|
774
|
+
}
|
|
775
|
+
function telegramHtmlToPlainText(html) {
|
|
776
|
+
return parseFragment(normalizeTelegramHtml(html)).childNodes.map(collectText).join("").trim();
|
|
777
|
+
}
|
|
778
|
+
function takeEncodedChunk(value, maxChars, encodeChar) {
|
|
779
|
+
let encoded = "";
|
|
780
|
+
let rawEnd = 0;
|
|
781
|
+
let lastBoundary = null;
|
|
782
|
+
for (const char of value) {
|
|
783
|
+
const encodedChar = encodeChar(char);
|
|
784
|
+
if (encoded.length + encodedChar.length > maxChars) break;
|
|
785
|
+
encoded += encodedChar;
|
|
786
|
+
rawEnd += char.length;
|
|
787
|
+
if (/\s/u.test(char)) lastBoundary = { rawEnd, encodedEnd: encoded.length };
|
|
788
|
+
}
|
|
789
|
+
if (rawEnd === value.length) return { chunk: encoded, remaining: "" };
|
|
790
|
+
if (rawEnd === 0) {
|
|
791
|
+
const [firstChar = ""] = value;
|
|
792
|
+
return { chunk: encodeChar(firstChar), remaining: value.slice(firstChar.length) };
|
|
793
|
+
}
|
|
794
|
+
const split = lastBoundary && lastBoundary.encodedEnd >= Math.floor(maxChars * 0.5) ? lastBoundary : { rawEnd, encodedEnd: encoded.length };
|
|
795
|
+
return { chunk: encoded.slice(0, split.encodedEnd), remaining: value.slice(split.rawEnd) };
|
|
796
|
+
}
|
|
797
|
+
function splitEncodedText(value, maxChars, encodeChar) {
|
|
798
|
+
let remaining = normalizeLineEndings(value);
|
|
799
|
+
if (!remaining) return [];
|
|
800
|
+
const chunks = [];
|
|
801
|
+
const max = clampMaxChars(maxChars);
|
|
802
|
+
while (remaining) {
|
|
803
|
+
const next = takeEncodedChunk(remaining, max, encodeChar);
|
|
804
|
+
chunks.push(next.chunk);
|
|
805
|
+
remaining = next.remaining;
|
|
806
|
+
}
|
|
807
|
+
return chunks;
|
|
808
|
+
}
|
|
809
|
+
function splitPlainTelegramText(value, maxChars = DEFAULT_TELEGRAM_SOFT_LIMIT) {
|
|
810
|
+
return splitEncodedText(value, maxChars, (char) => char);
|
|
811
|
+
}
|
|
812
|
+
function splitTelegramHtml(value, maxChars = DEFAULT_TELEGRAM_SOFT_LIMIT) {
|
|
813
|
+
const normalized = normalizeLineEndings(value);
|
|
814
|
+
if (!normalized) return [];
|
|
815
|
+
const max = clampMaxChars(maxChars);
|
|
816
|
+
if (normalized.length <= max) return [normalized];
|
|
817
|
+
const safeHtml = normalizeTelegramHtml(normalized);
|
|
818
|
+
return safeHtml.length <= max ? [safeHtml] : splitEncodedText(telegramHtmlToPlainText(safeHtml), max, escapeTelegramHtml);
|
|
819
|
+
}
|
|
820
|
+
function renderMarkdownToTelegramHtml(markdownText) {
|
|
821
|
+
const normalized = normalizeLineEndings(markdownText);
|
|
822
|
+
return normalized ? normalizeTelegramHtml(markdown.render(normalized)) : "";
|
|
823
|
+
}
|
|
824
|
+
function resultVisual(token, context) {
|
|
825
|
+
if (token.type === "fence" && token.info.trim().split(/\s+/, 1)[0]?.toLowerCase() === "mermaid") {
|
|
826
|
+
return { kind: "mermaid", source: token.content.trim() };
|
|
827
|
+
}
|
|
828
|
+
if (token.type !== "image") return null;
|
|
829
|
+
const image = parseManagedResultImagePath(token.attrGet("src") ?? "");
|
|
830
|
+
if (!image || image.instanceId !== context.instanceId || image.turnRecordId !== context.turnRecordId)
|
|
831
|
+
return null;
|
|
832
|
+
return { kind: "image", imageId: image.imageId, alt: token.content };
|
|
833
|
+
}
|
|
834
|
+
function renderResultMarkdownForTelegram(input) {
|
|
835
|
+
const normalized = normalizeLineEndings(input.markdown);
|
|
836
|
+
if (!normalized) return [];
|
|
837
|
+
const context = { instanceId: input.instanceId, turnRecordId: input.turnRecordId };
|
|
838
|
+
const tokens = markdown.parse(normalized, {});
|
|
839
|
+
const parts = [];
|
|
840
|
+
let textTokens = [];
|
|
841
|
+
const flushHtml = () => {
|
|
842
|
+
const html = normalizeTelegramHtml(markdown.renderer.render(textTokens, markdown.options, {}));
|
|
843
|
+
if (html) parts.push({ kind: "html", html });
|
|
844
|
+
textTokens = [];
|
|
845
|
+
};
|
|
846
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
847
|
+
const token = tokens[index];
|
|
848
|
+
if (!token) continue;
|
|
849
|
+
let visual = token.level === 0 ? resultVisual(token, context) : null;
|
|
850
|
+
let consumed = 0;
|
|
851
|
+
const inline = tokens[index + 1];
|
|
852
|
+
if (!visual && token.level === 0 && token.type === "paragraph_open" && inline?.type === "inline" && inline.children?.length === 1 && tokens[index + 2]?.type === "paragraph_close") {
|
|
853
|
+
visual = resultVisual(inline.children[0], context);
|
|
854
|
+
if (visual?.kind === "image") consumed = 2;
|
|
855
|
+
else visual = null;
|
|
856
|
+
}
|
|
857
|
+
if (!visual) {
|
|
858
|
+
textTokens.push(token);
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
flushHtml();
|
|
862
|
+
parts.push(visual);
|
|
863
|
+
index += consumed;
|
|
864
|
+
}
|
|
865
|
+
flushHtml();
|
|
866
|
+
return parts;
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// src/mermaid-image.ts
|
|
870
|
+
import { Worker } from "worker_threads";
|
|
871
|
+
var MAX_MERMAID_SOURCE_CHARS = 2e4;
|
|
872
|
+
var MAX_MERMAID_SOURCE_LINES = 500;
|
|
873
|
+
var MERMAID_RENDER_TIMEOUT_MS = 8e3;
|
|
874
|
+
var RENDER_WORKER_SOURCE = String.raw`
|
|
875
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
876
|
+
const MAX_SVG_BYTES = 2 * 1024 * 1024;
|
|
877
|
+
const MAX_SVG_ELEMENTS = 2_000;
|
|
878
|
+
const TARGET_WIDTH = 1_600;
|
|
879
|
+
const MAX_TARGET_HEIGHT = 5_000;
|
|
880
|
+
const MAX_TARGET_PIXELS = 8_000_000;
|
|
881
|
+
const MAX_PNG_BYTES = 10 * 1024 * 1024;
|
|
882
|
+
|
|
883
|
+
function fail(message) { throw new Error(message); }
|
|
884
|
+
function svgDimensions(svg) {
|
|
885
|
+
const match = /<svg[^>]*\bviewBox=["']\s*[-+\d.e]+\s+[-+\d.e]+\s+([-+\d.e]+)\s+([-+\d.e]+)\s*["']/i.exec(svg);
|
|
886
|
+
if (!match) fail("Rendered Mermaid SVG has no bounded viewBox");
|
|
887
|
+
const width = Number(match[1]);
|
|
888
|
+
const height = Number(match[2]);
|
|
889
|
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
|
890
|
+
fail("Rendered Mermaid SVG dimensions are invalid");
|
|
891
|
+
}
|
|
892
|
+
return { width, height };
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
(async () => {
|
|
896
|
+
const [{ renderMermaidSVG, THEMES }, { default: sharp }] = await Promise.all([
|
|
897
|
+
import("beautiful-mermaid"),
|
|
898
|
+
import("sharp"),
|
|
899
|
+
]);
|
|
900
|
+
const svg = renderMermaidSVG(workerData.source, THEMES["zinc-light"]);
|
|
901
|
+
if (Buffer.byteLength(svg, "utf8") > MAX_SVG_BYTES) fail("Rendered Mermaid SVG is too large");
|
|
902
|
+
const elementCount = (svg.match(/<[a-zA-Z][^>]*>/g) || []).length;
|
|
903
|
+
if (elementCount > MAX_SVG_ELEMENTS) fail("Rendered Mermaid diagram is too complex");
|
|
904
|
+
const dimensions = svgDimensions(svg);
|
|
905
|
+
const targetHeight = Math.ceil((dimensions.height / dimensions.width) * TARGET_WIDTH);
|
|
906
|
+
if (targetHeight > MAX_TARGET_HEIGHT || TARGET_WIDTH * targetHeight > MAX_TARGET_PIXELS) {
|
|
907
|
+
fail("Rendered Mermaid diagram dimensions are too large");
|
|
908
|
+
}
|
|
909
|
+
const png = await sharp(Buffer.from(svg), { limitInputPixels: MAX_TARGET_PIXELS })
|
|
910
|
+
.resize({ width: TARGET_WIDTH, height: targetHeight, fit: "fill" })
|
|
911
|
+
.flatten({ background: "#ffffff" })
|
|
912
|
+
.png()
|
|
913
|
+
.toBuffer();
|
|
914
|
+
if (png.byteLength > MAX_PNG_BYTES) fail("Rendered Mermaid PNG is too large");
|
|
915
|
+
const bytes = Uint8Array.from(png);
|
|
916
|
+
parentPort.postMessage({ ok: true, bytes }, [bytes.buffer]);
|
|
917
|
+
})().catch((error) => {
|
|
918
|
+
parentPort.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
919
|
+
});
|
|
920
|
+
`;
|
|
921
|
+
async function renderMermaidPng(source) {
|
|
922
|
+
const normalized = source.trim();
|
|
923
|
+
if (!normalized) throw new Error("Mermaid source is empty");
|
|
924
|
+
if (normalized.length > MAX_MERMAID_SOURCE_CHARS) {
|
|
925
|
+
throw new Error(`Mermaid source exceeds ${MAX_MERMAID_SOURCE_CHARS} characters`);
|
|
926
|
+
}
|
|
927
|
+
if (normalized.split("\n").length > MAX_MERMAID_SOURCE_LINES) {
|
|
928
|
+
throw new Error(`Mermaid source exceeds ${MAX_MERMAID_SOURCE_LINES} lines`);
|
|
929
|
+
}
|
|
930
|
+
return new Promise((resolve, reject) => {
|
|
931
|
+
const worker = new Worker(RENDER_WORKER_SOURCE, {
|
|
932
|
+
eval: true,
|
|
933
|
+
workerData: { source: normalized },
|
|
934
|
+
resourceLimits: {
|
|
935
|
+
maxOldGenerationSizeMb: 96,
|
|
936
|
+
maxYoungGenerationSizeMb: 24,
|
|
937
|
+
stackSizeMb: 4
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
let settled = false;
|
|
941
|
+
const finish = (work) => {
|
|
942
|
+
if (settled) return;
|
|
943
|
+
settled = true;
|
|
944
|
+
clearTimeout(timer);
|
|
945
|
+
void worker.terminate();
|
|
946
|
+
work();
|
|
947
|
+
};
|
|
948
|
+
const timer = setTimeout(() => {
|
|
949
|
+
finish(() => reject(new Error("Mermaid rendering timed out")));
|
|
950
|
+
}, MERMAID_RENDER_TIMEOUT_MS);
|
|
951
|
+
worker.once("message", (message) => {
|
|
952
|
+
const result = message;
|
|
953
|
+
if (result.ok && result.bytes instanceof Uint8Array) {
|
|
954
|
+
finish(() => resolve(result.bytes));
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
finish(() => reject(new Error(result.error || "Mermaid rendering failed")));
|
|
958
|
+
});
|
|
959
|
+
worker.once("error", (error) => finish(() => reject(error)));
|
|
960
|
+
worker.once("exit", (code) => {
|
|
961
|
+
if (code !== 0) finish(() => reject(new Error(`Mermaid renderer exited with code ${code}`)));
|
|
962
|
+
});
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// src/process-feed.ts
|
|
967
|
+
import {
|
|
968
|
+
formatPathTypeLabel
|
|
969
|
+
} from "@leitwerk-dev/domain";
|
|
970
|
+
var MAX_SUBMITTED_FIELD_VALUE_CHARS = 500;
|
|
971
|
+
function formatTurnIdLabel(turnId) {
|
|
972
|
+
return turnId.split(/[_-]+/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join(" ");
|
|
973
|
+
}
|
|
974
|
+
function processLabel(process2) {
|
|
975
|
+
return process2.title?.trim() || process2.externalId?.trim() || process2.processId;
|
|
976
|
+
}
|
|
977
|
+
function actionLabel(action) {
|
|
978
|
+
return action.label.trim() || action.id;
|
|
979
|
+
}
|
|
980
|
+
function actionListLines(actions = [], recoveryActions = []) {
|
|
981
|
+
const labels = [
|
|
982
|
+
...actions.map(actionLabel),
|
|
983
|
+
...recoveryActions.map((label) => label.trim()).filter((label) => label.length > 0)
|
|
984
|
+
];
|
|
985
|
+
return labels.length > 0 ? ["Available actions:", ...labels.map((label) => `- ${escapeTelegramHtml(label)}`)] : [];
|
|
986
|
+
}
|
|
987
|
+
function stringifySubmittedFieldValue(value) {
|
|
988
|
+
if (typeof value === "string") return value.trim();
|
|
989
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
990
|
+
if (Array.isArray(value)) {
|
|
991
|
+
return value.map((entry) => stringifySubmittedFieldValue(entry)).filter((entry) => entry.length > 0).join(", ").trim();
|
|
992
|
+
}
|
|
993
|
+
return "";
|
|
994
|
+
}
|
|
995
|
+
function trimSubmittedValue(value) {
|
|
996
|
+
return value.length > MAX_SUBMITTED_FIELD_VALUE_CHARS ? `${value.slice(0, MAX_SUBMITTED_FIELD_VALUE_CHARS - 1)}\u2026` : value;
|
|
997
|
+
}
|
|
998
|
+
function submittedActionFields(action, values) {
|
|
999
|
+
const submittedFields = [];
|
|
1000
|
+
const seenFieldIds = /* @__PURE__ */ new Set();
|
|
1001
|
+
for (const field of action.form?.fields ?? []) {
|
|
1002
|
+
seenFieldIds.add(field.id);
|
|
1003
|
+
const value = stringifySubmittedFieldValue(values[field.id]);
|
|
1004
|
+
if (value) submittedFields.push({ label: field.label, value: trimSubmittedValue(value) });
|
|
1005
|
+
}
|
|
1006
|
+
for (const [fieldId, rawValue] of Object.entries(values)) {
|
|
1007
|
+
if (seenFieldIds.has(fieldId)) continue;
|
|
1008
|
+
const value = stringifySubmittedFieldValue(rawValue);
|
|
1009
|
+
if (value) submittedFields.push({ label: fieldId, value: trimSubmittedValue(value) });
|
|
1010
|
+
}
|
|
1011
|
+
return submittedFields;
|
|
1012
|
+
}
|
|
1013
|
+
function actionNextLine(action) {
|
|
1014
|
+
if (action.preview?.kind === "fixed_turn" && action.preview.turnId) {
|
|
1015
|
+
return `Next: running ${escapeTelegramHtml(action.preview.turnId)}; result will be posted here.`;
|
|
1016
|
+
}
|
|
1017
|
+
if (action.preview?.kind === "terminal" && action.preview.lifecycleStatus) {
|
|
1018
|
+
return `Next: process will become ${escapeTelegramHtml(action.preview.lifecycleStatus)}.`;
|
|
1019
|
+
}
|
|
1020
|
+
return "Next: the process will update shortly.";
|
|
1021
|
+
}
|
|
1022
|
+
function buildProcessCreatedMessage(input) {
|
|
1023
|
+
const url = `${input.serverBaseUrl.replace(/\/$/, "")}/processes/${input.process.id}`;
|
|
1024
|
+
return [
|
|
1025
|
+
"\u{1F680} <b>Process created</b>",
|
|
1026
|
+
`Title: ${escapeTelegramHtml(processLabel(input.process))}`,
|
|
1027
|
+
`Status: ${escapeTelegramHtml(input.process.lifecycleStatus)}`,
|
|
1028
|
+
`Web UI: <a href="${escapeTelegramAttribute(url)}">open process</a>`
|
|
1029
|
+
].join("\n");
|
|
1030
|
+
}
|
|
1031
|
+
function buildTurnStartedMessage(turnRecord, options) {
|
|
1032
|
+
const description = options?.turnDescription?.trim() || turnRecord.turnId;
|
|
1033
|
+
const pathLabel = formatPathTypeLabel(turnRecord.pathType);
|
|
1034
|
+
const base = `\u25B6\uFE0F <b>Started</b>: ${escapeTelegramHtml(description)} \u2014 ${escapeTelegramHtml(pathLabel)}`;
|
|
1035
|
+
const modelLabel = options?.modelLabel?.trim() ?? null;
|
|
1036
|
+
return modelLabel ? `${base} (model: ${escapeTelegramHtml(modelLabel)})` : base;
|
|
1037
|
+
}
|
|
1038
|
+
function buildLeafOutcomeMessage(input) {
|
|
1039
|
+
const markdown2 = input.snapshot.fallbackMarkdown?.trim();
|
|
1040
|
+
if (!markdown2) {
|
|
1041
|
+
return "\u2705 <b>Result available</b>\n\nOpen the Web UI for the full result.";
|
|
1042
|
+
}
|
|
1043
|
+
const body = input.markdownHtml ?? renderMarkdownToTelegramHtml(markdown2);
|
|
1044
|
+
return body ? `\u2705 <b>Result</b>
|
|
1045
|
+
|
|
1046
|
+
${body}` : "\u2705 <b>Result</b>";
|
|
1047
|
+
}
|
|
1048
|
+
function buildTurnOutcomeMessage(input) {
|
|
1049
|
+
const pathSuffix = input.pathType ? ` (${escapeTelegramHtml(formatPathTypeLabel(input.pathType))})` : "";
|
|
1050
|
+
const heading = `\u2705 <b>Result</b>: ${escapeTelegramHtml(`${input.turnId}.${input.outcome}`)}${pathSuffix}`;
|
|
1051
|
+
const body = input.markdownHtml ?? renderMarkdownToTelegramHtml(input.markdown.trim());
|
|
1052
|
+
return body ? `${heading}
|
|
1053
|
+
|
|
1054
|
+
${body}` : heading;
|
|
1055
|
+
}
|
|
1056
|
+
function buildLifecycleMessage(input) {
|
|
1057
|
+
if (input.status === "completed") {
|
|
1058
|
+
return `\u{1F3C1} <b>Completed</b>: ${escapeTelegramHtml(processLabel(input.process))}`;
|
|
1059
|
+
}
|
|
1060
|
+
if (input.status === "aborted") {
|
|
1061
|
+
return `\u{1F6D1} <b>Aborted</b>: ${escapeTelegramHtml(processLabel(input.process))}`;
|
|
1062
|
+
}
|
|
1063
|
+
if (input.status === "error") {
|
|
1064
|
+
return `\u26A0\uFE0F <b>Process needs recovery</b>: ${escapeTelegramHtml(processLabel(input.process))}`;
|
|
1065
|
+
}
|
|
1066
|
+
return null;
|
|
1067
|
+
}
|
|
1068
|
+
function buildActionsPromptMessage(input) {
|
|
1069
|
+
const rawTurn = input.currentTurnDescription?.trim() || input.process.selectedTurnId;
|
|
1070
|
+
const turnDisplay = rawTurn ? formatTurnIdLabel(rawTurn) : "none";
|
|
1071
|
+
const turnLine = `Turn: ${escapeTelegramHtml(turnDisplay)}`;
|
|
1072
|
+
const pathLine = input.currentTurnPathType ? `Path: ${escapeTelegramHtml(formatPathTypeLabel(input.currentTurnPathType))}` : null;
|
|
1073
|
+
return [
|
|
1074
|
+
"\u23F8 <b>Action required</b>",
|
|
1075
|
+
"",
|
|
1076
|
+
`${escapeTelegramHtml(processLabel(input.process))}`,
|
|
1077
|
+
`Status: ${escapeTelegramHtml(input.process.lifecycleStatus)}`,
|
|
1078
|
+
turnLine,
|
|
1079
|
+
...pathLine ? [pathLine] : [],
|
|
1080
|
+
...actionListLines(input.actions, input.recoveryActions)
|
|
1081
|
+
].join("\n");
|
|
1082
|
+
}
|
|
1083
|
+
function buildStatusMessage(input) {
|
|
1084
|
+
const rawTurn = input.currentTurnDescription?.trim() || input.process.selectedTurnId;
|
|
1085
|
+
const turnDisplay = rawTurn ? formatTurnIdLabel(rawTurn) : "none";
|
|
1086
|
+
const turnLine = `Turn: ${escapeTelegramHtml(turnDisplay)}`;
|
|
1087
|
+
const pathLine = input.currentTurnPathType ? `Path: ${escapeTelegramHtml(formatPathTypeLabel(input.currentTurnPathType))}` : null;
|
|
1088
|
+
const actionLines = actionListLines(input.actions);
|
|
1089
|
+
return [
|
|
1090
|
+
`<b>${escapeTelegramHtml(processLabel(input.process))}</b>`,
|
|
1091
|
+
`Status: ${escapeTelegramHtml(input.process.lifecycleStatus)}`,
|
|
1092
|
+
turnLine,
|
|
1093
|
+
...pathLine ? [pathLine] : [],
|
|
1094
|
+
...actionLines.length > 0 ? ["", ...actionLines] : []
|
|
1095
|
+
].join("\n");
|
|
1096
|
+
}
|
|
1097
|
+
function buildActionSubmittedMessage(input) {
|
|
1098
|
+
const fields = submittedActionFields(input.action, input.values);
|
|
1099
|
+
return [
|
|
1100
|
+
`\u2705 <b>Submitted action</b>: ${escapeTelegramHtml(actionLabel(input.action))}`,
|
|
1101
|
+
...fields.length > 0 ? [
|
|
1102
|
+
"Input:",
|
|
1103
|
+
...fields.map((field) => `- ${escapeTelegramHtml(field.label)}: ${escapeTelegramHtml(field.value)}`)
|
|
1104
|
+
] : ["Input: none"],
|
|
1105
|
+
actionNextLine(input.action)
|
|
1106
|
+
].join("\n");
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// src/process-thread-store.ts
|
|
1110
|
+
var TELEGRAM_THREAD_LINKED_EVENT = "telegram.thread_linked";
|
|
1111
|
+
function readThreadFromEvent(event) {
|
|
1112
|
+
const data = event.data;
|
|
1113
|
+
return event.eventType === TELEGRAM_THREAD_LINKED_EVENT && data.mode === "forum_topic" && typeof data.chatId === "string" && typeof data.messageThreadId === "number" && typeof data.topicName === "string" ? {
|
|
1114
|
+
mode: "forum_topic",
|
|
1115
|
+
chatId: data.chatId,
|
|
1116
|
+
messageThreadId: data.messageThreadId,
|
|
1117
|
+
topicName: data.topicName
|
|
1118
|
+
} : null;
|
|
1119
|
+
}
|
|
1120
|
+
function newestFirst(events) {
|
|
1121
|
+
return [...events].sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
|
1122
|
+
}
|
|
1123
|
+
function threadKey(chatId, messageThreadId) {
|
|
1124
|
+
return `${chatId}:${messageThreadId ?? 0}`;
|
|
1125
|
+
}
|
|
1126
|
+
var ProcessThreadStore = class {
|
|
1127
|
+
constructor(deps) {
|
|
1128
|
+
this.deps = deps;
|
|
1129
|
+
}
|
|
1130
|
+
deps;
|
|
1131
|
+
byInstanceId = /* @__PURE__ */ new Map();
|
|
1132
|
+
byThreadKey = /* @__PURE__ */ new Map();
|
|
1133
|
+
rebuildFromEvents() {
|
|
1134
|
+
this.byInstanceId.clear();
|
|
1135
|
+
this.byThreadKey.clear();
|
|
1136
|
+
const mappedInstanceIds = [];
|
|
1137
|
+
for (const process2 of this.deps.processes.listAll()) {
|
|
1138
|
+
const linked = this.listThreadEvents(process2.id).map(readThreadFromEvent).find(Boolean);
|
|
1139
|
+
if (linked) {
|
|
1140
|
+
this.remember(process2.id, linked);
|
|
1141
|
+
mappedInstanceIds.push(process2.id);
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return mappedInstanceIds;
|
|
1145
|
+
}
|
|
1146
|
+
getByInstanceId(instanceId) {
|
|
1147
|
+
return this.byInstanceId.get(instanceId) ?? null;
|
|
1148
|
+
}
|
|
1149
|
+
getInstanceIdForThread(chatId, messageThreadId) {
|
|
1150
|
+
return this.byThreadKey.get(threadKey(chatId, messageThreadId)) ?? null;
|
|
1151
|
+
}
|
|
1152
|
+
record(process2, thread) {
|
|
1153
|
+
this.deps.events.create({
|
|
1154
|
+
instanceId: process2.id,
|
|
1155
|
+
eventType: TELEGRAM_THREAD_LINKED_EVENT,
|
|
1156
|
+
data: { ...thread }
|
|
1157
|
+
});
|
|
1158
|
+
this.remember(process2.id, thread);
|
|
1159
|
+
}
|
|
1160
|
+
listThreadEvents(instanceId) {
|
|
1161
|
+
const events = this.deps.events;
|
|
1162
|
+
if (events.listByInstanceEventTypes) {
|
|
1163
|
+
return newestFirst(
|
|
1164
|
+
events.listByInstanceEventTypes(instanceId, [TELEGRAM_THREAD_LINKED_EVENT], 1e4)
|
|
1165
|
+
);
|
|
1166
|
+
}
|
|
1167
|
+
return newestFirst(
|
|
1168
|
+
events.listByInstance(instanceId, Number.MAX_SAFE_INTEGER).filter((event) => event.eventType === TELEGRAM_THREAD_LINKED_EVENT)
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
remember(instanceId, thread) {
|
|
1172
|
+
const previous = this.byInstanceId.get(instanceId);
|
|
1173
|
+
if (previous) this.byThreadKey.delete(threadKey(previous.chatId, previous.messageThreadId));
|
|
1174
|
+
this.byInstanceId.set(instanceId, thread);
|
|
1175
|
+
this.byThreadKey.set(threadKey(thread.chatId, thread.messageThreadId), instanceId);
|
|
1176
|
+
}
|
|
1177
|
+
};
|
|
1178
|
+
|
|
1179
|
+
// src/topic-title.ts
|
|
1180
|
+
var MAX_TOPIC_TITLE_LENGTH = 128;
|
|
1181
|
+
function flatten(value) {
|
|
1182
|
+
return value.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
|
|
1183
|
+
}
|
|
1184
|
+
function truncate(value, max) {
|
|
1185
|
+
if (value.length <= max) return value;
|
|
1186
|
+
return `${value.slice(0, Math.max(1, max - 1)).trimEnd()}\u2026`;
|
|
1187
|
+
}
|
|
1188
|
+
function getProcessTopicBaseTitle(process2) {
|
|
1189
|
+
return flatten(process2.title ?? "") || flatten(process2.externalId ?? "") || flatten(process2.processId) || process2.id;
|
|
1190
|
+
}
|
|
1191
|
+
function buildTopicTitle(input) {
|
|
1192
|
+
const shortId = input.process.id.slice(-8);
|
|
1193
|
+
const title = getProcessTopicBaseTitle(input.process);
|
|
1194
|
+
const rendered = input.template.replaceAll("{title}", title).replaceAll("{shortId}", shortId).replaceAll("{processId}", input.process.processId).replaceAll("{externalId}", input.process.externalId ?? "");
|
|
1195
|
+
return truncate(flatten(rendered) || `Process ${shortId}`, MAX_TOPIC_TITLE_LENGTH);
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// src/bridge.ts
|
|
1199
|
+
var LAUNCH_CALLBACK_PREFIX = "launch:";
|
|
1200
|
+
var LAUNCH_SESSION_TTL_MS = 20 * 60 * 1e3;
|
|
1201
|
+
var MAX_LAUNCHER_BUTTONS = 30;
|
|
1202
|
+
var MAX_FIELD_OPTION_BUTTONS = 20;
|
|
1203
|
+
var MAX_MODEL_PROFILE_BUTTONS = 20;
|
|
1204
|
+
var CONTINUE_PROMPT = "Send an optional continuation instruction, or send /skip to continue with the default prompt.";
|
|
1205
|
+
function commandName(text) {
|
|
1206
|
+
return /^\/(\w+)(?:@\w+)?(?:\s|$)/.exec(text.trim())?.[1]?.toLowerCase() ?? null;
|
|
1207
|
+
}
|
|
1208
|
+
function commandArgs(text) {
|
|
1209
|
+
return text.trim().replace(/^\/\w+(?:@\w+)?\s*/, "").trim();
|
|
1210
|
+
}
|
|
1211
|
+
function messageTarget(chatId, messageThreadId) {
|
|
1212
|
+
return { chatId, ...messageThreadId !== void 0 ? { messageThreadId } : {} };
|
|
1213
|
+
}
|
|
1214
|
+
function launchSessionKey(input) {
|
|
1215
|
+
return typeof input.from?.id === "number" ? `${input.chatId}:${input.messageThreadId ?? 0}:${input.from.id}` : null;
|
|
1216
|
+
}
|
|
1217
|
+
function parseCallbackCommand(data) {
|
|
1218
|
+
const separator = data.indexOf(":");
|
|
1219
|
+
if (separator < 0) return null;
|
|
1220
|
+
const prefix = data.slice(0, separator);
|
|
1221
|
+
const payload = data.slice(separator + 1);
|
|
1222
|
+
if (prefix === "r" || prefix === "c") {
|
|
1223
|
+
return payload ? { kind: prefix === "r" ? "retry" : "continue", instanceId: payload } : null;
|
|
1224
|
+
}
|
|
1225
|
+
if (prefix === "a") {
|
|
1226
|
+
const separator2 = payload.indexOf(":");
|
|
1227
|
+
if (separator2 <= 0 || separator2 === payload.length - 1) return null;
|
|
1228
|
+
return {
|
|
1229
|
+
kind: "process_action",
|
|
1230
|
+
instanceId: payload.slice(0, separator2),
|
|
1231
|
+
actionId: payload.slice(separator2 + 1)
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
const [instanceId, sessionId, ...rest] = payload.split(":");
|
|
1235
|
+
if (!instanceId || !sessionId) return null;
|
|
1236
|
+
switch (prefix) {
|
|
1237
|
+
case "fs":
|
|
1238
|
+
return { kind: "action_form_skip", instanceId, sessionId, fieldId: rest.join(":") };
|
|
1239
|
+
case "amk":
|
|
1240
|
+
return { kind: "action_model_skip", instanceId, sessionId };
|
|
1241
|
+
case "ams": {
|
|
1242
|
+
const profileIndex = Number(rest.join(":"));
|
|
1243
|
+
return Number.isInteger(profileIndex) && profileIndex >= 1 ? { kind: "action_model_select", instanceId, sessionId, profileIndex } : null;
|
|
1244
|
+
}
|
|
1245
|
+
default:
|
|
1246
|
+
return null;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
function resolveProfileByTextOrIndex(text, profiles) {
|
|
1250
|
+
const byIdOrLabel = profiles.find(
|
|
1251
|
+
(p) => p.id === text || p.label.toLowerCase() === text.toLowerCase()
|
|
1252
|
+
);
|
|
1253
|
+
if (byIdOrLabel) return byIdOrLabel;
|
|
1254
|
+
const index = Number(text);
|
|
1255
|
+
if (Number.isInteger(index) && index >= 1 && index <= profiles.length) {
|
|
1256
|
+
return profiles[index - 1] ?? null;
|
|
1257
|
+
}
|
|
1258
|
+
return null;
|
|
1259
|
+
}
|
|
1260
|
+
function resolveModelProfileFromSession(session, profileIndex) {
|
|
1261
|
+
return session?.kind === "action_model" || session?.kind === "recovery_model" ? session.profiles?.[profileIndex - 1] ?? null : null;
|
|
1262
|
+
}
|
|
1263
|
+
function processCanAcceptFreeText(process2) {
|
|
1264
|
+
return !["completed", "aborted", "error"].includes(process2.lifecycleStatus);
|
|
1265
|
+
}
|
|
1266
|
+
function processIsFinished(process2) {
|
|
1267
|
+
return process2.lifecycleStatus === "completed" || process2.lifecycleStatus === "aborted";
|
|
1268
|
+
}
|
|
1269
|
+
function resultTurnRecordKey(instanceId, turnRecordId) {
|
|
1270
|
+
return `${instanceId}:${turnRecordId}`;
|
|
1271
|
+
}
|
|
1272
|
+
function recoveryActionLabels(process2) {
|
|
1273
|
+
if (process2.lifecycleStatus !== "error" || !process2.currentExecution) return [];
|
|
1274
|
+
return ["Retry", ...continuableFailedTurnRecordId(process2) ? ["Continue"] : []];
|
|
1275
|
+
}
|
|
1276
|
+
function readActionPreview(action) {
|
|
1277
|
+
const preview = action.preview;
|
|
1278
|
+
if (!isRecord(preview)) return null;
|
|
1279
|
+
return {
|
|
1280
|
+
...typeof preview.kind === "string" ? { kind: preview.kind } : {},
|
|
1281
|
+
...typeof preview.turnId === "string" ? { turnId: preview.turnId } : {},
|
|
1282
|
+
...typeof preview.lifecycleStatus === "string" ? { lifecycleStatus: preview.lifecycleStatus } : {}
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
function shouldDeferActionPromptUntilTurnTerminalEvent(changedFields) {
|
|
1286
|
+
return changedFields.includes("currentExecution");
|
|
1287
|
+
}
|
|
1288
|
+
function shouldDeferCompletedLifecycleUntilTurnOutcome(input) {
|
|
1289
|
+
return input.process.lifecycleStatus === "completed" && input.changedFields.includes("currentExecution");
|
|
1290
|
+
}
|
|
1291
|
+
function readClaimedLaunchThread(process2, expectedChatId) {
|
|
1292
|
+
const telegram = isRecord(process2.metadata?.telegram) ? process2.metadata.telegram : null;
|
|
1293
|
+
const thread = isRecord(telegram?.launchThread) ? telegram.launchThread : null;
|
|
1294
|
+
return thread?.mode === "forum_topic" && thread.chatId === expectedChatId && typeof thread.messageThreadId === "number" ? { mode: "forum_topic", chatId: thread.chatId, messageThreadId: thread.messageThreadId } : null;
|
|
1295
|
+
}
|
|
1296
|
+
function createActionFormSessionId() {
|
|
1297
|
+
return randomBytes(4).toString("hex");
|
|
1298
|
+
}
|
|
1299
|
+
var TelegramBridge = class {
|
|
1300
|
+
constructor(input) {
|
|
1301
|
+
this.input = input;
|
|
1302
|
+
this.store = new ProcessThreadStore(input.deps);
|
|
1303
|
+
this.processModelSelection = input.deps.processModelSelection ?? null;
|
|
1304
|
+
input.client.onText((update) => this.handleText(update));
|
|
1305
|
+
input.client.onCallback((update) => this.handleCallback(update));
|
|
1306
|
+
input.client.onForumTopicCreated((update) => this.handleForumTopicCreated(update));
|
|
1307
|
+
input.client.onForumTopicClosed((update) => this.handleForumTopicClosed(update));
|
|
1308
|
+
}
|
|
1309
|
+
input;
|
|
1310
|
+
store;
|
|
1311
|
+
sessions = /* @__PURE__ */ new Map();
|
|
1312
|
+
launchSessions = /* @__PURE__ */ new Map();
|
|
1313
|
+
launchCallbacks = /* @__PURE__ */ new Map();
|
|
1314
|
+
nextLaunchCallbackId = 1;
|
|
1315
|
+
processModelSelection;
|
|
1316
|
+
threadEligibleInstanceIds = /* @__PURE__ */ new Set();
|
|
1317
|
+
introSentInstanceIds = /* @__PURE__ */ new Set();
|
|
1318
|
+
closedThreadKeys = /* @__PURE__ */ new Set();
|
|
1319
|
+
sentResultTurnRecordKeys = /* @__PURE__ */ new Set();
|
|
1320
|
+
deferredCompletedLifecycleProcesses = /* @__PURE__ */ new Map();
|
|
1321
|
+
queues = /* @__PURE__ */ new Map();
|
|
1322
|
+
lastTurnInfo = /* @__PURE__ */ new Map();
|
|
1323
|
+
async start() {
|
|
1324
|
+
for (const instanceId of this.store.rebuildFromEvents()) {
|
|
1325
|
+
this.threadEligibleInstanceIds.add(instanceId);
|
|
1326
|
+
this.introSentInstanceIds.add(instanceId);
|
|
1327
|
+
}
|
|
1328
|
+
this.seedLastTurnInfoFromEvents();
|
|
1329
|
+
await this.input.client.start();
|
|
1330
|
+
for (const request of this.input.deps.processQuestions?.listOpen() ?? []) {
|
|
1331
|
+
await this.onQuestionRequested({ instanceId: request.instanceId, request });
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* After a server restart the in-memory lastTurnInfo map is empty.
|
|
1336
|
+
* Rebuild it from the most recent turn_started event for every non-terminal
|
|
1337
|
+
* process that already has a Telegram thread, so that /status and actions
|
|
1338
|
+
* prompts show the correct path label without waiting for the next turn.
|
|
1339
|
+
*/
|
|
1340
|
+
seedLastTurnInfoFromEvents() {
|
|
1341
|
+
for (const process2 of this.input.deps.processes.listAll()) {
|
|
1342
|
+
if (["completed", "aborted"].includes(process2.lifecycleStatus)) continue;
|
|
1343
|
+
if (!this.store.getByInstanceId(process2.id)) continue;
|
|
1344
|
+
if (this.lastTurnInfo.has(process2.id)) continue;
|
|
1345
|
+
const events = this.input.deps.events.listByInstance(process2.id, 50);
|
|
1346
|
+
const turnStartedEvent = events.find((e) => e.eventType === "turn_started");
|
|
1347
|
+
if (!turnStartedEvent) continue;
|
|
1348
|
+
const pathType = turnStartedEvent.data.pathType;
|
|
1349
|
+
const turnId = turnStartedEvent.data.turnId;
|
|
1350
|
+
if (pathType && turnId) {
|
|
1351
|
+
this.lastTurnInfo.set(process2.id, { pathType, turnId });
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
async stop() {
|
|
1356
|
+
await this.input.client.stop();
|
|
1357
|
+
}
|
|
1358
|
+
register(events) {
|
|
1359
|
+
const on = (event, handler) => events.on(event, (payload) => void this.enqueue(payload.instanceId, () => handler(payload)));
|
|
1360
|
+
on("process_created", (payload) => this.onProcessCreated(payload));
|
|
1361
|
+
on("process_updated", (payload) => this.onProcessUpdated(payload));
|
|
1362
|
+
on("turn_started", (payload) => this.onTurnStarted(payload.turnRecord));
|
|
1363
|
+
on("turn_failed", (payload) => this.onTurnFailed(payload));
|
|
1364
|
+
on("leaf_outcome_captured", (payload) => this.onLeafOutcome(payload.snapshot));
|
|
1365
|
+
on("question_requested", (payload) => this.onQuestionRequested(payload));
|
|
1366
|
+
on("turn_outcome", (payload) => this.onTurnOutcome(payload));
|
|
1367
|
+
}
|
|
1368
|
+
enqueue(instanceId, task) {
|
|
1369
|
+
const previous = this.queues.get(instanceId) ?? Promise.resolve();
|
|
1370
|
+
const next = previous.catch(() => void 0).then(task).catch((error) => this.logError(error, "Telegram bridge task failed"));
|
|
1371
|
+
const stored = next.finally(() => {
|
|
1372
|
+
if (this.queues.get(instanceId) === stored) this.queues.delete(instanceId);
|
|
1373
|
+
});
|
|
1374
|
+
this.queues.set(instanceId, stored);
|
|
1375
|
+
return stored;
|
|
1376
|
+
}
|
|
1377
|
+
async onProcessCreated(payload) {
|
|
1378
|
+
this.threadEligibleInstanceIds.add(payload.process.id);
|
|
1379
|
+
const thread = await this.ensureThread(payload.process);
|
|
1380
|
+
if (!thread) return;
|
|
1381
|
+
await this.sendProcessIntro(thread, payload.process);
|
|
1382
|
+
if (processIsFinished(payload.process)) {
|
|
1383
|
+
await this.closeThread(thread);
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
if (["waiting", "error"].includes(payload.process.lifecycleStatus)) {
|
|
1387
|
+
await this.sendActionsForProcess(payload.process);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
async onProcessUpdated(payload) {
|
|
1391
|
+
const thread = await this.getThread(payload.process);
|
|
1392
|
+
if (!thread) return;
|
|
1393
|
+
if (payload.changedFields.includes("title")) {
|
|
1394
|
+
await this.syncThreadTitle(thread, payload.process);
|
|
1395
|
+
}
|
|
1396
|
+
const deferCompletedLifecycle = shouldDeferCompletedLifecycleUntilTurnOutcome({
|
|
1397
|
+
process: payload.process,
|
|
1398
|
+
changedFields: payload.changedFields
|
|
1399
|
+
});
|
|
1400
|
+
if (deferCompletedLifecycle) {
|
|
1401
|
+
this.deferredCompletedLifecycleProcesses.set(payload.process.id, payload.process);
|
|
1402
|
+
} else if (payload.changedFields.includes("lifecycleStatus")) {
|
|
1403
|
+
this.deferredCompletedLifecycleProcesses.delete(payload.process.id);
|
|
1404
|
+
const lifecycleMessage = buildLifecycleMessage({
|
|
1405
|
+
process: payload.process,
|
|
1406
|
+
status: payload.process.lifecycleStatus
|
|
1407
|
+
});
|
|
1408
|
+
if (lifecycleMessage) await this.sendHtml(thread, lifecycleMessage);
|
|
1409
|
+
if (processIsFinished(payload.process)) {
|
|
1410
|
+
await this.closeThread(thread);
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
if ((payload.process.lifecycleStatus === "waiting" || payload.process.lifecycleStatus === "error" || payload.changedFields.includes("selectedTurnId")) && !shouldDeferActionPromptUntilTurnTerminalEvent(payload.changedFields)) {
|
|
1415
|
+
await this.sendActionsForProcess(payload.process);
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
async onTurnStarted(turnRecord) {
|
|
1419
|
+
const thread = await this.getThread(turnRecord.instanceId);
|
|
1420
|
+
if (!thread) return;
|
|
1421
|
+
const modelLabel = this.resolveTurnModelLabel(turnRecord);
|
|
1422
|
+
const turnDescription = formatTurnIdLabel(turnRecord.turnId);
|
|
1423
|
+
this.lastTurnInfo.set(turnRecord.instanceId, {
|
|
1424
|
+
pathType: turnRecord.pathType,
|
|
1425
|
+
turnId: turnRecord.turnId
|
|
1426
|
+
});
|
|
1427
|
+
await this.sendHtml(
|
|
1428
|
+
thread,
|
|
1429
|
+
buildTurnStartedMessage(turnRecord, { turnDescription, modelLabel })
|
|
1430
|
+
);
|
|
1431
|
+
}
|
|
1432
|
+
async onQuestionRequested(payload) {
|
|
1433
|
+
const thread = await this.getThread(payload.instanceId);
|
|
1434
|
+
if (!thread) return;
|
|
1435
|
+
const key = threadKey(thread.chatId, thread.messageThreadId);
|
|
1436
|
+
const existing = this.sessions.get(key);
|
|
1437
|
+
if (existing?.kind === "question" && existing.request.id === payload.request.id) return;
|
|
1438
|
+
const session = buildQuestionSession(payload);
|
|
1439
|
+
this.sessions.set(key, session);
|
|
1440
|
+
await this.sendCurrentSessionPrompt(thread, session);
|
|
1441
|
+
}
|
|
1442
|
+
// Resolves the human-readable label for the model currently running in a turn.
|
|
1443
|
+
// Intentionally queries unfiltered availableProfiles (not filtered through allowedModelProfileIds)
|
|
1444
|
+
// because this describes what IS running, not what the user could have selected.
|
|
1445
|
+
resolveTurnModelLabel(turnRecord) {
|
|
1446
|
+
if (turnRecord.turnType !== "llm" || !turnRecord.modelProfileId) return null;
|
|
1447
|
+
const profile = this.processModelSelection?.listAvailableProfiles(turnRecord.instanceId)?.find((p) => p.id === turnRecord.modelProfileId);
|
|
1448
|
+
return profile?.label ?? turnRecord.modelProfileId;
|
|
1449
|
+
}
|
|
1450
|
+
filterProfiles(profiles) {
|
|
1451
|
+
const allowedIds = this.input.config.allowedModelProfileIds;
|
|
1452
|
+
if (!allowedIds.length) return profiles;
|
|
1453
|
+
const allowed = new Set(allowedIds);
|
|
1454
|
+
return profiles.filter((p) => allowed.has(p.id));
|
|
1455
|
+
}
|
|
1456
|
+
listSelectableProfiles(instanceId) {
|
|
1457
|
+
if (!this.input.config.actionModelSelection.enabled || !this.processModelSelection) return [];
|
|
1458
|
+
return this.filterProfiles(this.processModelSelection.listAvailableProfiles(instanceId) ?? []);
|
|
1459
|
+
}
|
|
1460
|
+
filterLaunchSchemaAvailableProfiles(schema) {
|
|
1461
|
+
return schema ? { ...schema, availableProfiles: this.filterProfiles(schema.availableProfiles) } : null;
|
|
1462
|
+
}
|
|
1463
|
+
async onTurnFailed(payload) {
|
|
1464
|
+
const { turnRecord } = payload;
|
|
1465
|
+
const thread = await this.getThread(turnRecord.instanceId);
|
|
1466
|
+
if (!thread) return;
|
|
1467
|
+
const errorSummary = payload.errorSummary.trim() || turnRecord.errorSummary || "Turn failed";
|
|
1468
|
+
const errorClass = payload.errorClass ?? turnRecord.errorClass ?? null;
|
|
1469
|
+
await this.sendHtml(
|
|
1470
|
+
thread,
|
|
1471
|
+
[
|
|
1472
|
+
`\u26A0\uFE0F <b>Turn failed</b>: ${escapeTelegramHtml(turnRecord.turnId)}`,
|
|
1473
|
+
`Error: ${escapeTelegramHtml(errorSummary)}`,
|
|
1474
|
+
...errorClass ? [`Class: ${escapeTelegramHtml(errorClass)}`] : [],
|
|
1475
|
+
"",
|
|
1476
|
+
"Use the recovery buttons for retry or continue options."
|
|
1477
|
+
].join("\n")
|
|
1478
|
+
);
|
|
1479
|
+
const process2 = this.input.deps.processes.getById(turnRecord.instanceId);
|
|
1480
|
+
if (process2) await this.sendActionsForProcess(process2);
|
|
1481
|
+
}
|
|
1482
|
+
async sendPublishedResult(thread, input) {
|
|
1483
|
+
const markdown2 = input.markdown.trim();
|
|
1484
|
+
if (!markdown2) return;
|
|
1485
|
+
const dedupeKey = resultTurnRecordKey(input.instanceId, input.turnRecordId);
|
|
1486
|
+
if (this.sentResultTurnRecordKeys.has(dedupeKey)) return;
|
|
1487
|
+
const parts = renderResultMarkdownForTelegram({
|
|
1488
|
+
markdown: markdown2,
|
|
1489
|
+
instanceId: input.instanceId,
|
|
1490
|
+
turnRecordId: input.turnRecordId
|
|
1491
|
+
});
|
|
1492
|
+
const leadingHtml = parts[0]?.kind === "html" ? parts[0] : null;
|
|
1493
|
+
await this.sendHtml(thread, input.buildMessage(leadingHtml?.html ?? ""));
|
|
1494
|
+
await this.sendResultParts(
|
|
1495
|
+
thread,
|
|
1496
|
+
input.instanceId,
|
|
1497
|
+
input.turnRecordId,
|
|
1498
|
+
parts.slice(leadingHtml ? 1 : 0)
|
|
1499
|
+
);
|
|
1500
|
+
this.sentResultTurnRecordKeys.add(dedupeKey);
|
|
1501
|
+
}
|
|
1502
|
+
async onLeafOutcome(snapshot) {
|
|
1503
|
+
const thread = await this.getThread(snapshot.instanceId);
|
|
1504
|
+
if (!thread) return;
|
|
1505
|
+
const markdown2 = snapshot.fallbackMarkdown?.trim() ?? "";
|
|
1506
|
+
if (markdown2 && snapshot.turnRecordId) {
|
|
1507
|
+
await this.sendPublishedResult(thread, {
|
|
1508
|
+
instanceId: snapshot.instanceId,
|
|
1509
|
+
turnRecordId: snapshot.turnRecordId,
|
|
1510
|
+
markdown: markdown2,
|
|
1511
|
+
buildMessage: (markdownHtml) => buildLeafOutcomeMessage({ snapshot, markdownHtml })
|
|
1512
|
+
});
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
await this.sendHtml(thread, buildLeafOutcomeMessage({ snapshot }));
|
|
1516
|
+
}
|
|
1517
|
+
async onTurnOutcome(payload) {
|
|
1518
|
+
const thread = await this.getThread(payload.instanceId);
|
|
1519
|
+
if (!thread) return;
|
|
1520
|
+
const pathType = this.lastTurnInfo.get(payload.instanceId)?.pathType ?? null;
|
|
1521
|
+
await this.sendPublishedResult(thread, {
|
|
1522
|
+
instanceId: payload.instanceId,
|
|
1523
|
+
turnRecordId: payload.turnRecordId,
|
|
1524
|
+
markdown: payload.turnResultMarkdown ?? "",
|
|
1525
|
+
buildMessage: (markdownHtml) => buildTurnOutcomeMessage({
|
|
1526
|
+
turnId: payload.turnId,
|
|
1527
|
+
outcome: payload.outcome,
|
|
1528
|
+
markdown: payload.turnResultMarkdown ?? "",
|
|
1529
|
+
markdownHtml,
|
|
1530
|
+
pathType
|
|
1531
|
+
})
|
|
1532
|
+
});
|
|
1533
|
+
const deferredCompletedProcess = this.deferredCompletedLifecycleProcesses.get(
|
|
1534
|
+
payload.instanceId
|
|
1535
|
+
);
|
|
1536
|
+
if (deferredCompletedProcess) {
|
|
1537
|
+
this.deferredCompletedLifecycleProcesses.delete(payload.instanceId);
|
|
1538
|
+
const process3 = this.input.deps.processes.getById(payload.instanceId) ?? deferredCompletedProcess;
|
|
1539
|
+
const lifecycleMessage = buildLifecycleMessage({
|
|
1540
|
+
process: process3,
|
|
1541
|
+
status: process3.lifecycleStatus
|
|
1542
|
+
});
|
|
1543
|
+
if (lifecycleMessage) await this.sendHtml(thread, lifecycleMessage);
|
|
1544
|
+
if (processIsFinished(process3)) await this.closeThread(thread);
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
const process2 = this.input.deps.processes.getById(payload.instanceId);
|
|
1548
|
+
if (process2 && ["waiting", "error"].includes(process2.lifecycleStatus)) {
|
|
1549
|
+
await this.sendActionsForProcess(process2);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
async ensureThread(process2) {
|
|
1553
|
+
const existing = this.store.getByInstanceId(process2.id);
|
|
1554
|
+
if (existing) return existing;
|
|
1555
|
+
const topicName = buildTopicTitle({ process: process2, template: this.input.config.topicTitleTemplate });
|
|
1556
|
+
const claimedThread = readClaimedLaunchThread(process2, this.input.config.delivery.forumChatId);
|
|
1557
|
+
if (claimedThread) {
|
|
1558
|
+
const thread = { ...claimedThread, topicName };
|
|
1559
|
+
try {
|
|
1560
|
+
await this.input.client.editForumTopic({
|
|
1561
|
+
chatId: thread.chatId,
|
|
1562
|
+
messageThreadId: thread.messageThreadId,
|
|
1563
|
+
name: topicName
|
|
1564
|
+
});
|
|
1565
|
+
} catch (error) {
|
|
1566
|
+
this.logError(error, "Failed to rename claimed Telegram launch topic");
|
|
1567
|
+
}
|
|
1568
|
+
this.store.record(process2, thread);
|
|
1569
|
+
return thread;
|
|
1570
|
+
}
|
|
1571
|
+
try {
|
|
1572
|
+
const topic = await this.input.client.createForumTopic({
|
|
1573
|
+
chatId: this.input.config.delivery.forumChatId,
|
|
1574
|
+
name: topicName
|
|
1575
|
+
});
|
|
1576
|
+
const thread = {
|
|
1577
|
+
mode: "forum_topic",
|
|
1578
|
+
chatId: this.input.config.delivery.forumChatId,
|
|
1579
|
+
messageThreadId: topic.messageThreadId,
|
|
1580
|
+
topicName
|
|
1581
|
+
};
|
|
1582
|
+
this.store.record(process2, thread);
|
|
1583
|
+
return thread;
|
|
1584
|
+
} catch (error) {
|
|
1585
|
+
this.logError(error, "Failed to create Telegram process topic");
|
|
1586
|
+
return null;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
async getThread(input) {
|
|
1590
|
+
const instanceId = typeof input === "string" ? input : input.id;
|
|
1591
|
+
const existing = this.store.getByInstanceId(instanceId);
|
|
1592
|
+
if (existing) return existing;
|
|
1593
|
+
if (!this.threadEligibleInstanceIds.has(instanceId)) return null;
|
|
1594
|
+
const process2 = typeof input === "string" ? this.input.deps.processes.getById(input) : input;
|
|
1595
|
+
if (!process2) return null;
|
|
1596
|
+
const thread = await this.ensureThread(process2);
|
|
1597
|
+
if (thread) await this.sendProcessIntro(thread, process2);
|
|
1598
|
+
return thread;
|
|
1599
|
+
}
|
|
1600
|
+
async sendProcessIntro(thread, process2) {
|
|
1601
|
+
if (this.introSentInstanceIds.has(process2.id)) return;
|
|
1602
|
+
await this.sendHtml(
|
|
1603
|
+
thread,
|
|
1604
|
+
buildProcessCreatedMessage({ process: process2, serverBaseUrl: this.input.deps.serverBaseUrl })
|
|
1605
|
+
);
|
|
1606
|
+
this.introSentInstanceIds.add(process2.id);
|
|
1607
|
+
}
|
|
1608
|
+
async closeThread(thread) {
|
|
1609
|
+
if (this.closedThreadKeys.has(threadKey(thread.chatId, thread.messageThreadId))) return;
|
|
1610
|
+
try {
|
|
1611
|
+
await this.input.client.closeForumTopic({
|
|
1612
|
+
chatId: thread.chatId,
|
|
1613
|
+
messageThreadId: thread.messageThreadId
|
|
1614
|
+
});
|
|
1615
|
+
} catch (error) {
|
|
1616
|
+
this.logError(error, "Failed to close Telegram process topic");
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
async syncThreadTitle(thread, process2) {
|
|
1620
|
+
const topicName = buildTopicTitle({ process: process2, template: this.input.config.topicTitleTemplate });
|
|
1621
|
+
if (topicName === thread.topicName) return;
|
|
1622
|
+
try {
|
|
1623
|
+
await this.input.client.editForumTopic({
|
|
1624
|
+
chatId: thread.chatId,
|
|
1625
|
+
messageThreadId: thread.messageThreadId,
|
|
1626
|
+
name: topicName
|
|
1627
|
+
});
|
|
1628
|
+
this.store.record(process2, { ...thread, topicName });
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
this.logError(error, "Failed to rename Telegram process topic");
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
async sendActionsForProcess(process2, options = {}) {
|
|
1634
|
+
const thread = this.store.getByInstanceId(process2.id);
|
|
1635
|
+
if (!thread) return;
|
|
1636
|
+
const actions = process2.lifecycleStatus === "waiting" ? this.input.deps.processActions.listVisibleActions(process2.id) : [];
|
|
1637
|
+
const isRecoveryOrHumanWait = ["waiting", "error"].includes(process2.lifecycleStatus);
|
|
1638
|
+
if (!options.explicit && !isRecoveryOrHumanWait && actions.length === 0) return;
|
|
1639
|
+
const keyboard = buildActionKeyboard({
|
|
1640
|
+
process: process2,
|
|
1641
|
+
actions
|
|
1642
|
+
});
|
|
1643
|
+
if (!keyboard) {
|
|
1644
|
+
if (options.explicit)
|
|
1645
|
+
await this.sendHtml(thread, "No actions are available for this process.");
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
const turnInfo = this.lastTurnInfo.get(process2.id);
|
|
1649
|
+
await this.sendHtml(
|
|
1650
|
+
thread,
|
|
1651
|
+
buildActionsPromptMessage({
|
|
1652
|
+
process: process2,
|
|
1653
|
+
actions,
|
|
1654
|
+
recoveryActions: recoveryActionLabels(process2),
|
|
1655
|
+
currentTurnDescription: turnInfo ? formatTurnIdLabel(turnInfo.turnId) : null,
|
|
1656
|
+
currentTurnPathType: turnInfo?.pathType ?? null
|
|
1657
|
+
}),
|
|
1658
|
+
keyboard
|
|
1659
|
+
);
|
|
1660
|
+
}
|
|
1661
|
+
async handleForumTopicCreated(update) {
|
|
1662
|
+
if (!this.isAllowed(update.from)) return;
|
|
1663
|
+
if (update.chatId !== this.input.config.delivery.forumChatId) return;
|
|
1664
|
+
if (this.store.getInstanceIdForThread(update.chatId, update.messageThreadId)) return;
|
|
1665
|
+
await this.sendUnmappedTopicHelp(update.chatId, update.messageThreadId);
|
|
1666
|
+
}
|
|
1667
|
+
async handleForumTopicClosed(update) {
|
|
1668
|
+
if (update.chatId !== this.input.config.delivery.forumChatId) return;
|
|
1669
|
+
const instanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
|
|
1670
|
+
if (!instanceId) return;
|
|
1671
|
+
this.closedThreadKeys.add(threadKey(update.chatId, update.messageThreadId));
|
|
1672
|
+
await this.enqueue(instanceId, () => this.abortProcessForClosedTopic(instanceId));
|
|
1673
|
+
}
|
|
1674
|
+
async abortProcessForClosedTopic(instanceId) {
|
|
1675
|
+
const process2 = this.input.deps.processes.getById(instanceId);
|
|
1676
|
+
if (!process2 || processIsFinished(process2)) return;
|
|
1677
|
+
const result = await this.input.deps.commands.abortProcess(instanceId, {
|
|
1678
|
+
actor: TELEGRAM_ACTOR
|
|
1679
|
+
});
|
|
1680
|
+
if (!result.ok) {
|
|
1681
|
+
this.logError(
|
|
1682
|
+
result.message ?? result.code ?? "Abort failed",
|
|
1683
|
+
"Failed to abort closed Telegram topic"
|
|
1684
|
+
);
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
async handleText(update) {
|
|
1688
|
+
if (!this.isAllowed(update.from)) return;
|
|
1689
|
+
const name = commandName(update.text);
|
|
1690
|
+
const instanceId = this.store.getInstanceIdForThread(update.chatId, update.messageThreadId);
|
|
1691
|
+
if (!instanceId) {
|
|
1692
|
+
await this.handleUnmappedTopicText(update, name);
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
await this.enqueue(instanceId, () => this.handleProcessText(instanceId, update, name));
|
|
1696
|
+
}
|
|
1697
|
+
async handleUnmappedTopicText(update, name) {
|
|
1698
|
+
const key = launchSessionKey(update);
|
|
1699
|
+
if (!key) return;
|
|
1700
|
+
const inConfiguredForum = update.chatId === this.input.config.delivery.forumChatId;
|
|
1701
|
+
if (!inConfiguredForum) {
|
|
1702
|
+
if (name === "help") {
|
|
1703
|
+
await this.sendPlainToChat(
|
|
1704
|
+
update.chatId,
|
|
1705
|
+
update.messageThreadId,
|
|
1706
|
+
"This bot is operated from the configured process forum chat."
|
|
1707
|
+
);
|
|
1708
|
+
}
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
if (name === "cancel") {
|
|
1712
|
+
this.launchSessions.delete(key);
|
|
1713
|
+
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Cancelled.");
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
if (name === "help") {
|
|
1717
|
+
await this.sendUnmappedTopicHelp(update.chatId, update.messageThreadId);
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
if (name === "launchers") {
|
|
1721
|
+
await this.sendLauncherList(update, key, { includeButtons: false });
|
|
1722
|
+
return;
|
|
1723
|
+
}
|
|
1724
|
+
if (name === "launch") {
|
|
1725
|
+
if (update.messageThreadId === void 0) {
|
|
1726
|
+
await this.sendHtmlToChat(
|
|
1727
|
+
update.chatId,
|
|
1728
|
+
update.messageThreadId,
|
|
1729
|
+
"Create a new forum topic first, then send /launch in that topic."
|
|
1730
|
+
);
|
|
1731
|
+
return;
|
|
1732
|
+
}
|
|
1733
|
+
const launcherId = commandArgs(update.text);
|
|
1734
|
+
if (launcherId) {
|
|
1735
|
+
await this.startLaunchSession(update, key, launcherId);
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
await this.sendLauncherList(update, key, { includeButtons: true });
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
const session = this.launchSessions.get(key);
|
|
1742
|
+
if (session) {
|
|
1743
|
+
await this.handleLaunchSessionText(key, session, update, name);
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
if (name) {
|
|
1747
|
+
await this.sendHtmlToChat(
|
|
1748
|
+
update.chatId,
|
|
1749
|
+
update.messageThreadId,
|
|
1750
|
+
"Unknown command. Use /help for available commands."
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
async handleProcessText(instanceId, update, name) {
|
|
1755
|
+
const thread = this.store.getByInstanceId(instanceId);
|
|
1756
|
+
if (!thread) return;
|
|
1757
|
+
const key = threadKey(update.chatId, update.messageThreadId);
|
|
1758
|
+
if (name === "cancel") {
|
|
1759
|
+
if (this.sessions.get(key)?.kind === "question") {
|
|
1760
|
+
await this.sendHtml(
|
|
1761
|
+
thread,
|
|
1762
|
+
"The active turn is still waiting for this answer. Answer here, use the Web UI, or stop the turn."
|
|
1763
|
+
);
|
|
1764
|
+
return;
|
|
1765
|
+
}
|
|
1766
|
+
this.sessions.delete(key);
|
|
1767
|
+
await this.sendHtml(thread, "Cancelled.");
|
|
1768
|
+
return;
|
|
1769
|
+
}
|
|
1770
|
+
if (name === "actions") {
|
|
1771
|
+
const process3 = this.input.deps.processes.getById(instanceId);
|
|
1772
|
+
if (process3) await this.sendActionsForProcess(process3, { explicit: true });
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
if (name === "status") {
|
|
1776
|
+
const process3 = this.input.deps.processes.getById(instanceId);
|
|
1777
|
+
if (process3) {
|
|
1778
|
+
const actions = process3.lifecycleStatus === "waiting" ? this.input.deps.processActions.listVisibleActions(process3.id) : [];
|
|
1779
|
+
const turnInfo = this.lastTurnInfo.get(instanceId);
|
|
1780
|
+
await this.sendHtml(
|
|
1781
|
+
thread,
|
|
1782
|
+
buildStatusMessage({
|
|
1783
|
+
process: process3,
|
|
1784
|
+
actions,
|
|
1785
|
+
currentTurnDescription: turnInfo ? formatTurnIdLabel(turnInfo.turnId) : null,
|
|
1786
|
+
currentTurnPathType: turnInfo?.pathType ?? null
|
|
1787
|
+
})
|
|
1788
|
+
);
|
|
1789
|
+
}
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
if (name === "help") {
|
|
1793
|
+
await this.sendHtml(
|
|
1794
|
+
thread,
|
|
1795
|
+
"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."
|
|
1796
|
+
);
|
|
1797
|
+
return;
|
|
1798
|
+
}
|
|
1799
|
+
if (name === "launch") {
|
|
1800
|
+
await this.sendHtml(
|
|
1801
|
+
thread,
|
|
1802
|
+
"This topic is already linked to a process. Create a new forum topic and send /launch there to start another process."
|
|
1803
|
+
);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
const session = this.sessions.get(key);
|
|
1807
|
+
if (session) {
|
|
1808
|
+
await this.handleSessionText(key, session, update.text, thread, name);
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
if (name) {
|
|
1812
|
+
await this.sendHtml(thread, "Unknown command. Use /help for available commands.");
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
const process2 = this.input.deps.processes.getById(instanceId);
|
|
1816
|
+
if (!process2) return;
|
|
1817
|
+
if (!processCanAcceptFreeText(process2)) {
|
|
1818
|
+
await this.sendHtml(
|
|
1819
|
+
thread,
|
|
1820
|
+
"This process is not accepting free-text input right now. Use /actions for available options."
|
|
1821
|
+
);
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
const result = await this.input.deps.commands.queueInputs(
|
|
1825
|
+
instanceId,
|
|
1826
|
+
[{ source: "external_comment", kind: "instruction", bodyMarkdown: update.text }],
|
|
1827
|
+
{
|
|
1828
|
+
dispatchErrorMessage: "Failed to deliver the Telegram input to the worker",
|
|
1829
|
+
actor: TELEGRAM_ACTOR
|
|
1830
|
+
}
|
|
1831
|
+
);
|
|
1832
|
+
await this.sendCommandResult(thread, result, "\u{1F4AC} Sent to process.", "Failed to send input");
|
|
1833
|
+
}
|
|
1834
|
+
async handleCallback(update) {
|
|
1835
|
+
if (!this.isAllowed(update.from)) {
|
|
1836
|
+
await this.answerCallback(update.id, "Not allowed", true);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
const launchCallback = this.readLaunchCallbackCommand(update.data);
|
|
1840
|
+
if (launchCallback) {
|
|
1841
|
+
const key = launchSessionKey(update);
|
|
1842
|
+
if (!key || key !== launchCallback.command.sessionKey) {
|
|
1843
|
+
await this.answerCallback(
|
|
1844
|
+
update.id,
|
|
1845
|
+
"This launch button belongs to another session.",
|
|
1846
|
+
true
|
|
1847
|
+
);
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
this.launchCallbacks.delete(launchCallback.token);
|
|
1851
|
+
await this.answerCallback(update.id);
|
|
1852
|
+
await this.executeLaunchCallbackCommand(key, update, launchCallback.command);
|
|
1853
|
+
return;
|
|
1854
|
+
}
|
|
1855
|
+
if (update.data.startsWith(LAUNCH_CALLBACK_PREFIX)) {
|
|
1856
|
+
await this.answerCallback(
|
|
1857
|
+
update.id,
|
|
1858
|
+
"This launch button expired. Send /launch to start again.",
|
|
1859
|
+
true
|
|
1860
|
+
);
|
|
1861
|
+
return;
|
|
1862
|
+
}
|
|
1863
|
+
const command = parseCallbackCommand(update.data);
|
|
1864
|
+
if (!command) {
|
|
1865
|
+
await this.answerCallback(update.id, "Unknown button. Send /actions to refresh.", true);
|
|
1866
|
+
return;
|
|
1867
|
+
}
|
|
1868
|
+
const resolved = this.resolveCallbackInstance(update, command);
|
|
1869
|
+
if (!resolved.ok) {
|
|
1870
|
+
await this.answerCallback(update.id, resolved.message, true);
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
await this.answerCallback(update.id);
|
|
1874
|
+
await this.enqueue(
|
|
1875
|
+
resolved.instanceId,
|
|
1876
|
+
() => this.executeCallbackCommand(resolved.instanceId, command)
|
|
1877
|
+
);
|
|
1878
|
+
}
|
|
1879
|
+
resolveCallbackInstance(update, command) {
|
|
1880
|
+
const threadInstanceId = this.store.getInstanceIdForThread(
|
|
1881
|
+
update.chatId,
|
|
1882
|
+
update.messageThreadId
|
|
1883
|
+
);
|
|
1884
|
+
if (!threadInstanceId) {
|
|
1885
|
+
return { ok: false, message: "This button is not in a process topic." };
|
|
1886
|
+
}
|
|
1887
|
+
if (command.instanceId !== threadInstanceId) {
|
|
1888
|
+
return { ok: false, message: "This button belongs to another process topic." };
|
|
1889
|
+
}
|
|
1890
|
+
return { ok: true, instanceId: threadInstanceId };
|
|
1891
|
+
}
|
|
1892
|
+
async answerCallback(id, text, showAlert) {
|
|
1893
|
+
await this.input.client.answerCallbackQuery({
|
|
1894
|
+
callbackQueryId: id,
|
|
1895
|
+
...text ? { text } : {},
|
|
1896
|
+
...showAlert !== void 0 ? { showAlert } : {}
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
getLauncher(launcherId) {
|
|
1900
|
+
return this.input.deps.launcherService.listUiLaunchers().find((launcher) => launcher.id === launcherId) ?? null;
|
|
1901
|
+
}
|
|
1902
|
+
async sendUnmappedTopicHelp(chatId, messageThreadId) {
|
|
1903
|
+
await this.sendHtmlToChat(
|
|
1904
|
+
chatId,
|
|
1905
|
+
messageThreadId,
|
|
1906
|
+
[
|
|
1907
|
+
"This topic can become a new leitwerk process.",
|
|
1908
|
+
"Send /launch to choose a process launcher, then answer the prompts here.",
|
|
1909
|
+
"Required fields are asked first; optional fields come after and can be skipped with /skip.",
|
|
1910
|
+
"Use /launchers to list launcher ids, or /cancel to discard a pending launch draft."
|
|
1911
|
+
].join("\n")
|
|
1912
|
+
);
|
|
1913
|
+
}
|
|
1914
|
+
async sendLauncherList(update, sessionKey, options) {
|
|
1915
|
+
const launchers = this.input.deps.launcherService.listUiLaunchers();
|
|
1916
|
+
if (launchers.length === 0) {
|
|
1917
|
+
await this.sendHtmlToChat(
|
|
1918
|
+
update.chatId,
|
|
1919
|
+
update.messageThreadId,
|
|
1920
|
+
"No launchers are available."
|
|
1921
|
+
);
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
const lines = ["Available launchers:", ""];
|
|
1925
|
+
for (const launcher of launchers) {
|
|
1926
|
+
const description = launcher.description.trim();
|
|
1927
|
+
lines.push(
|
|
1928
|
+
description ? `- ${launcher.label} (${launcher.id}) \u2014 ${description}` : `- ${launcher.label} (${launcher.id})`
|
|
1929
|
+
);
|
|
1930
|
+
}
|
|
1931
|
+
if (launchers.length > MAX_LAUNCHER_BUTTONS && options.includeButtons) {
|
|
1932
|
+
lines.push(
|
|
1933
|
+
"",
|
|
1934
|
+
`Showing buttons for the first ${MAX_LAUNCHER_BUTTONS}. Use /launch <launcherId> for others.`
|
|
1935
|
+
);
|
|
1936
|
+
}
|
|
1937
|
+
await this.sendHtmlToChat(
|
|
1938
|
+
update.chatId,
|
|
1939
|
+
update.messageThreadId,
|
|
1940
|
+
escapeTelegramHtml(lines.join("\n")),
|
|
1941
|
+
options.includeButtons ? this.buildLauncherListKeyboard(launchers, sessionKey) : void 0
|
|
1942
|
+
);
|
|
1943
|
+
}
|
|
1944
|
+
async startLaunchSession(update, sessionKey, launcherId) {
|
|
1945
|
+
if (update.chatId !== this.input.config.delivery.forumChatId) {
|
|
1946
|
+
await this.sendHtmlToChat(
|
|
1947
|
+
update.chatId,
|
|
1948
|
+
update.messageThreadId,
|
|
1949
|
+
"Launches are only available from the configured process forum chat."
|
|
1950
|
+
);
|
|
1951
|
+
return;
|
|
1952
|
+
}
|
|
1953
|
+
if (update.messageThreadId === void 0) {
|
|
1954
|
+
await this.sendHtmlToChat(
|
|
1955
|
+
update.chatId,
|
|
1956
|
+
update.messageThreadId,
|
|
1957
|
+
"Create a new forum topic first, then send /launch in that topic."
|
|
1958
|
+
);
|
|
1959
|
+
return;
|
|
1960
|
+
}
|
|
1961
|
+
const launcher = this.getLauncher(launcherId);
|
|
1962
|
+
if (!launcher) {
|
|
1963
|
+
await this.sendHtmlToChat(
|
|
1964
|
+
update.chatId,
|
|
1965
|
+
update.messageThreadId,
|
|
1966
|
+
`Unknown launcher: ${escapeTelegramHtml(launcherId)}`
|
|
1967
|
+
);
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
let defaults;
|
|
1971
|
+
try {
|
|
1972
|
+
defaults = await this.input.deps.launcherService.resolveUiDefaults(launcher.id);
|
|
1973
|
+
} catch (error) {
|
|
1974
|
+
this.logError(error, "Failed to resolve Telegram launcher defaults");
|
|
1975
|
+
await this.sendHtmlToChat(
|
|
1976
|
+
update.chatId,
|
|
1977
|
+
update.messageThreadId,
|
|
1978
|
+
"Couldn't load launcher defaults. Try /launch again later."
|
|
1979
|
+
);
|
|
1980
|
+
return;
|
|
1981
|
+
}
|
|
1982
|
+
const session = createLaunchSession({
|
|
1983
|
+
launcher,
|
|
1984
|
+
defaults,
|
|
1985
|
+
ttlMs: LAUNCH_SESSION_TTL_MS
|
|
1986
|
+
});
|
|
1987
|
+
this.launchSessions.set(sessionKey, session);
|
|
1988
|
+
await this.sendHtmlToChat(
|
|
1989
|
+
update.chatId,
|
|
1990
|
+
update.messageThreadId,
|
|
1991
|
+
`Starting launcher: ${escapeTelegramHtml(launcher.label)}. I\u2019ll ask required fields first, then optional fields. Use /skip for optional/defaulted fields and /cancel to discard this draft.`
|
|
1992
|
+
);
|
|
1993
|
+
await this.sendNextLaunchPrompt(sessionKey, session, update);
|
|
1994
|
+
}
|
|
1995
|
+
async handleLaunchSessionText(sessionKey, session, update, name) {
|
|
1996
|
+
if (session.expiresAt < Date.now()) {
|
|
1997
|
+
this.launchSessions.delete(sessionKey);
|
|
1998
|
+
await this.sendHtmlToChat(
|
|
1999
|
+
update.chatId,
|
|
2000
|
+
update.messageThreadId,
|
|
2001
|
+
"This launch draft expired. Send /launch to start again."
|
|
2002
|
+
);
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
if (name && name !== "skip") {
|
|
2006
|
+
await this.sendHtmlToChat(
|
|
2007
|
+
update.chatId,
|
|
2008
|
+
update.messageThreadId,
|
|
2009
|
+
"Finish this launch prompt, or send /cancel to discard it."
|
|
2010
|
+
);
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
const launcher = this.getLauncher(session.launcherId);
|
|
2014
|
+
if (!launcher) {
|
|
2015
|
+
this.launchSessions.delete(sessionKey);
|
|
2016
|
+
await this.sendHtmlToChat(
|
|
2017
|
+
update.chatId,
|
|
2018
|
+
update.messageThreadId,
|
|
2019
|
+
"This launcher is no longer available. Send /launch to choose another."
|
|
2020
|
+
);
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
if (session.modelEdit) {
|
|
2024
|
+
await this.handleLaunchModelText(sessionKey, session, update);
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
2027
|
+
const optionsById = await this.resolveLaunchOptions(session);
|
|
2028
|
+
const step = applyLaunchFieldText(session, launcher, update.text, optionsById);
|
|
2029
|
+
if (!step.ok) {
|
|
2030
|
+
await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeTelegramHtml(step.prompt));
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
if (step.done) {
|
|
2034
|
+
await this.sendLaunchReview(sessionKey, session, launcher, update);
|
|
2035
|
+
return;
|
|
2036
|
+
}
|
|
2037
|
+
await this.sendNextLaunchPrompt(sessionKey, session, update);
|
|
2038
|
+
}
|
|
2039
|
+
async executeLaunchCallbackCommand(sessionKey, update, command) {
|
|
2040
|
+
switch (command.kind) {
|
|
2041
|
+
case "select_launcher":
|
|
2042
|
+
await this.startLaunchSession(update, sessionKey, command.launcherId);
|
|
2043
|
+
return;
|
|
2044
|
+
case "cancel_launch":
|
|
2045
|
+
this.launchSessions.delete(sessionKey);
|
|
2046
|
+
await this.sendHtmlToChat(update.chatId, update.messageThreadId, "Cancelled.");
|
|
2047
|
+
return;
|
|
2048
|
+
case "edit_models":
|
|
2049
|
+
await this.startLaunchModelEdit(sessionKey, update);
|
|
2050
|
+
return;
|
|
2051
|
+
case "model_step":
|
|
2052
|
+
await this.executeLaunchModelCallbackCommand(sessionKey, update, command);
|
|
2053
|
+
return;
|
|
2054
|
+
case "finish_model_edit":
|
|
2055
|
+
await this.finishLaunchModelEdit(sessionKey, update);
|
|
2056
|
+
return;
|
|
2057
|
+
case "confirm_launch": {
|
|
2058
|
+
const session = await this.getActiveLaunchSession(sessionKey, update);
|
|
2059
|
+
if (!session) return;
|
|
2060
|
+
if (session.modelEdit) {
|
|
2061
|
+
await this.sendHtmlToChat(
|
|
2062
|
+
update.chatId,
|
|
2063
|
+
update.messageThreadId,
|
|
2064
|
+
"Finish model setup before starting this process."
|
|
2065
|
+
);
|
|
2066
|
+
await this.sendNextLaunchModelPrompt(sessionKey, session, update);
|
|
2067
|
+
return;
|
|
2068
|
+
}
|
|
2069
|
+
await this.executeLaunchSession(sessionKey, session, update);
|
|
2070
|
+
return;
|
|
2071
|
+
}
|
|
2072
|
+
case "field_value":
|
|
2073
|
+
case "skip_field": {
|
|
2074
|
+
const context = await this.getLaunchContext(sessionKey, update);
|
|
2075
|
+
if (!context) return;
|
|
2076
|
+
const { session, launcher } = context;
|
|
2077
|
+
const field = currentLaunchField(session, launcher);
|
|
2078
|
+
if (!field || field.id !== command.fieldId) {
|
|
2079
|
+
await this.sendHtmlToChat(
|
|
2080
|
+
update.chatId,
|
|
2081
|
+
update.messageThreadId,
|
|
2082
|
+
"That launch button is stale. Continue with the latest prompt or send /cancel."
|
|
2083
|
+
);
|
|
2084
|
+
return;
|
|
2085
|
+
}
|
|
2086
|
+
const optionsById = await this.resolveLaunchOptions(session);
|
|
2087
|
+
const step = command.kind === "skip_field" ? applyLaunchFieldText(session, launcher, "/skip", optionsById) : applyLaunchFieldValue(session, launcher, command.value, optionsById);
|
|
2088
|
+
if (!step.ok) {
|
|
2089
|
+
await this.sendHtmlToChat(update.chatId, update.messageThreadId, escapeTelegramHtml(step.prompt));
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
if (step.done) {
|
|
2093
|
+
await this.sendLaunchReview(sessionKey, session, launcher, update);
|
|
2094
|
+
return;
|
|
2095
|
+
}
|
|
2096
|
+
await this.sendNextLaunchPrompt(sessionKey, session, update);
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
async getLaunchModelSchema(session) {
|
|
2102
|
+
try {
|
|
2103
|
+
const schema = await this.input.deps.launcherModelConfigs.getSchema(session.launcherId);
|
|
2104
|
+
return this.filterLaunchSchemaAvailableProfiles(schema);
|
|
2105
|
+
} catch (error) {
|
|
2106
|
+
this.logError(error, "Failed to resolve Telegram launcher model schema");
|
|
2107
|
+
return null;
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
async getLaunchModelPreview(session) {
|
|
2111
|
+
try {
|
|
2112
|
+
return await this.input.deps.launcherModelConfigs.preview(
|
|
2113
|
+
session.launcherId,
|
|
2114
|
+
buildLaunchInput(session),
|
|
2115
|
+
{ modelConfig: buildLaunchModelConfig(session) }
|
|
2116
|
+
);
|
|
2117
|
+
} catch (error) {
|
|
2118
|
+
this.logError(error, "Failed to resolve Telegram launcher model preview");
|
|
2119
|
+
return null;
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
async getActiveLaunchSession(sessionKey, target) {
|
|
2123
|
+
const session = this.launchSessions.get(sessionKey);
|
|
2124
|
+
if (session && session.expiresAt >= Date.now()) return session;
|
|
2125
|
+
if (session) this.launchSessions.delete(sessionKey);
|
|
2126
|
+
await this.sendHtmlToChat(
|
|
2127
|
+
target.chatId,
|
|
2128
|
+
target.messageThreadId,
|
|
2129
|
+
"This launch draft expired. Send /launch to start again."
|
|
2130
|
+
);
|
|
2131
|
+
return null;
|
|
2132
|
+
}
|
|
2133
|
+
async getLaunchContext(sessionKey, target) {
|
|
2134
|
+
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
2135
|
+
if (!session) return null;
|
|
2136
|
+
const launcher = this.getLauncher(session.launcherId);
|
|
2137
|
+
if (launcher) return { session, launcher };
|
|
2138
|
+
this.launchSessions.delete(sessionKey);
|
|
2139
|
+
await this.sendHtmlToChat(
|
|
2140
|
+
target.chatId,
|
|
2141
|
+
target.messageThreadId,
|
|
2142
|
+
"This launcher is no longer available. Send /launch to choose another."
|
|
2143
|
+
);
|
|
2144
|
+
return null;
|
|
2145
|
+
}
|
|
2146
|
+
async sendLaunchReviewForSession(sessionKey, session, target) {
|
|
2147
|
+
const launcher = this.getLauncher(session.launcherId);
|
|
2148
|
+
if (!launcher) {
|
|
2149
|
+
this.launchSessions.delete(sessionKey);
|
|
2150
|
+
await this.sendHtmlToChat(
|
|
2151
|
+
target.chatId,
|
|
2152
|
+
target.messageThreadId,
|
|
2153
|
+
"This launcher is no longer available. Send /launch to choose another."
|
|
2154
|
+
);
|
|
2155
|
+
return;
|
|
2156
|
+
}
|
|
2157
|
+
await this.sendLaunchReview(sessionKey, session, launcher, target);
|
|
2158
|
+
}
|
|
2159
|
+
async finishLaunchModelEditAndReview(sessionKey, session, target) {
|
|
2160
|
+
finishLaunchModelEdit(session);
|
|
2161
|
+
await this.sendLaunchReviewForSession(sessionKey, session, target);
|
|
2162
|
+
}
|
|
2163
|
+
async startLaunchModelEdit(sessionKey, target) {
|
|
2164
|
+
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
2165
|
+
if (!session) return;
|
|
2166
|
+
const schema = await this.getLaunchModelSchema(session);
|
|
2167
|
+
if (!hasLaunchModelControls(schema)) {
|
|
2168
|
+
await this.sendHtmlToChat(
|
|
2169
|
+
target.chatId,
|
|
2170
|
+
target.messageThreadId,
|
|
2171
|
+
"This launcher has no editable model setup."
|
|
2172
|
+
);
|
|
2173
|
+
return;
|
|
2174
|
+
}
|
|
2175
|
+
beginLaunchModelEdit(session, schema);
|
|
2176
|
+
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
2177
|
+
}
|
|
2178
|
+
async executeLaunchModelCallbackCommand(sessionKey, target, command) {
|
|
2179
|
+
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
2180
|
+
if (!session) return;
|
|
2181
|
+
const schema = await this.getLaunchModelSchema(session);
|
|
2182
|
+
if (!hasLaunchModelControls(schema)) {
|
|
2183
|
+
await this.finishLaunchModelEditAndReview(sessionKey, session, target);
|
|
2184
|
+
return;
|
|
2185
|
+
}
|
|
2186
|
+
const step = currentLaunchModelStep(session, schema);
|
|
2187
|
+
if (!step || step.key !== command.stepKey) {
|
|
2188
|
+
await this.sendHtmlToChat(
|
|
2189
|
+
target.chatId,
|
|
2190
|
+
target.messageThreadId,
|
|
2191
|
+
"That model button is stale. Continue with the latest prompt or send /cancel."
|
|
2192
|
+
);
|
|
2193
|
+
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
2194
|
+
return;
|
|
2195
|
+
}
|
|
2196
|
+
const action = command.action === "set" ? { action: "set", value: command.value } : command.action === "inherit" ? { action: "inherit" } : { action: "skip" };
|
|
2197
|
+
await this.continueAfterLaunchModelResult(
|
|
2198
|
+
sessionKey,
|
|
2199
|
+
session,
|
|
2200
|
+
schema,
|
|
2201
|
+
applyLaunchModelStepAction(session, schema, action),
|
|
2202
|
+
target
|
|
2203
|
+
);
|
|
2204
|
+
}
|
|
2205
|
+
async finishLaunchModelEdit(sessionKey, target) {
|
|
2206
|
+
const session = await this.getActiveLaunchSession(sessionKey, target);
|
|
2207
|
+
if (session) await this.finishLaunchModelEditAndReview(sessionKey, session, target);
|
|
2208
|
+
}
|
|
2209
|
+
async handleLaunchModelText(sessionKey, session, update) {
|
|
2210
|
+
const schema = await this.getLaunchModelSchema(session);
|
|
2211
|
+
if (!hasLaunchModelControls(schema)) {
|
|
2212
|
+
await this.finishLaunchModelEditAndReview(sessionKey, session, update);
|
|
2213
|
+
return;
|
|
2214
|
+
}
|
|
2215
|
+
await this.continueAfterLaunchModelResult(
|
|
2216
|
+
sessionKey,
|
|
2217
|
+
session,
|
|
2218
|
+
schema,
|
|
2219
|
+
applyLaunchModelStepText(session, schema, update.text),
|
|
2220
|
+
update
|
|
2221
|
+
);
|
|
2222
|
+
}
|
|
2223
|
+
async continueAfterLaunchModelResult(sessionKey, session, schema, result, target) {
|
|
2224
|
+
if (!result.ok) {
|
|
2225
|
+
const step = currentLaunchModelStep(session, schema);
|
|
2226
|
+
await this.sendHtmlToChat(
|
|
2227
|
+
target.chatId,
|
|
2228
|
+
target.messageThreadId,
|
|
2229
|
+
escapeTelegramHtml(result.prompt),
|
|
2230
|
+
step ? this.buildLaunchModelReplyMarkup({ sessionKey, step, schema }) : void 0
|
|
2231
|
+
);
|
|
2232
|
+
return;
|
|
2233
|
+
}
|
|
2234
|
+
if (result.done) {
|
|
2235
|
+
await this.sendLaunchReviewForSession(sessionKey, session, target);
|
|
2236
|
+
return;
|
|
2237
|
+
}
|
|
2238
|
+
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
2239
|
+
}
|
|
2240
|
+
resolveLaunchRecentValues(session) {
|
|
2241
|
+
try {
|
|
2242
|
+
return this.input.deps.launcherRecentValues.list(session.launcherId);
|
|
2243
|
+
} catch (error) {
|
|
2244
|
+
this.logError(error, "Failed to resolve Telegram launcher recent values");
|
|
2245
|
+
return {};
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
recordLaunchRecentValuesBestEffort(session) {
|
|
2249
|
+
try {
|
|
2250
|
+
this.input.deps.launcherRecentValues.record(session.launcherId, buildLaunchInput(session));
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
this.logError(error, "Failed to record Telegram launcher recent values");
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
async resolveLaunchOptions(session) {
|
|
2256
|
+
const launcher = this.getLauncher(session.launcherId);
|
|
2257
|
+
if (!launcher?.launchConfigSchema.fields.some((field) => field.kind === "select")) {
|
|
2258
|
+
return {};
|
|
2259
|
+
}
|
|
2260
|
+
try {
|
|
2261
|
+
return await this.input.deps.launcherService.resolveUiOptions(
|
|
2262
|
+
session.launcherId,
|
|
2263
|
+
buildLaunchInput(session)
|
|
2264
|
+
);
|
|
2265
|
+
} catch (error) {
|
|
2266
|
+
this.logError(error, "Failed to resolve Telegram launch field options");
|
|
2267
|
+
return {};
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
async sendNextLaunchModelPrompt(sessionKey, session, target) {
|
|
2271
|
+
const schema = await this.getLaunchModelSchema(session);
|
|
2272
|
+
if (!hasLaunchModelControls(schema)) {
|
|
2273
|
+
await this.finishLaunchModelEditAndReview(sessionKey, session, target);
|
|
2274
|
+
return;
|
|
2275
|
+
}
|
|
2276
|
+
const step = currentLaunchModelStep(session, schema);
|
|
2277
|
+
if (!step) {
|
|
2278
|
+
await this.sendLaunchReviewForSession(sessionKey, session, target);
|
|
2279
|
+
return;
|
|
2280
|
+
}
|
|
2281
|
+
const preview = await this.getLaunchModelPreview(session);
|
|
2282
|
+
const prompt = buildLaunchModelStepPrompt({ step, schema, session, preview });
|
|
2283
|
+
await this.sendHtmlToChat(
|
|
2284
|
+
target.chatId,
|
|
2285
|
+
target.messageThreadId,
|
|
2286
|
+
escapeTelegramHtml(prompt),
|
|
2287
|
+
this.buildLaunchModelReplyMarkup({ sessionKey, step, schema })
|
|
2288
|
+
);
|
|
2289
|
+
}
|
|
2290
|
+
async sendNextLaunchPrompt(sessionKey, session, target) {
|
|
2291
|
+
if (session.modelEdit) {
|
|
2292
|
+
await this.sendNextLaunchModelPrompt(sessionKey, session, target);
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
const launcher = this.getLauncher(session.launcherId);
|
|
2296
|
+
if (!launcher) return;
|
|
2297
|
+
const field = currentLaunchField(session, launcher);
|
|
2298
|
+
if (!field) {
|
|
2299
|
+
await this.sendLaunchReview(sessionKey, session, launcher, target);
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
const optionsById = await this.resolveLaunchOptions(session);
|
|
2303
|
+
const recentValuesById = this.resolveLaunchRecentValues(session);
|
|
2304
|
+
const fieldOptions = getLaunchFieldOptions(field, optionsById);
|
|
2305
|
+
const fieldRecentValues = recentValuesById[field.id] ?? [];
|
|
2306
|
+
const prompt = buildLaunchFieldPrompt({
|
|
2307
|
+
field,
|
|
2308
|
+
currentValue: session.values[field.id],
|
|
2309
|
+
options: fieldOptions,
|
|
2310
|
+
recentValues: fieldRecentValues
|
|
2311
|
+
});
|
|
2312
|
+
await this.sendHtmlToChat(
|
|
2313
|
+
target.chatId,
|
|
2314
|
+
target.messageThreadId,
|
|
2315
|
+
escapeTelegramHtml(prompt),
|
|
2316
|
+
this.buildLaunchFieldReplyMarkup({
|
|
2317
|
+
sessionKey,
|
|
2318
|
+
fieldId: field.id,
|
|
2319
|
+
fieldKind: field.kind,
|
|
2320
|
+
currentValue: session.values[field.id],
|
|
2321
|
+
options: fieldOptions,
|
|
2322
|
+
recentValues: fieldRecentValues,
|
|
2323
|
+
required: field.required
|
|
2324
|
+
})
|
|
2325
|
+
);
|
|
2326
|
+
}
|
|
2327
|
+
async sendLaunchReview(sessionKey, session, launcher, target) {
|
|
2328
|
+
const prepared = await this.prepareLaunchSession(session, launcher);
|
|
2329
|
+
if (!prepared.ok) {
|
|
2330
|
+
await this.sendHtmlToChat(
|
|
2331
|
+
target.chatId,
|
|
2332
|
+
target.messageThreadId,
|
|
2333
|
+
escapeTelegramHtml(prepared.message)
|
|
2334
|
+
);
|
|
2335
|
+
if (prepared.reprompt) await this.sendNextLaunchPrompt(sessionKey, session, target);
|
|
2336
|
+
return;
|
|
2337
|
+
}
|
|
2338
|
+
const schema = await this.getLaunchModelSchema(session);
|
|
2339
|
+
const modelSummary = hasLaunchModelControls(schema) ? buildLaunchModelSummary({
|
|
2340
|
+
schema,
|
|
2341
|
+
session,
|
|
2342
|
+
preview: await this.getLaunchModelPreview(session)
|
|
2343
|
+
}) : null;
|
|
2344
|
+
await this.sendHtmlToChat(
|
|
2345
|
+
target.chatId,
|
|
2346
|
+
target.messageThreadId,
|
|
2347
|
+
escapeTelegramHtml(
|
|
2348
|
+
[
|
|
2349
|
+
buildLaunchReview({ launcher, session }),
|
|
2350
|
+
...modelSummary ? ["", modelSummary] : []
|
|
2351
|
+
].join("\n")
|
|
2352
|
+
),
|
|
2353
|
+
this.buildLaunchConfirmationKeyboard(sessionKey, Boolean(modelSummary))
|
|
2354
|
+
);
|
|
2355
|
+
}
|
|
2356
|
+
async prepareLaunchSession(session, launcher) {
|
|
2357
|
+
let resolved;
|
|
2358
|
+
try {
|
|
2359
|
+
resolved = await this.input.deps.launcherService.resolveUiLauncher(
|
|
2360
|
+
launcher.id,
|
|
2361
|
+
buildLaunchInput(session)
|
|
2362
|
+
);
|
|
2363
|
+
} catch (error) {
|
|
2364
|
+
this.logError(error, "Failed to resolve Telegram launcher input");
|
|
2365
|
+
return {
|
|
2366
|
+
ok: false,
|
|
2367
|
+
message: "Couldn't validate launcher input. Try again or send /cancel.",
|
|
2368
|
+
reprompt: false
|
|
2369
|
+
};
|
|
2370
|
+
}
|
|
2371
|
+
if (!resolved.ok) {
|
|
2372
|
+
const field = moveLaunchSessionToValidationField(session, launcher, resolved.errors);
|
|
2373
|
+
return {
|
|
2374
|
+
ok: false,
|
|
2375
|
+
message: resolved.errors.map((error) => error.message).join("\n") || "Launcher input is invalid.",
|
|
2376
|
+
reprompt: Boolean(field)
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
let prepared;
|
|
2380
|
+
try {
|
|
2381
|
+
prepared = await this.input.deps.launchPlans.prepare(resolved.launcher.launchPlan, {
|
|
2382
|
+
...session.modelConfigTouched ? { modelConfig: buildLaunchModelConfig(session), replaceModelConfig: true } : {}
|
|
2383
|
+
});
|
|
2384
|
+
} catch (error) {
|
|
2385
|
+
this.logError(error, "Failed to prepare Telegram launch plan");
|
|
2386
|
+
return {
|
|
2387
|
+
ok: false,
|
|
2388
|
+
message: "Couldn't prepare this launch. Try again or send /cancel.",
|
|
2389
|
+
reprompt: false
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2392
|
+
if (!prepared.ok) {
|
|
2393
|
+
return {
|
|
2394
|
+
ok: false,
|
|
2395
|
+
message: prepared.errors.map((error) => error.message).join("\n") || "Launch configuration is invalid.",
|
|
2396
|
+
reprompt: false
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
2399
|
+
seedLaunchModelConfigFromPlan(session, prepared.launchPlan);
|
|
2400
|
+
return { ok: true, launchPlan: prepared.launchPlan };
|
|
2401
|
+
}
|
|
2402
|
+
async executeLaunchSession(sessionKey, session, target) {
|
|
2403
|
+
const { chatId, messageThreadId } = target;
|
|
2404
|
+
const launcher = this.getLauncher(session.launcherId);
|
|
2405
|
+
if (!launcher) {
|
|
2406
|
+
this.launchSessions.delete(sessionKey);
|
|
2407
|
+
await this.sendHtmlToChat(
|
|
2408
|
+
chatId,
|
|
2409
|
+
messageThreadId,
|
|
2410
|
+
"This launcher is no longer available. Send /launch to choose another."
|
|
2411
|
+
);
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
const prepared = await this.prepareLaunchSession(session, launcher);
|
|
2415
|
+
if (!prepared.ok) {
|
|
2416
|
+
await this.sendHtmlToChat(chatId, messageThreadId, escapeTelegramHtml(prepared.message));
|
|
2417
|
+
if (prepared.reprompt) await this.sendNextLaunchPrompt(sessionKey, session, target);
|
|
2418
|
+
return;
|
|
2419
|
+
}
|
|
2420
|
+
if (messageThreadId === void 0) {
|
|
2421
|
+
await this.sendHtmlToChat(
|
|
2422
|
+
chatId,
|
|
2423
|
+
messageThreadId,
|
|
2424
|
+
"Create a new forum topic first, then send /launch in that topic."
|
|
2425
|
+
);
|
|
2426
|
+
return;
|
|
2427
|
+
}
|
|
2428
|
+
let result;
|
|
2429
|
+
try {
|
|
2430
|
+
result = await this.input.deps.launchRuns.startProgrammatic(
|
|
2431
|
+
{
|
|
2432
|
+
launcherId: launcher.id,
|
|
2433
|
+
launcherInput: buildLaunchInput(session),
|
|
2434
|
+
...session.modelConfigTouched ? { modelConfig: buildLaunchModelConfig(session) } : {},
|
|
2435
|
+
processMetadata: {
|
|
2436
|
+
telegram: {
|
|
2437
|
+
launchThread: { mode: "forum_topic", chatId, messageThreadId }
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
},
|
|
2441
|
+
{
|
|
2442
|
+
actor: TELEGRAM_ACTOR,
|
|
2443
|
+
idempotencyKey: `telegram:${sessionKey}:${session.expiresAt}`
|
|
2444
|
+
}
|
|
2445
|
+
);
|
|
2446
|
+
} catch (error) {
|
|
2447
|
+
this.logError(error, "Failed to admit Telegram-launched process");
|
|
2448
|
+
await this.sendHtmlToChat(
|
|
2449
|
+
chatId,
|
|
2450
|
+
messageThreadId,
|
|
2451
|
+
"Couldn't create this process. Try again or send /cancel."
|
|
2452
|
+
);
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
if (result.process) {
|
|
2456
|
+
this.recordLaunchRecentValuesBestEffort(session);
|
|
2457
|
+
this.launchSessions.delete(sessionKey);
|
|
2458
|
+
await this.sendHtmlToChat(
|
|
2459
|
+
chatId,
|
|
2460
|
+
messageThreadId,
|
|
2461
|
+
result.error ? `\u26A0\uFE0F Process was created but launch had a follow-up problem. Web UI: ${escapeTelegramHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${result.process.id}`)}` : `\u2705 Process launched. Web UI: ${escapeTelegramHtml(`${this.input.deps.serverBaseUrl.replace(/\/$/, "")}/processes/${result.process.id}`)}`
|
|
2462
|
+
);
|
|
2463
|
+
return;
|
|
2464
|
+
}
|
|
2465
|
+
await this.sendHtmlToChat(
|
|
2466
|
+
chatId,
|
|
2467
|
+
messageThreadId,
|
|
2468
|
+
`\u26A0\uFE0F ${escapeTelegramHtml(result.error ?? "Launch failed")}`
|
|
2469
|
+
);
|
|
2470
|
+
}
|
|
2471
|
+
createLaunchCallbackCommand(command) {
|
|
2472
|
+
const token = `${Date.now().toString(36)}_${(this.nextLaunchCallbackId++).toString(36)}`;
|
|
2473
|
+
this.launchCallbacks.set(token, {
|
|
2474
|
+
command,
|
|
2475
|
+
expiresAt: Date.now() + LAUNCH_SESSION_TTL_MS
|
|
2476
|
+
});
|
|
2477
|
+
return `${LAUNCH_CALLBACK_PREFIX}${token}`;
|
|
2478
|
+
}
|
|
2479
|
+
readLaunchCallbackCommand(data) {
|
|
2480
|
+
if (!data.startsWith(LAUNCH_CALLBACK_PREFIX)) return null;
|
|
2481
|
+
const token = data.slice(LAUNCH_CALLBACK_PREFIX.length);
|
|
2482
|
+
const stored = this.launchCallbacks.get(token);
|
|
2483
|
+
if (!stored) return null;
|
|
2484
|
+
if (stored.expiresAt < Date.now()) {
|
|
2485
|
+
this.launchCallbacks.delete(token);
|
|
2486
|
+
return null;
|
|
2487
|
+
}
|
|
2488
|
+
return { token, command: stored.command };
|
|
2489
|
+
}
|
|
2490
|
+
buildLauncherListKeyboard(launchers, sessionKey) {
|
|
2491
|
+
const buttons = launchers.slice(0, MAX_LAUNCHER_BUTTONS).map((launcher) => ({
|
|
2492
|
+
text: launcher.label,
|
|
2493
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2494
|
+
kind: "select_launcher",
|
|
2495
|
+
sessionKey,
|
|
2496
|
+
launcherId: launcher.id
|
|
2497
|
+
})
|
|
2498
|
+
}));
|
|
2499
|
+
return buttons.length ? { inlineKeyboard: rows(buttons, 1) } : void 0;
|
|
2500
|
+
}
|
|
2501
|
+
buildLaunchConfirmationKeyboard(sessionKey, includeModelControls) {
|
|
2502
|
+
return {
|
|
2503
|
+
inlineKeyboard: [
|
|
2504
|
+
[
|
|
2505
|
+
{
|
|
2506
|
+
text: "Start process",
|
|
2507
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2508
|
+
kind: "confirm_launch",
|
|
2509
|
+
sessionKey
|
|
2510
|
+
})
|
|
2511
|
+
},
|
|
2512
|
+
{
|
|
2513
|
+
text: "Cancel",
|
|
2514
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2515
|
+
kind: "cancel_launch",
|
|
2516
|
+
sessionKey
|
|
2517
|
+
})
|
|
2518
|
+
}
|
|
2519
|
+
],
|
|
2520
|
+
...includeModelControls ? [
|
|
2521
|
+
[
|
|
2522
|
+
{
|
|
2523
|
+
text: "Change models",
|
|
2524
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2525
|
+
kind: "edit_models",
|
|
2526
|
+
sessionKey
|
|
2527
|
+
})
|
|
2528
|
+
}
|
|
2529
|
+
]
|
|
2530
|
+
] : []
|
|
2531
|
+
]
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
buildLaunchModelReplyMarkup(input) {
|
|
2535
|
+
const buttons = [];
|
|
2536
|
+
for (const profile of input.schema.availableProfiles.slice(0, MAX_MODEL_PROFILE_BUTTONS)) {
|
|
2537
|
+
buttons.push({
|
|
2538
|
+
text: profile.id,
|
|
2539
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2540
|
+
kind: "model_step",
|
|
2541
|
+
sessionKey: input.sessionKey,
|
|
2542
|
+
stepKey: input.step.key,
|
|
2543
|
+
action: "set",
|
|
2544
|
+
value: profile.id
|
|
2545
|
+
})
|
|
2546
|
+
});
|
|
2547
|
+
}
|
|
2548
|
+
buttons.push(
|
|
2549
|
+
{
|
|
2550
|
+
text: "Inherit",
|
|
2551
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2552
|
+
kind: "model_step",
|
|
2553
|
+
sessionKey: input.sessionKey,
|
|
2554
|
+
stepKey: input.step.key,
|
|
2555
|
+
action: "inherit"
|
|
2556
|
+
})
|
|
2557
|
+
},
|
|
2558
|
+
{
|
|
2559
|
+
text: "Keep current",
|
|
2560
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2561
|
+
kind: "model_step",
|
|
2562
|
+
sessionKey: input.sessionKey,
|
|
2563
|
+
stepKey: input.step.key,
|
|
2564
|
+
action: "skip"
|
|
2565
|
+
})
|
|
2566
|
+
},
|
|
2567
|
+
{
|
|
2568
|
+
text: "Done",
|
|
2569
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2570
|
+
kind: "finish_model_edit",
|
|
2571
|
+
sessionKey: input.sessionKey
|
|
2572
|
+
})
|
|
2573
|
+
}
|
|
2574
|
+
);
|
|
2575
|
+
return { inlineKeyboard: rows(buttons, 1) };
|
|
2576
|
+
}
|
|
2577
|
+
buildLaunchFieldReplyMarkup(input) {
|
|
2578
|
+
const buttons = [];
|
|
2579
|
+
if (input.fieldKind === "boolean") {
|
|
2580
|
+
buttons.push(
|
|
2581
|
+
{
|
|
2582
|
+
text: "Yes",
|
|
2583
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2584
|
+
kind: "field_value",
|
|
2585
|
+
sessionKey: input.sessionKey,
|
|
2586
|
+
fieldId: input.fieldId,
|
|
2587
|
+
value: true
|
|
2588
|
+
})
|
|
2589
|
+
},
|
|
2590
|
+
{
|
|
2591
|
+
text: "No",
|
|
2592
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2593
|
+
kind: "field_value",
|
|
2594
|
+
sessionKey: input.sessionKey,
|
|
2595
|
+
fieldId: input.fieldId,
|
|
2596
|
+
value: false
|
|
2597
|
+
})
|
|
2598
|
+
}
|
|
2599
|
+
);
|
|
2600
|
+
} else if (input.fieldKind === "select") {
|
|
2601
|
+
for (const option of input.options.slice(0, MAX_FIELD_OPTION_BUTTONS)) {
|
|
2602
|
+
buttons.push({
|
|
2603
|
+
text: option.label,
|
|
2604
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2605
|
+
kind: "field_value",
|
|
2606
|
+
sessionKey: input.sessionKey,
|
|
2607
|
+
fieldId: input.fieldId,
|
|
2608
|
+
value: option.value
|
|
2609
|
+
})
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
} else {
|
|
2613
|
+
for (const value of input.recentValues.slice(0, MAX_FIELD_OPTION_BUTTONS)) {
|
|
2614
|
+
buttons.push({
|
|
2615
|
+
text: this.formatRecentValueButtonText(value),
|
|
2616
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2617
|
+
kind: "field_value",
|
|
2618
|
+
sessionKey: input.sessionKey,
|
|
2619
|
+
fieldId: input.fieldId,
|
|
2620
|
+
value
|
|
2621
|
+
})
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
const hasCurrentValue = typeof input.currentValue === "boolean" || typeof input.currentValue === "number" && Number.isFinite(input.currentValue) || typeof input.currentValue === "string" && input.currentValue.trim() !== "";
|
|
2626
|
+
if (input.fieldKind !== "boolean" && input.fieldKind !== "select" && input.required && !hasCurrentValue && buttons.length === 0) {
|
|
2627
|
+
return {
|
|
2628
|
+
forceReply: true,
|
|
2629
|
+
selective: true,
|
|
2630
|
+
inputFieldPlaceholder: "Reply with this field value"
|
|
2631
|
+
};
|
|
2632
|
+
}
|
|
2633
|
+
if (!input.required || hasCurrentValue) {
|
|
2634
|
+
buttons.push({
|
|
2635
|
+
text: hasCurrentValue ? "Use default" : "Skip",
|
|
2636
|
+
callbackData: this.createLaunchCallbackCommand({
|
|
2637
|
+
kind: "skip_field",
|
|
2638
|
+
sessionKey: input.sessionKey,
|
|
2639
|
+
fieldId: input.fieldId
|
|
2640
|
+
})
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
2643
|
+
if (buttons.length > 0) return { inlineKeyboard: rows(buttons, 1) };
|
|
2644
|
+
return {
|
|
2645
|
+
forceReply: true,
|
|
2646
|
+
selective: true,
|
|
2647
|
+
inputFieldPlaceholder: "Reply with this field value"
|
|
2648
|
+
};
|
|
2649
|
+
}
|
|
2650
|
+
formatRecentValueButtonText(value) {
|
|
2651
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
2652
|
+
return normalized.length > 56 ? `${normalized.slice(0, 55)}\u2026` : normalized;
|
|
2653
|
+
}
|
|
2654
|
+
buildActionFormFieldReplyMarkup(session, field) {
|
|
2655
|
+
if (!canSkipActionFormField(field)) {
|
|
2656
|
+
return void 0;
|
|
2657
|
+
}
|
|
2658
|
+
return {
|
|
2659
|
+
inlineKeyboard: [
|
|
2660
|
+
[
|
|
2661
|
+
{
|
|
2662
|
+
text: "Skip",
|
|
2663
|
+
callbackData: `fs:${session.instanceId}:${session.sessionId}:${field.id}`
|
|
2664
|
+
}
|
|
2665
|
+
]
|
|
2666
|
+
]
|
|
2667
|
+
};
|
|
2668
|
+
}
|
|
2669
|
+
async sendActionFormFieldPrompt(thread, session, field, prompt = buildFieldPrompt(field)) {
|
|
2670
|
+
await this.sendHtml(
|
|
2671
|
+
thread,
|
|
2672
|
+
escapeTelegramHtml(prompt),
|
|
2673
|
+
this.buildActionFormFieldReplyMarkup(session, field)
|
|
2674
|
+
);
|
|
2675
|
+
}
|
|
2676
|
+
async executeCallbackCommand(instanceId, command) {
|
|
2677
|
+
const process2 = this.input.deps.processes.getById(instanceId);
|
|
2678
|
+
if (!process2) return;
|
|
2679
|
+
const thread = this.store.getByInstanceId(process2.id);
|
|
2680
|
+
if (!thread) return;
|
|
2681
|
+
const key = threadKey(thread.chatId, thread.messageThreadId);
|
|
2682
|
+
switch (command.kind) {
|
|
2683
|
+
case "process_action": {
|
|
2684
|
+
if (process2.lifecycleStatus !== "waiting") {
|
|
2685
|
+
await this.sendHtml(
|
|
2686
|
+
thread,
|
|
2687
|
+
"That action is no longer available. Use /actions to refresh."
|
|
2688
|
+
);
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
const action = this.input.deps.processActions.listVisibleActions(process2.id).find((candidate) => candidate.id === command.actionId);
|
|
2692
|
+
if (!action) {
|
|
2693
|
+
await this.sendHtml(
|
|
2694
|
+
thread,
|
|
2695
|
+
"That action is no longer available. Use /actions to refresh."
|
|
2696
|
+
);
|
|
2697
|
+
return;
|
|
2698
|
+
}
|
|
2699
|
+
if (action.form?.fields.length) {
|
|
2700
|
+
const session = buildActionFormSession({
|
|
2701
|
+
instanceId: process2.id,
|
|
2702
|
+
actionId: action.id,
|
|
2703
|
+
actionLabel: action.label,
|
|
2704
|
+
actionPreview: readActionPreview(action),
|
|
2705
|
+
sessionId: createActionFormSessionId(),
|
|
2706
|
+
form: action.form
|
|
2707
|
+
});
|
|
2708
|
+
this.sessions.set(key, session);
|
|
2709
|
+
const field = currentField(session);
|
|
2710
|
+
if (field) await this.sendActionFormFieldPrompt(thread, session, field);
|
|
2711
|
+
return;
|
|
2712
|
+
}
|
|
2713
|
+
await this.maybeSelectActionModel({
|
|
2714
|
+
instanceId: process2.id,
|
|
2715
|
+
action,
|
|
2716
|
+
formValues: {},
|
|
2717
|
+
sessionKey: key,
|
|
2718
|
+
thread
|
|
2719
|
+
});
|
|
2720
|
+
return;
|
|
2721
|
+
}
|
|
2722
|
+
case "action_form_skip": {
|
|
2723
|
+
await this.skipCurrentActionFormField(key, command.sessionId, command.fieldId, thread);
|
|
2724
|
+
return;
|
|
2725
|
+
}
|
|
2726
|
+
case "action_model_select": {
|
|
2727
|
+
const modelSession = this.sessions.get(key);
|
|
2728
|
+
const modelProfile = resolveModelProfileFromSession(modelSession, command.profileIndex);
|
|
2729
|
+
if (!modelProfile) {
|
|
2730
|
+
await this.sendHtml(
|
|
2731
|
+
thread,
|
|
2732
|
+
"That model option is no longer available. Use /actions to start again."
|
|
2733
|
+
);
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
if (modelSession?.kind === "recovery_model") {
|
|
2737
|
+
await this.executeRecoveryModelSession(key, modelSession, thread, {
|
|
2738
|
+
nextTurnModelProfileId: modelProfile.id
|
|
2739
|
+
});
|
|
2740
|
+
return;
|
|
2741
|
+
}
|
|
2742
|
+
await this.handleActionModelSelect(key, command.sessionId, modelProfile.id, thread);
|
|
2743
|
+
return;
|
|
2744
|
+
}
|
|
2745
|
+
case "action_model_skip": {
|
|
2746
|
+
const modelSession = this.sessions.get(key);
|
|
2747
|
+
if (modelSession?.kind === "recovery_model") {
|
|
2748
|
+
await this.executeRecoveryModelSession(key, modelSession, thread);
|
|
2749
|
+
return;
|
|
2750
|
+
}
|
|
2751
|
+
await this.handleActionModelSkip(key, command.sessionId, thread);
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2754
|
+
case "retry": {
|
|
2755
|
+
await this.maybeSelectRecoveryModel({
|
|
2756
|
+
instanceId: process2.id,
|
|
2757
|
+
recoveryKind: "retry",
|
|
2758
|
+
sessionKey: key,
|
|
2759
|
+
thread,
|
|
2760
|
+
execute: (opts) => this.input.deps.commands.retryProcess(process2.id, {
|
|
2761
|
+
...opts?.nextTurnModelProfileId !== void 0 ? opts : {},
|
|
2762
|
+
actor: TELEGRAM_ACTOR
|
|
2763
|
+
}).then((result) => {
|
|
2764
|
+
this.sendCommandResult(thread, result, "Retry started.", "Retry failed");
|
|
2765
|
+
})
|
|
2766
|
+
});
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
case "continue": {
|
|
2770
|
+
const turnRecordId = continuableFailedTurnRecordId(process2);
|
|
2771
|
+
if (!turnRecordId) {
|
|
2772
|
+
await this.sendHtml(thread, "No failed turn is available to continue.");
|
|
2773
|
+
return;
|
|
2774
|
+
}
|
|
2775
|
+
await this.maybeSelectRecoveryModel({
|
|
2776
|
+
instanceId: process2.id,
|
|
2777
|
+
recoveryKind: "continue",
|
|
2778
|
+
turnRecordId,
|
|
2779
|
+
sessionKey: key,
|
|
2780
|
+
thread,
|
|
2781
|
+
execute: (opts) => {
|
|
2782
|
+
const session = buildContinueSession({
|
|
2783
|
+
instanceId: process2.id,
|
|
2784
|
+
turnRecordId,
|
|
2785
|
+
nextTurnModelProfileId: opts?.nextTurnModelProfileId
|
|
31
2786
|
});
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
2787
|
+
this.sessions.set(key, session);
|
|
2788
|
+
this.sendCurrentSessionPrompt(thread, session);
|
|
2789
|
+
}
|
|
2790
|
+
});
|
|
2791
|
+
return;
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
async sendCurrentSessionPrompt(thread, session) {
|
|
2796
|
+
if (session.kind === "continue") {
|
|
2797
|
+
await this.sendHtml(thread, CONTINUE_PROMPT);
|
|
2798
|
+
return true;
|
|
2799
|
+
}
|
|
2800
|
+
if (session.kind === "question") {
|
|
2801
|
+
await this.sendHtml(thread, escapeTelegramHtml(buildQuestionPrompt(session)));
|
|
2802
|
+
return true;
|
|
2803
|
+
}
|
|
2804
|
+
if (session.kind === "action_model" || session.kind === "recovery_model") {
|
|
2805
|
+
await this.sendModelPrompt(thread, session);
|
|
2806
|
+
return true;
|
|
2807
|
+
}
|
|
2808
|
+
const field = currentField(session);
|
|
2809
|
+
if (!field) return false;
|
|
2810
|
+
await this.sendActionFormFieldPrompt(thread, session, field);
|
|
2811
|
+
return true;
|
|
2812
|
+
}
|
|
2813
|
+
async maybeSelectActionModel(input) {
|
|
2814
|
+
const fallback = () => this.executeProcessAction(
|
|
2815
|
+
input.instanceId,
|
|
2816
|
+
{ id: input.action.id, label: input.action.label, preview: input.action.preview },
|
|
2817
|
+
input.formValues,
|
|
2818
|
+
input.thread
|
|
2819
|
+
);
|
|
2820
|
+
try {
|
|
2821
|
+
const profiles = this.listSelectableProfiles(input.instanceId);
|
|
2822
|
+
if (!profiles.length) return fallback();
|
|
2823
|
+
const result = await this.processModelSelection?.preview(
|
|
2824
|
+
input.instanceId,
|
|
2825
|
+
input.action.id,
|
|
2826
|
+
input.formValues
|
|
2827
|
+
);
|
|
2828
|
+
if (!result) return fallback();
|
|
2829
|
+
if (result.kind === "operational_failure") {
|
|
2830
|
+
this.input.logger?.warn?.(
|
|
2831
|
+
{ code: result.code },
|
|
2832
|
+
"Action model preview unavailable; falling back to direct execution"
|
|
2833
|
+
);
|
|
2834
|
+
return fallback();
|
|
2835
|
+
}
|
|
2836
|
+
if (result.kind !== "llm_turn") return fallback();
|
|
2837
|
+
const sessionId = createActionFormSessionId();
|
|
2838
|
+
const session = buildActionModelSession({
|
|
2839
|
+
instanceId: input.instanceId,
|
|
2840
|
+
actionId: input.action.id,
|
|
2841
|
+
actionLabel: input.action.label,
|
|
2842
|
+
actionPreview: input.action.preview,
|
|
2843
|
+
sessionId,
|
|
2844
|
+
formValues: input.formValues,
|
|
2845
|
+
preview: result,
|
|
2846
|
+
profiles
|
|
2847
|
+
});
|
|
2848
|
+
this.sessions.set(input.sessionKey, session);
|
|
2849
|
+
await this.sendModelPrompt(input.thread, session);
|
|
2850
|
+
} catch (error) {
|
|
2851
|
+
this.logError(error, "Action model preview failed; falling back to direct execution");
|
|
2852
|
+
return fallback();
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
async resolveActionModelSession(sessionKey, sessionId, thread) {
|
|
2856
|
+
const session = this.sessions.get(sessionKey);
|
|
2857
|
+
if (!session || session.kind !== "action_model" || session.sessionId !== sessionId) {
|
|
2858
|
+
await this.sendHtml(thread, "That model selection expired. Use /actions to start again.");
|
|
2859
|
+
return null;
|
|
2860
|
+
}
|
|
2861
|
+
if (session.expiresAt < Date.now()) {
|
|
2862
|
+
this.sessions.delete(sessionKey);
|
|
2863
|
+
await this.sendHtml(thread, "That model selection expired. Use /actions to start again.");
|
|
2864
|
+
return null;
|
|
2865
|
+
}
|
|
2866
|
+
this.sessions.delete(sessionKey);
|
|
2867
|
+
return session;
|
|
2868
|
+
}
|
|
2869
|
+
executeActionModelSession(session, thread, opts) {
|
|
2870
|
+
return this.executeProcessAction(
|
|
2871
|
+
session.instanceId,
|
|
2872
|
+
{ id: session.actionId, label: session.actionLabel, preview: session.actionPreview },
|
|
2873
|
+
session.formValues,
|
|
2874
|
+
thread,
|
|
2875
|
+
opts
|
|
2876
|
+
);
|
|
2877
|
+
}
|
|
2878
|
+
async sendActionModelSwitchWarning(session, effectiveModelProfileId, thread) {
|
|
2879
|
+
if (!effectiveModelProfileId) return;
|
|
2880
|
+
const warning = buildActionModelSwitchWarning({ session, effectiveModelProfileId });
|
|
2881
|
+
if (warning) await this.sendHtml(thread, escapeTelegramHtml(warning));
|
|
2882
|
+
}
|
|
2883
|
+
async handleActionModelSelect(sessionKey, sessionId, modelProfileId, thread) {
|
|
2884
|
+
const session = await this.resolveActionModelSession(sessionKey, sessionId, thread);
|
|
2885
|
+
if (!session) return;
|
|
2886
|
+
await this.sendActionModelSwitchWarning(session, modelProfileId, thread);
|
|
2887
|
+
await this.executeActionModelSession(session, thread, {
|
|
2888
|
+
nextTurnModelProfileId: modelProfileId
|
|
2889
|
+
});
|
|
2890
|
+
}
|
|
2891
|
+
async handleActionModelSkip(sessionKey, sessionId, thread) {
|
|
2892
|
+
const session = await this.resolveActionModelSession(sessionKey, sessionId, thread);
|
|
2893
|
+
if (!session) return;
|
|
2894
|
+
const resolved = session.preview.resolvedModel;
|
|
2895
|
+
await this.sendActionModelSwitchWarning(
|
|
2896
|
+
session,
|
|
2897
|
+
resolved?.status === "resolved" ? resolved.modelProfileId : null,
|
|
2898
|
+
thread
|
|
2899
|
+
);
|
|
2900
|
+
await this.executeActionModelSession(session, thread);
|
|
2901
|
+
}
|
|
2902
|
+
async sendModelPrompt(thread, session, error = "") {
|
|
2903
|
+
const prompt = session.kind === "action_model" ? buildActionModelPrompt({ session }) : buildRecoveryModelPrompt({ session });
|
|
2904
|
+
await this.sendHtml(
|
|
2905
|
+
thread,
|
|
2906
|
+
escapeTelegramHtml(`${error}${prompt}`),
|
|
2907
|
+
this.buildModelReplyMarkup(session)
|
|
2908
|
+
);
|
|
2909
|
+
}
|
|
2910
|
+
buildModelReplyMarkup(session) {
|
|
2911
|
+
const buttons = [];
|
|
2912
|
+
let index = 0;
|
|
2913
|
+
for (const profile of session.profiles.slice(0, 20)) {
|
|
2914
|
+
index += 1;
|
|
2915
|
+
const switchesModel = session.kind === "action_model" && buildActionModelSwitchWarning({
|
|
2916
|
+
session,
|
|
2917
|
+
effectiveModelProfileId: profile.id
|
|
2918
|
+
});
|
|
2919
|
+
buttons.push({
|
|
2920
|
+
text: `${switchesModel ? "\u26A0 " : ""}${profile.id}`,
|
|
2921
|
+
callbackData: `ams:${session.instanceId}:${session.sessionId}:${index}`
|
|
2922
|
+
});
|
|
2923
|
+
}
|
|
2924
|
+
const resolved = session.kind === "action_model" ? session.preview.resolvedModel : null;
|
|
2925
|
+
const resolvedProfileId = resolved?.status === "resolved" ? resolved.modelProfileId : null;
|
|
2926
|
+
const keepingCurrentSwitchesModel = session.kind === "action_model" && resolvedProfileId ? buildActionModelSwitchWarning({ session, effectiveModelProfileId: resolvedProfileId }) : null;
|
|
2927
|
+
buttons.push({
|
|
2928
|
+
text: `${keepingCurrentSwitchesModel ? "\u26A0 " : ""}Keep current`,
|
|
2929
|
+
callbackData: `amk:${session.instanceId}:${session.sessionId}`
|
|
2930
|
+
});
|
|
2931
|
+
return { inlineKeyboard: rows(buttons, 1) };
|
|
2932
|
+
}
|
|
2933
|
+
async applyActionFormStep(key, session, step, thread) {
|
|
2934
|
+
if (!step.ok || !step.done) {
|
|
2935
|
+
const field = currentField(session);
|
|
2936
|
+
if (field) {
|
|
2937
|
+
await this.sendActionFormFieldPrompt(thread, session, field, step.prompt);
|
|
2938
|
+
} else {
|
|
2939
|
+
await this.sendHtml(thread, escapeTelegramHtml(step.prompt));
|
|
2940
|
+
}
|
|
2941
|
+
return;
|
|
2942
|
+
}
|
|
2943
|
+
this.sessions.delete(key);
|
|
2944
|
+
await this.maybeSelectActionModel({
|
|
2945
|
+
instanceId: session.instanceId,
|
|
2946
|
+
action: {
|
|
2947
|
+
id: session.actionId,
|
|
2948
|
+
label: session.actionLabel,
|
|
2949
|
+
form: session.form,
|
|
2950
|
+
preview: session.actionPreview
|
|
2951
|
+
},
|
|
2952
|
+
formValues: step.values,
|
|
2953
|
+
sessionKey: key,
|
|
2954
|
+
thread
|
|
2955
|
+
});
|
|
2956
|
+
}
|
|
2957
|
+
async skipCurrentActionFormField(key, sessionId, fieldId, thread) {
|
|
2958
|
+
const session = this.sessions.get(key);
|
|
2959
|
+
if (!session || session.kind !== "action_form") {
|
|
2960
|
+
await this.sendHtml(thread, "This form prompt expired. Use /actions to start again.");
|
|
2961
|
+
return;
|
|
2962
|
+
}
|
|
2963
|
+
if (session.expiresAt < Date.now()) {
|
|
2964
|
+
this.sessions.delete(key);
|
|
2965
|
+
await this.sendHtml(thread, "This form prompt expired. Use /actions to start again.");
|
|
2966
|
+
return;
|
|
2967
|
+
}
|
|
2968
|
+
const field = currentField(session);
|
|
2969
|
+
if (session.sessionId !== sessionId || !field || field.id !== fieldId) {
|
|
2970
|
+
await this.sendHtml(
|
|
2971
|
+
thread,
|
|
2972
|
+
"That skip button is stale. Continue with the latest prompt or send /cancel."
|
|
2973
|
+
);
|
|
2974
|
+
return;
|
|
2975
|
+
}
|
|
2976
|
+
if (!canSkipActionFormField(field)) {
|
|
2977
|
+
await this.sendActionFormFieldPrompt(
|
|
2978
|
+
thread,
|
|
2979
|
+
session,
|
|
2980
|
+
field,
|
|
2981
|
+
`${field.label} is required and cannot be skipped.
|
|
2982
|
+
${buildFieldPrompt(field)}`
|
|
2983
|
+
);
|
|
2984
|
+
return;
|
|
2985
|
+
}
|
|
2986
|
+
await this.applyActionFormStep(key, session, applyFormSkip(session), thread);
|
|
2987
|
+
}
|
|
2988
|
+
async handleSessionText(key, session, text, thread, name) {
|
|
2989
|
+
if (session.expiresAt < Date.now()) {
|
|
2990
|
+
this.sessions.delete(key);
|
|
2991
|
+
await this.sendHtml(thread, "This prompt expired. Use /actions to start again.");
|
|
2992
|
+
return;
|
|
2993
|
+
}
|
|
2994
|
+
if (session.kind === "continue") {
|
|
2995
|
+
const prompt = name === "skip" ? null : text;
|
|
2996
|
+
this.sessions.delete(key);
|
|
2997
|
+
const result = await this.input.deps.commands.continueFailedTurn(
|
|
2998
|
+
session.instanceId,
|
|
2999
|
+
session.turnRecordId,
|
|
3000
|
+
{
|
|
3001
|
+
prompt,
|
|
3002
|
+
...session.nextTurnModelProfileId !== void 0 && session.nextTurnModelProfileId !== null ? { nextTurnModelProfileId: session.nextTurnModelProfileId } : {},
|
|
3003
|
+
actor: TELEGRAM_ACTOR
|
|
3004
|
+
}
|
|
3005
|
+
);
|
|
3006
|
+
await this.sendCommandResult(thread, result, "Continue started.", "Continue failed");
|
|
3007
|
+
return;
|
|
3008
|
+
}
|
|
3009
|
+
if (session.kind === "question") {
|
|
3010
|
+
if (name) {
|
|
3011
|
+
await this.sendHtml(thread, escapeTelegramHtml(buildQuestionPrompt(session)));
|
|
3012
|
+
return;
|
|
3013
|
+
}
|
|
3014
|
+
const step = applyQuestionText(session, text);
|
|
3015
|
+
if (!step.done) {
|
|
3016
|
+
await this.sendHtml(thread, escapeTelegramHtml(step.prompt ?? buildQuestionPrompt(session)));
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
const service = this.input.deps.processQuestions;
|
|
3020
|
+
const result = service ? await service.submitAnswers(
|
|
3021
|
+
session.instanceId,
|
|
3022
|
+
session.request.id,
|
|
3023
|
+
step.draft,
|
|
3024
|
+
TELEGRAM_ACTOR
|
|
3025
|
+
) : { ok: false, message: "Answers cannot be submitted through Telegram." };
|
|
3026
|
+
this.sessions.delete(key);
|
|
3027
|
+
await this.sendHtml(
|
|
3028
|
+
thread,
|
|
3029
|
+
result.ok ? "\u2705 Answers sent. The active turn is continuing." : escapeTelegramHtml(result.message)
|
|
3030
|
+
);
|
|
3031
|
+
return;
|
|
3032
|
+
}
|
|
3033
|
+
if (session.kind === "action_model" || session.kind === "recovery_model") {
|
|
3034
|
+
if (name === "skip") {
|
|
3035
|
+
if (session.kind === "action_model") {
|
|
3036
|
+
await this.handleActionModelSkip(key, session.sessionId, thread);
|
|
3037
|
+
} else {
|
|
3038
|
+
await this.executeRecoveryModelSession(key, session, thread);
|
|
3039
|
+
}
|
|
3040
|
+
return;
|
|
3041
|
+
}
|
|
3042
|
+
if (name === "cancel") {
|
|
3043
|
+
this.sessions.delete(key);
|
|
3044
|
+
await this.sendHtml(thread, "Cancelled.");
|
|
3045
|
+
return;
|
|
3046
|
+
}
|
|
3047
|
+
await this.handleModelText(key, session, text, thread);
|
|
3048
|
+
return;
|
|
3049
|
+
}
|
|
3050
|
+
if (name === "skip") {
|
|
3051
|
+
const field = currentField(session);
|
|
3052
|
+
if (!canSkipActionFormField(field)) {
|
|
3053
|
+
if (field) {
|
|
3054
|
+
await this.sendActionFormFieldPrompt(
|
|
3055
|
+
thread,
|
|
3056
|
+
session,
|
|
3057
|
+
field,
|
|
3058
|
+
`${field.label} is required and cannot be skipped.
|
|
3059
|
+
${buildFieldPrompt(field)}`
|
|
3060
|
+
);
|
|
3061
|
+
}
|
|
3062
|
+
return;
|
|
3063
|
+
}
|
|
3064
|
+
await this.applyActionFormStep(key, session, applyFormSkip(session), thread);
|
|
3065
|
+
return;
|
|
3066
|
+
}
|
|
3067
|
+
await this.applyActionFormStep(key, session, applyFormText(session, text), thread);
|
|
3068
|
+
}
|
|
3069
|
+
async handleModelText(sessionKey, session, text, thread) {
|
|
3070
|
+
const profile = resolveProfileByTextOrIndex(text.trim(), session.profiles);
|
|
3071
|
+
if (!profile) {
|
|
3072
|
+
await this.sendModelPrompt(thread, session, "Model must match an available profile.\n");
|
|
3073
|
+
return;
|
|
3074
|
+
}
|
|
3075
|
+
if (session.kind === "action_model") {
|
|
3076
|
+
this.sessions.delete(sessionKey);
|
|
3077
|
+
await this.sendActionModelSwitchWarning(session, profile.id, thread);
|
|
3078
|
+
return this.executeActionModelSession(session, thread, {
|
|
3079
|
+
nextTurnModelProfileId: profile.id
|
|
3080
|
+
});
|
|
3081
|
+
}
|
|
3082
|
+
await this.executeRecoveryModelSession(sessionKey, session, thread, {
|
|
3083
|
+
nextTurnModelProfileId: profile.id
|
|
3084
|
+
});
|
|
3085
|
+
}
|
|
3086
|
+
async maybeSelectRecoveryModel(input) {
|
|
3087
|
+
try {
|
|
3088
|
+
const profiles = this.listSelectableProfiles(input.instanceId);
|
|
3089
|
+
if (!profiles.length) return input.execute();
|
|
3090
|
+
const sessionId = createActionFormSessionId();
|
|
3091
|
+
const session = buildRecoveryModelSession({
|
|
3092
|
+
instanceId: input.instanceId,
|
|
3093
|
+
recoveryKind: input.recoveryKind,
|
|
3094
|
+
turnRecordId: input.turnRecordId,
|
|
3095
|
+
sessionId,
|
|
3096
|
+
profiles
|
|
3097
|
+
});
|
|
3098
|
+
this.sessions.set(input.sessionKey, session);
|
|
3099
|
+
await this.sendModelPrompt(input.thread, session);
|
|
3100
|
+
} catch (error) {
|
|
3101
|
+
this.logError(error, "Recovery model selection failed; falling back to direct execution");
|
|
3102
|
+
return input.execute();
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
3105
|
+
async executeRecoveryModelSession(sessionKey, session, thread, opts) {
|
|
3106
|
+
this.sessions.delete(sessionKey);
|
|
3107
|
+
if (session.recoveryKind === "retry") {
|
|
3108
|
+
const retryOpts = {
|
|
3109
|
+
...opts?.nextTurnModelProfileId !== void 0 ? opts : {},
|
|
3110
|
+
actor: TELEGRAM_ACTOR
|
|
3111
|
+
};
|
|
3112
|
+
void this.input.deps.commands.retryProcess(session.instanceId, retryOpts).then((result) => {
|
|
3113
|
+
this.sendCommandResult(thread, result, "Retry started.", "Retry failed");
|
|
3114
|
+
});
|
|
3115
|
+
} else {
|
|
3116
|
+
const continueSession = buildContinueSession({
|
|
3117
|
+
instanceId: session.instanceId,
|
|
3118
|
+
turnRecordId: session.turnRecordId ?? "",
|
|
3119
|
+
nextTurnModelProfileId: opts?.nextTurnModelProfileId
|
|
3120
|
+
});
|
|
3121
|
+
const key = threadKey(thread.chatId, thread.messageThreadId);
|
|
3122
|
+
this.sessions.set(key, continueSession);
|
|
3123
|
+
await this.sendCurrentSessionPrompt(thread, continueSession);
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
async executeProcessAction(instanceId, action, input, thread, opts) {
|
|
3127
|
+
const executeOpts = {
|
|
3128
|
+
source: "ui",
|
|
3129
|
+
origin: "external_interface",
|
|
3130
|
+
actor: TELEGRAM_ACTOR
|
|
3131
|
+
};
|
|
3132
|
+
if (opts?.nextTurnModelProfileId !== void 0) {
|
|
3133
|
+
executeOpts.nextTurnModelProfileId = opts.nextTurnModelProfileId;
|
|
3134
|
+
}
|
|
3135
|
+
const result = await this.input.deps.processActions.executeAction(
|
|
3136
|
+
instanceId,
|
|
3137
|
+
action.id,
|
|
3138
|
+
input,
|
|
3139
|
+
executeOpts
|
|
3140
|
+
);
|
|
3141
|
+
await this.sendCommandResult(
|
|
3142
|
+
thread,
|
|
3143
|
+
result,
|
|
3144
|
+
buildActionSubmittedMessage({ action, values: input }),
|
|
3145
|
+
`Action failed: ${action.label}`
|
|
3146
|
+
);
|
|
3147
|
+
}
|
|
3148
|
+
async sendCommandResult(thread, result, successText, fallbackError) {
|
|
3149
|
+
await this.sendHtml(
|
|
3150
|
+
thread,
|
|
3151
|
+
result.ok ? successText : `\u26A0\uFE0F ${escapeTelegramHtml(result.error ?? result.message ?? fallbackError)}`
|
|
3152
|
+
);
|
|
3153
|
+
}
|
|
3154
|
+
isAllowed(from) {
|
|
3155
|
+
return typeof from?.id === "number" && this.input.config.allowUserIds.includes(from.id);
|
|
3156
|
+
}
|
|
3157
|
+
async sendHtml(thread, text, replyMarkup) {
|
|
3158
|
+
await this.sendHtmlToChat(thread.chatId, thread.messageThreadId, text, replyMarkup);
|
|
3159
|
+
}
|
|
3160
|
+
async sendResultParts(thread, instanceId, turnRecordId, parts) {
|
|
3161
|
+
for (const [index, part] of parts.entries()) {
|
|
3162
|
+
if (part.kind === "html") {
|
|
3163
|
+
await this.sendHtml(thread, part.html);
|
|
3164
|
+
continue;
|
|
3165
|
+
}
|
|
3166
|
+
if (part.kind === "mermaid") {
|
|
3167
|
+
try {
|
|
3168
|
+
await this.sendPhotoWithDocumentFallback(thread, {
|
|
3169
|
+
bytes: await renderMermaidPng(part.source),
|
|
3170
|
+
filename: `diagram-${index + 1}.png`,
|
|
3171
|
+
caption: "Mermaid diagram"
|
|
3172
|
+
});
|
|
3173
|
+
} catch (error) {
|
|
3174
|
+
this.logError(error, "Telegram Mermaid rendering failed; sending diagram source");
|
|
3175
|
+
await this.sendHtml(
|
|
3176
|
+
thread,
|
|
3177
|
+
`\u26A0\uFE0F <b>Diagram could not be rendered</b>
|
|
3178
|
+
<pre><code>${escapeTelegramHtml(part.source)}</code></pre>`
|
|
3179
|
+
);
|
|
3180
|
+
}
|
|
3181
|
+
continue;
|
|
3182
|
+
}
|
|
3183
|
+
try {
|
|
3184
|
+
const bytes = await this.input.deps.resultImages?.get(
|
|
3185
|
+
instanceId,
|
|
3186
|
+
turnRecordId,
|
|
3187
|
+
part.imageId
|
|
3188
|
+
);
|
|
3189
|
+
if (!bytes) throw new Error("Managed result image is unavailable");
|
|
3190
|
+
await this.sendPhotoWithDocumentFallback(thread, {
|
|
3191
|
+
bytes,
|
|
3192
|
+
filename: part.imageId,
|
|
3193
|
+
...part.alt.trim() ? { caption: part.alt.trim().slice(0, 900) } : {}
|
|
3194
|
+
});
|
|
3195
|
+
} catch (error) {
|
|
3196
|
+
this.logError(error, "Telegram result image delivery failed");
|
|
3197
|
+
const label = part.alt.trim() || part.imageId;
|
|
3198
|
+
await this.sendHtml(thread, `\u26A0\uFE0F Image unavailable: ${escapeTelegramHtml(label)}`);
|
|
3199
|
+
}
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
async sendPhotoWithDocumentFallback(thread, file) {
|
|
3203
|
+
const input = { ...messageTarget(thread.chatId, thread.messageThreadId), ...file };
|
|
3204
|
+
try {
|
|
3205
|
+
await this.input.client.sendPhoto(input);
|
|
3206
|
+
} catch (error) {
|
|
3207
|
+
this.logError(error, "Telegram photo send failed; retrying as a document");
|
|
3208
|
+
await this.input.client.sendDocument(input);
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
async sendPlainToChat(chatId, messageThreadId, text, replyMarkup) {
|
|
3212
|
+
const chunks = splitPlainTelegramText(text, this.input.config.markdown.maxChars);
|
|
3213
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
3214
|
+
const isLast = index === chunks.length - 1;
|
|
3215
|
+
await this.input.client.sendMessage({
|
|
3216
|
+
...messageTarget(chatId, messageThreadId),
|
|
3217
|
+
text: chunk,
|
|
3218
|
+
...isLast && replyMarkup ? { replyMarkup } : {}
|
|
3219
|
+
});
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
async sendHtmlToChat(chatId, messageThreadId, text, replyMarkup) {
|
|
3223
|
+
const chunks = splitTelegramHtml(text, this.input.config.markdown.maxChars);
|
|
3224
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
3225
|
+
const isLast = index === chunks.length - 1;
|
|
3226
|
+
try {
|
|
3227
|
+
await this.input.client.sendMessage({
|
|
3228
|
+
...messageTarget(chatId, messageThreadId),
|
|
3229
|
+
text: chunk,
|
|
3230
|
+
parseMode: "HTML",
|
|
3231
|
+
...isLast && replyMarkup ? { replyMarkup } : {}
|
|
3232
|
+
});
|
|
3233
|
+
} catch (error) {
|
|
3234
|
+
this.logError(error, "Telegram HTML chunk send failed; retrying chunk as plain text");
|
|
3235
|
+
await this.sendPlainToChat(
|
|
3236
|
+
chatId,
|
|
3237
|
+
messageThreadId,
|
|
3238
|
+
telegramHtmlToPlainText(chunk),
|
|
3239
|
+
isLast ? replyMarkup : void 0
|
|
3240
|
+
);
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
logError(error, message) {
|
|
3245
|
+
this.input.logger?.warn?.(
|
|
3246
|
+
{ err: error instanceof Error ? error.message : String(error) },
|
|
3247
|
+
message
|
|
3248
|
+
);
|
|
3249
|
+
}
|
|
3250
|
+
};
|
|
3251
|
+
|
|
3252
|
+
// src/config.ts
|
|
3253
|
+
import { isUnknownRecord as isRecord2 } from "@leitwerk-dev/domain";
|
|
3254
|
+
function normalizeUserIds(value) {
|
|
3255
|
+
if (!Array.isArray(value)) return [];
|
|
3256
|
+
return [
|
|
3257
|
+
...new Set(
|
|
3258
|
+
value.map(
|
|
3259
|
+
(entry) => typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN
|
|
3260
|
+
).filter(Number.isSafeInteger)
|
|
3261
|
+
)
|
|
3262
|
+
];
|
|
3263
|
+
}
|
|
3264
|
+
function readInlineToken(raw) {
|
|
3265
|
+
return typeof raw.bot_token === "string" ? raw.bot_token.trim() : "";
|
|
3266
|
+
}
|
|
3267
|
+
function readToken(raw) {
|
|
3268
|
+
const envName = typeof raw.bot_token_env === "string" ? raw.bot_token_env.trim() : "";
|
|
3269
|
+
return envName ? process.env[envName]?.trim() ?? readInlineToken(raw) : readInlineToken(raw);
|
|
3270
|
+
}
|
|
3271
|
+
function normalizeAllowedModelProfileIds(value) {
|
|
3272
|
+
if (!Array.isArray(value)) return [];
|
|
3273
|
+
return [
|
|
3274
|
+
...new Set(
|
|
3275
|
+
value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)
|
|
3276
|
+
)
|
|
3277
|
+
];
|
|
3278
|
+
}
|
|
3279
|
+
function normalizeTelegramConfig(rawValue) {
|
|
3280
|
+
const raw = isRecord2(rawValue) ? rawValue : {};
|
|
3281
|
+
const delivery = isRecord2(raw.delivery) ? raw.delivery : {};
|
|
3282
|
+
const markdown2 = isRecord2(raw.markdown) ? raw.markdown : {};
|
|
3283
|
+
const actionModelSelection = isRecord2(raw.action_model_selection) ? raw.action_model_selection : {};
|
|
3284
|
+
const config = {
|
|
3285
|
+
enabled: raw.enabled === true,
|
|
3286
|
+
botToken: readToken(raw),
|
|
3287
|
+
allowUserIds: normalizeUserIds(raw.allow_user_ids),
|
|
3288
|
+
delivery: {
|
|
3289
|
+
forumChatId: typeof delivery.forum_chat_id === "string" ? delivery.forum_chat_id.trim() : ""
|
|
3290
|
+
},
|
|
3291
|
+
markdown: {
|
|
3292
|
+
maxChars: typeof markdown2.max_chars === "number" && Number.isSafeInteger(markdown2.max_chars) ? Math.min(Math.max(markdown2.max_chars, 500), 4096) : 3900
|
|
44
3293
|
},
|
|
3294
|
+
topicTitleTemplate: typeof raw.topic_title_template === "string" && raw.topic_title_template.trim() ? raw.topic_title_template.trim() : "{title} \xB7 {shortId}",
|
|
3295
|
+
actionModelSelection: {
|
|
3296
|
+
enabled: actionModelSelection.enabled !== false
|
|
3297
|
+
},
|
|
3298
|
+
allowedModelProfileIds: normalizeAllowedModelProfileIds(raw.allowed_model_profile_ids)
|
|
3299
|
+
};
|
|
3300
|
+
if (!config.enabled) return { ok: true, config };
|
|
3301
|
+
const errors = [];
|
|
3302
|
+
if (!config.botToken)
|
|
3303
|
+
errors.push("extensions.telegram requires bot_token_env or bot_token when enabled");
|
|
3304
|
+
if (config.allowUserIds.length === 0) {
|
|
3305
|
+
errors.push("extensions.telegram.allow_user_ids must contain at least one Telegram user id");
|
|
3306
|
+
}
|
|
3307
|
+
if (!config.delivery.forumChatId) {
|
|
3308
|
+
errors.push("extensions.telegram.delivery.forum_chat_id is required for forum topic delivery");
|
|
3309
|
+
}
|
|
3310
|
+
return errors.length ? { ok: false, errors } : { ok: true, config };
|
|
3311
|
+
}
|
|
3312
|
+
|
|
3313
|
+
// src/grammy-telegram-client.ts
|
|
3314
|
+
import { Bot, InputFile } from "grammy";
|
|
3315
|
+
|
|
3316
|
+
// src/types.ts
|
|
3317
|
+
var BaseTelegramClientEventRegistrar = class {
|
|
3318
|
+
textHandlers = /* @__PURE__ */ new Set();
|
|
3319
|
+
callbackHandlers = /* @__PURE__ */ new Set();
|
|
3320
|
+
forumTopicCreatedHandlers = /* @__PURE__ */ new Set();
|
|
3321
|
+
forumTopicClosedHandlers = /* @__PURE__ */ new Set();
|
|
3322
|
+
onText(handler) {
|
|
3323
|
+
this.textHandlers.add(handler);
|
|
3324
|
+
}
|
|
3325
|
+
onCallback(handler) {
|
|
3326
|
+
this.callbackHandlers.add(handler);
|
|
3327
|
+
}
|
|
3328
|
+
onForumTopicCreated(handler) {
|
|
3329
|
+
this.forumTopicCreatedHandlers.add(handler);
|
|
3330
|
+
}
|
|
3331
|
+
onForumTopicClosed(handler) {
|
|
3332
|
+
this.forumTopicClosedHandlers.add(handler);
|
|
3333
|
+
}
|
|
3334
|
+
};
|
|
3335
|
+
|
|
3336
|
+
// src/grammy-telegram-client.ts
|
|
3337
|
+
function toTelegramReplyMarkup(markup) {
|
|
3338
|
+
if (!markup) return void 0;
|
|
3339
|
+
if (markup.inlineKeyboard) {
|
|
3340
|
+
return {
|
|
3341
|
+
inline_keyboard: markup.inlineKeyboard.map(
|
|
3342
|
+
(row) => row.map((button) => ({ text: button.text, callback_data: button.callbackData }))
|
|
3343
|
+
)
|
|
3344
|
+
};
|
|
3345
|
+
}
|
|
3346
|
+
if (markup.forceReply) {
|
|
3347
|
+
return {
|
|
3348
|
+
force_reply: true,
|
|
3349
|
+
...markup.inputFieldPlaceholder ? { input_field_placeholder: markup.inputFieldPlaceholder } : {},
|
|
3350
|
+
...markup.selective !== void 0 ? { selective: markup.selective } : {}
|
|
3351
|
+
};
|
|
3352
|
+
}
|
|
3353
|
+
return void 0;
|
|
3354
|
+
}
|
|
3355
|
+
function toUserRef(value) {
|
|
3356
|
+
return value ? { id: value.id, ...value.username ? { username: value.username } : {} } : null;
|
|
3357
|
+
}
|
|
3358
|
+
var GrammyTelegramClient = class extends BaseTelegramClientEventRegistrar {
|
|
3359
|
+
constructor(input) {
|
|
3360
|
+
super();
|
|
3361
|
+
this.input = input;
|
|
3362
|
+
this.bot = input.botFactory?.(input.botToken) ?? new Bot(input.botToken);
|
|
3363
|
+
this.bot.on("message:text", (ctx) => this.dispatchText(ctx));
|
|
3364
|
+
this.bot.on(
|
|
3365
|
+
"message:forum_topic_created",
|
|
3366
|
+
(ctx) => this.dispatchForumTopic(ctx, this.forumTopicCreatedHandlers)
|
|
3367
|
+
);
|
|
3368
|
+
this.bot.on(
|
|
3369
|
+
"message:forum_topic_closed",
|
|
3370
|
+
(ctx) => this.dispatchForumTopic(ctx, this.forumTopicClosedHandlers)
|
|
3371
|
+
);
|
|
3372
|
+
this.bot.on("callback_query:data", (ctx) => this.dispatchCallback(ctx));
|
|
3373
|
+
}
|
|
3374
|
+
input;
|
|
3375
|
+
bot;
|
|
3376
|
+
startPromise = null;
|
|
3377
|
+
pollingPromise = null;
|
|
3378
|
+
async start() {
|
|
3379
|
+
if (this.startPromise) return this.startPromise;
|
|
3380
|
+
const starting = this.startPolling();
|
|
3381
|
+
this.startPromise = starting;
|
|
3382
|
+
try {
|
|
3383
|
+
await starting;
|
|
3384
|
+
} catch (error) {
|
|
3385
|
+
if (this.startPromise === starting) this.startPromise = null;
|
|
3386
|
+
throw error;
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
async startPolling() {
|
|
3390
|
+
const allowedUpdates = ["message", "callback_query"];
|
|
3391
|
+
await this.bot.api.getUpdates({
|
|
3392
|
+
allowed_updates: allowedUpdates,
|
|
3393
|
+
limit: 1,
|
|
3394
|
+
offset: -1,
|
|
3395
|
+
timeout: 0
|
|
3396
|
+
});
|
|
3397
|
+
let startupSettled = false;
|
|
3398
|
+
let resolveStartup;
|
|
3399
|
+
let rejectStartup;
|
|
3400
|
+
const startup = new Promise((resolve, reject) => {
|
|
3401
|
+
resolveStartup = resolve;
|
|
3402
|
+
rejectStartup = reject;
|
|
3403
|
+
});
|
|
3404
|
+
const polling = this.bot.start({
|
|
3405
|
+
allowed_updates: allowedUpdates,
|
|
3406
|
+
drop_pending_updates: true,
|
|
3407
|
+
onStart: () => {
|
|
3408
|
+
startupSettled = true;
|
|
3409
|
+
resolveStartup?.();
|
|
3410
|
+
}
|
|
3411
|
+
});
|
|
3412
|
+
this.pollingPromise = polling;
|
|
3413
|
+
void polling.catch((error) => {
|
|
3414
|
+
if (!startupSettled) {
|
|
3415
|
+
rejectStartup?.(error);
|
|
3416
|
+
return;
|
|
3417
|
+
}
|
|
3418
|
+
this.logWarn(error, "Telegram polling failed");
|
|
3419
|
+
});
|
|
3420
|
+
await startup;
|
|
3421
|
+
}
|
|
3422
|
+
async stop() {
|
|
3423
|
+
const started = this.startPromise;
|
|
3424
|
+
if (!started) return;
|
|
3425
|
+
this.startPromise = null;
|
|
3426
|
+
await started.catch(() => void 0);
|
|
3427
|
+
const polling = this.pollingPromise;
|
|
3428
|
+
this.pollingPromise = null;
|
|
3429
|
+
if (!polling) return;
|
|
3430
|
+
await this.bot.stop();
|
|
3431
|
+
await polling.catch(() => void 0);
|
|
3432
|
+
}
|
|
3433
|
+
async createForumTopic(input) {
|
|
3434
|
+
const result = await this.bot.api.createForumTopic(input.chatId, input.name);
|
|
3435
|
+
return { messageThreadId: result.message_thread_id };
|
|
3436
|
+
}
|
|
3437
|
+
async editForumTopic(input) {
|
|
3438
|
+
await this.bot.api.editForumTopic(input.chatId, input.messageThreadId, { name: input.name });
|
|
3439
|
+
}
|
|
3440
|
+
async closeForumTopic(input) {
|
|
3441
|
+
await this.bot.api.closeForumTopic(input.chatId, input.messageThreadId);
|
|
3442
|
+
}
|
|
3443
|
+
async sendMessage(input) {
|
|
3444
|
+
const result = await this.bot.api.sendMessage(input.chatId, input.text, {
|
|
3445
|
+
...input.messageThreadId !== void 0 ? { message_thread_id: input.messageThreadId } : {},
|
|
3446
|
+
...input.parseMode ? { parse_mode: input.parseMode } : {},
|
|
3447
|
+
...input.replyMarkup ? { reply_markup: toTelegramReplyMarkup(input.replyMarkup) } : {}
|
|
3448
|
+
});
|
|
3449
|
+
return { messageId: result.message_id };
|
|
3450
|
+
}
|
|
3451
|
+
async sendPhoto(input) {
|
|
3452
|
+
const result = await this.bot.api.sendPhoto(
|
|
3453
|
+
input.chatId,
|
|
3454
|
+
new InputFile(input.bytes, input.filename),
|
|
3455
|
+
this.fileOptions(input)
|
|
3456
|
+
);
|
|
3457
|
+
return { messageId: result.message_id };
|
|
3458
|
+
}
|
|
3459
|
+
async sendDocument(input) {
|
|
3460
|
+
const result = await this.bot.api.sendDocument(
|
|
3461
|
+
input.chatId,
|
|
3462
|
+
new InputFile(input.bytes, input.filename),
|
|
3463
|
+
this.fileOptions(input)
|
|
3464
|
+
);
|
|
3465
|
+
return { messageId: result.message_id };
|
|
3466
|
+
}
|
|
3467
|
+
fileOptions(input) {
|
|
3468
|
+
return {
|
|
3469
|
+
...input.messageThreadId !== void 0 ? { message_thread_id: input.messageThreadId } : {},
|
|
3470
|
+
...input.caption ? { caption: input.caption } : {},
|
|
3471
|
+
...input.parseMode ? { parse_mode: input.parseMode } : {}
|
|
3472
|
+
};
|
|
3473
|
+
}
|
|
3474
|
+
async answerCallbackQuery(input) {
|
|
3475
|
+
await this.bot.api.answerCallbackQuery(input.callbackQueryId, {
|
|
3476
|
+
...input.text ? { text: input.text } : {},
|
|
3477
|
+
...input.showAlert !== void 0 ? { show_alert: input.showAlert } : {}
|
|
3478
|
+
});
|
|
3479
|
+
}
|
|
3480
|
+
async dispatchText(ctx) {
|
|
3481
|
+
const message = ctx.message;
|
|
3482
|
+
const update = {
|
|
3483
|
+
messageId: message.message_id,
|
|
3484
|
+
chatId: String(message.chat.id),
|
|
3485
|
+
...message.message_thread_id !== void 0 ? { messageThreadId: message.message_thread_id } : {},
|
|
3486
|
+
from: toUserRef(message.from),
|
|
3487
|
+
text: message.text
|
|
3488
|
+
};
|
|
3489
|
+
await Promise.all([...this.textHandlers].map((handler) => handler(update)));
|
|
3490
|
+
}
|
|
3491
|
+
async dispatchForumTopic(ctx, handlers) {
|
|
3492
|
+
const message = ctx.message;
|
|
3493
|
+
if (message.message_thread_id === void 0) return;
|
|
3494
|
+
const update = {
|
|
3495
|
+
messageId: message.message_id,
|
|
3496
|
+
chatId: String(message.chat.id),
|
|
3497
|
+
messageThreadId: message.message_thread_id,
|
|
3498
|
+
from: toUserRef(message.from)
|
|
3499
|
+
};
|
|
3500
|
+
await Promise.all([...handlers].map((handler) => handler(update)));
|
|
3501
|
+
}
|
|
3502
|
+
async dispatchCallback(ctx) {
|
|
3503
|
+
const callback = ctx.callbackQuery;
|
|
3504
|
+
if (!callback.message) return;
|
|
3505
|
+
const update = {
|
|
3506
|
+
id: callback.id,
|
|
3507
|
+
chatId: String(callback.message.chat.id),
|
|
3508
|
+
...callback.message.message_thread_id !== void 0 ? { messageThreadId: callback.message.message_thread_id } : {},
|
|
3509
|
+
from: toUserRef(callback.from),
|
|
3510
|
+
data: callback.data
|
|
3511
|
+
};
|
|
3512
|
+
await Promise.all([...this.callbackHandlers].map((handler) => handler(update)));
|
|
3513
|
+
}
|
|
3514
|
+
logWarn(error, message) {
|
|
3515
|
+
this.input.logger?.warn?.(
|
|
3516
|
+
{ err: error instanceof Error ? error.message : String(error) },
|
|
3517
|
+
message
|
|
3518
|
+
);
|
|
3519
|
+
}
|
|
3520
|
+
};
|
|
3521
|
+
|
|
3522
|
+
// src/fake-telegram-client.ts
|
|
3523
|
+
var FakeTelegramClient = class extends BaseTelegramClientEventRegistrar {
|
|
3524
|
+
operations = [];
|
|
3525
|
+
createdTopics = [];
|
|
3526
|
+
editedTopics = [];
|
|
3527
|
+
closedTopics = [];
|
|
3528
|
+
sentMessages = [];
|
|
3529
|
+
sentPhotos = [];
|
|
3530
|
+
sentDocuments = [];
|
|
3531
|
+
answeredCallbacks = [];
|
|
3532
|
+
nextThreadId = 100;
|
|
3533
|
+
nextMessageId = 1;
|
|
3534
|
+
createForumTopicFailures = [];
|
|
3535
|
+
sendPhotoFailures = [];
|
|
3536
|
+
sendDocumentFailures = [];
|
|
3537
|
+
sendMessageFailure = null;
|
|
3538
|
+
started = false;
|
|
3539
|
+
async start() {
|
|
3540
|
+
this.started = true;
|
|
3541
|
+
}
|
|
3542
|
+
async stop() {
|
|
3543
|
+
this.started = false;
|
|
3544
|
+
}
|
|
3545
|
+
failNextCreateForumTopic(error = new Error("createForumTopic failed")) {
|
|
3546
|
+
this.createForumTopicFailures.push(error);
|
|
3547
|
+
}
|
|
3548
|
+
failSendMessageAfter(successfulSends, error = new Error("sendMessage failed")) {
|
|
3549
|
+
this.sendMessageFailure = {
|
|
3550
|
+
remainingSuccessfulSends: Math.max(0, successfulSends),
|
|
3551
|
+
error
|
|
3552
|
+
};
|
|
3553
|
+
}
|
|
3554
|
+
failNextSendPhoto(error = new Error("sendPhoto failed")) {
|
|
3555
|
+
this.sendPhotoFailures.push(error);
|
|
3556
|
+
}
|
|
3557
|
+
failNextSendDocument(error = new Error("sendDocument failed")) {
|
|
3558
|
+
this.sendDocumentFailures.push(error);
|
|
3559
|
+
}
|
|
3560
|
+
async createForumTopic(input) {
|
|
3561
|
+
const failure = this.createForumTopicFailures.shift();
|
|
3562
|
+
if (failure) {
|
|
3563
|
+
throw failure;
|
|
3564
|
+
}
|
|
3565
|
+
const topic = {
|
|
3566
|
+
chatId: input.chatId,
|
|
3567
|
+
name: input.name,
|
|
3568
|
+
messageThreadId: this.nextThreadId++
|
|
3569
|
+
};
|
|
3570
|
+
this.operations.push({ kind: "createForumTopic", input: topic });
|
|
3571
|
+
this.createdTopics.push(topic);
|
|
3572
|
+
return { messageThreadId: topic.messageThreadId };
|
|
3573
|
+
}
|
|
3574
|
+
async editForumTopic(input) {
|
|
3575
|
+
this.operations.push({ kind: "editForumTopic", input });
|
|
3576
|
+
this.editedTopics.push(input);
|
|
3577
|
+
}
|
|
3578
|
+
async closeForumTopic(input) {
|
|
3579
|
+
this.operations.push({ kind: "closeForumTopic", input });
|
|
3580
|
+
this.closedTopics.push(input);
|
|
3581
|
+
}
|
|
3582
|
+
async sendMessage(input) {
|
|
3583
|
+
const failure = this.sendMessageFailure;
|
|
3584
|
+
if (failure) {
|
|
3585
|
+
if (failure.remainingSuccessfulSends <= 0) {
|
|
3586
|
+
this.sendMessageFailure = null;
|
|
3587
|
+
throw failure.error;
|
|
3588
|
+
}
|
|
3589
|
+
failure.remainingSuccessfulSends -= 1;
|
|
3590
|
+
}
|
|
3591
|
+
this.operations.push({ kind: "sendMessage", input });
|
|
3592
|
+
this.sentMessages.push(input);
|
|
3593
|
+
return { messageId: this.nextMessageId++ };
|
|
3594
|
+
}
|
|
3595
|
+
async sendPhoto(input) {
|
|
3596
|
+
const failure = this.sendPhotoFailures.shift();
|
|
3597
|
+
if (failure) throw failure;
|
|
3598
|
+
this.operations.push({ kind: "sendPhoto", input });
|
|
3599
|
+
this.sentPhotos.push(input);
|
|
3600
|
+
return { messageId: this.nextMessageId++ };
|
|
3601
|
+
}
|
|
3602
|
+
async sendDocument(input) {
|
|
3603
|
+
const failure = this.sendDocumentFailures.shift();
|
|
3604
|
+
if (failure) throw failure;
|
|
3605
|
+
this.operations.push({ kind: "sendDocument", input });
|
|
3606
|
+
this.sentDocuments.push(input);
|
|
3607
|
+
return { messageId: this.nextMessageId++ };
|
|
3608
|
+
}
|
|
3609
|
+
async answerCallbackQuery(input) {
|
|
3610
|
+
this.operations.push({ kind: "answerCallbackQuery", input });
|
|
3611
|
+
this.answeredCallbacks.push(input);
|
|
3612
|
+
}
|
|
3613
|
+
async simulateText(update) {
|
|
3614
|
+
await Promise.all([...this.textHandlers].map((handler) => handler(update)));
|
|
3615
|
+
}
|
|
3616
|
+
async simulateCallback(update) {
|
|
3617
|
+
await Promise.all([...this.callbackHandlers].map((handler) => handler(update)));
|
|
3618
|
+
}
|
|
3619
|
+
async simulateForumTopicCreated(update) {
|
|
3620
|
+
await Promise.all([...this.forumTopicCreatedHandlers].map((handler) => handler(update)));
|
|
3621
|
+
}
|
|
3622
|
+
async simulateForumTopicClosed(update) {
|
|
3623
|
+
await Promise.all([...this.forumTopicClosedHandlers].map((handler) => handler(update)));
|
|
3624
|
+
}
|
|
3625
|
+
};
|
|
3626
|
+
|
|
3627
|
+
// src/index.ts
|
|
3628
|
+
var telegramClientToken = createCapabilityToken("telegram:client");
|
|
3629
|
+
var manifest = {
|
|
3630
|
+
id: "telegram",
|
|
3631
|
+
version: "0.1.0"
|
|
3632
|
+
};
|
|
3633
|
+
var telegramExtension = {
|
|
3634
|
+
manifest,
|
|
3635
|
+
setupServer(api, rawConfig) {
|
|
3636
|
+
const configResult = normalizeTelegramConfig(rawConfig);
|
|
3637
|
+
if (!configResult.ok) {
|
|
3638
|
+
throw new Error(`Invalid telegram extension config:
|
|
3639
|
+
${configResult.errors.join("\n")}`);
|
|
3640
|
+
}
|
|
3641
|
+
const config = configResult.config;
|
|
3642
|
+
if (!config.enabled) {
|
|
3643
|
+
return;
|
|
3644
|
+
}
|
|
3645
|
+
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
3646
|
+
if (!deps || Array.isArray(deps)) {
|
|
3647
|
+
return;
|
|
3648
|
+
}
|
|
3649
|
+
const providedClient = api.get(telegramClientToken);
|
|
3650
|
+
const client = Array.isArray(providedClient) ? providedClient[0] : providedClient;
|
|
3651
|
+
const telegramClient = client ?? new GrammyTelegramClient({
|
|
3652
|
+
botToken: config.botToken,
|
|
3653
|
+
logger: api.logger
|
|
3654
|
+
});
|
|
3655
|
+
if (!client) {
|
|
3656
|
+
api.provide(telegramClientToken, telegramClient);
|
|
3657
|
+
}
|
|
3658
|
+
const bridge = new TelegramBridge({
|
|
3659
|
+
config,
|
|
3660
|
+
deps,
|
|
3661
|
+
client: telegramClient,
|
|
3662
|
+
logger: api.logger
|
|
3663
|
+
});
|
|
3664
|
+
bridge.register(api.events);
|
|
3665
|
+
api.onStart(() => bridge.start());
|
|
3666
|
+
api.onStop(() => bridge.stop());
|
|
3667
|
+
}
|
|
3668
|
+
};
|
|
3669
|
+
var index_default = telegramExtension;
|
|
3670
|
+
export {
|
|
3671
|
+
FakeTelegramClient,
|
|
3672
|
+
ProcessThreadStore,
|
|
3673
|
+
TELEGRAM_ACTOR,
|
|
3674
|
+
TELEGRAM_THREAD_LINKED_EVENT,
|
|
3675
|
+
TelegramBridge,
|
|
3676
|
+
applyFormSkip,
|
|
3677
|
+
applyFormText,
|
|
3678
|
+
applyLaunchFieldText,
|
|
3679
|
+
applyLaunchFieldValue,
|
|
3680
|
+
applyLaunchModelStepAction,
|
|
3681
|
+
applyLaunchModelStepText,
|
|
3682
|
+
applyQuestionText,
|
|
3683
|
+
beginLaunchModelEdit,
|
|
3684
|
+
buildActionFormSession,
|
|
3685
|
+
buildActionModelPrompt,
|
|
3686
|
+
buildActionModelSession,
|
|
3687
|
+
buildActionModelSwitchWarning,
|
|
3688
|
+
buildContinueSession,
|
|
3689
|
+
buildFieldPrompt,
|
|
3690
|
+
buildLaunchFieldPrompt,
|
|
3691
|
+
buildLaunchInput,
|
|
3692
|
+
buildLaunchModelConfig,
|
|
3693
|
+
buildLaunchModelStepPrompt,
|
|
3694
|
+
buildLaunchModelSummary,
|
|
3695
|
+
buildLaunchReview,
|
|
3696
|
+
buildQuestionPrompt,
|
|
3697
|
+
buildQuestionSession,
|
|
3698
|
+
buildRecoveryModelPrompt,
|
|
3699
|
+
buildRecoveryModelSession,
|
|
3700
|
+
buildTopicTitle,
|
|
3701
|
+
canSkipActionFormField,
|
|
3702
|
+
createLaunchSession,
|
|
3703
|
+
currentField,
|
|
3704
|
+
currentLaunchField,
|
|
3705
|
+
currentLaunchModelStep,
|
|
3706
|
+
index_default as default,
|
|
3707
|
+
escapeTelegramAttribute,
|
|
3708
|
+
escapeTelegramHtml,
|
|
3709
|
+
finishLaunchModelEdit,
|
|
3710
|
+
getLaunchFieldOptions,
|
|
3711
|
+
getProcessTopicBaseTitle,
|
|
3712
|
+
hasLaunchModelControls,
|
|
3713
|
+
isLaunchSessionComplete,
|
|
3714
|
+
manifest,
|
|
3715
|
+
moveLaunchSessionToValidationField,
|
|
3716
|
+
normalizeTelegramConfig,
|
|
3717
|
+
renderMarkdownToTelegramHtml,
|
|
3718
|
+
renderResultMarkdownForTelegram,
|
|
3719
|
+
seedLaunchModelConfigFromPlan,
|
|
3720
|
+
splitPlainTelegramText,
|
|
3721
|
+
splitTelegramHtml,
|
|
3722
|
+
telegramClientToken,
|
|
3723
|
+
telegramHtmlToPlainText,
|
|
3724
|
+
threadKey
|
|
45
3725
|
};
|
|
46
|
-
export default telegramExtension;
|
|
47
|
-
export { TELEGRAM_ACTOR } from "./actor.js";
|
|
48
|
-
export * from "./bridge.js";
|
|
49
|
-
export * from "./config.js";
|
|
50
|
-
export * from "./fake-telegram-client.js";
|
|
51
|
-
export * from "./form-session.js";
|
|
52
|
-
export * from "./launch-session.js";
|
|
53
|
-
export * from "./markdown-html.js";
|
|
54
|
-
export * from "./process-thread-store.js";
|
|
55
|
-
export * from "./topic-title.js";
|
|
56
3726
|
//# sourceMappingURL=index.js.map
|