@leitwerk-dev/telegram 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +145 -0
  2. package/dist/LICENSE +13 -0
  3. package/dist/actions.d.ts +9 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/actions.js +32 -0
  6. package/dist/actions.js.map +1 -0
  7. package/dist/bridge.d.ts +132 -0
  8. package/dist/bridge.d.ts.map +1 -0
  9. package/dist/bridge.js +2032 -0
  10. package/dist/bridge.js.map +1 -0
  11. package/dist/config.d.ts +25 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +70 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/fake-telegram-client.d.ts +82 -0
  16. package/dist/fake-telegram-client.d.ts.map +1 -0
  17. package/dist/fake-telegram-client.js +107 -0
  18. package/dist/fake-telegram-client.js.map +1 -0
  19. package/dist/form-session.d.ts +143 -0
  20. package/dist/form-session.d.ts.map +1 -0
  21. package/dist/form-session.js +218 -0
  22. package/dist/form-session.js.map +1 -0
  23. package/dist/grammy-telegram-client.d.ts +131 -0
  24. package/dist/grammy-telegram-client.d.ts.map +1 -0
  25. package/dist/grammy-telegram-client.js +151 -0
  26. package/dist/grammy-telegram-client.js.map +1 -0
  27. package/dist/index.d.ts +19 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +55 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/launch-session.d.ts +103 -0
  32. package/dist/launch-session.d.ts.map +1 -0
  33. package/dist/launch-session.js +435 -0
  34. package/dist/launch-session.js.map +1 -0
  35. package/dist/markdown-html.d.ts +29 -0
  36. package/dist/markdown-html.d.ts.map +1 -0
  37. package/dist/markdown-html.js +259 -0
  38. package/dist/markdown-html.js.map +1 -0
  39. package/dist/mermaid-image.d.ts +2 -0
  40. package/dist/mermaid-image.d.ts.map +1 -0
  41. package/dist/mermaid-image.js +99 -0
  42. package/dist/mermaid-image.js.map +1 -0
  43. package/dist/process-feed.d.ts +58 -0
  44. package/dist/process-feed.d.ts.map +1 -0
  45. package/dist/process-feed.js +165 -0
  46. package/dist/process-feed.js.map +1 -0
  47. package/dist/process-thread-store.d.ts +18 -0
  48. package/dist/process-thread-store.d.ts.map +1 -0
  49. package/dist/process-thread-store.js +74 -0
  50. package/dist/process-thread-store.js.map +1 -0
  51. package/dist/topic-title.d.ts +7 -0
  52. package/dist/topic-title.d.ts.map +1 -0
  53. package/dist/topic-title.js +29 -0
  54. package/dist/topic-title.js.map +1 -0
  55. package/dist/types.d.ts +118 -0
  56. package/dist/types.d.ts.map +1 -0
  57. package/dist/types.js +19 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +57 -0
  60. package/src/actions.ts +41 -0
  61. package/src/bridge.ts +2870 -0
  62. package/src/config.ts +108 -0
  63. package/src/fake-telegram-client.ts +167 -0
  64. package/src/form-session.ts +359 -0
  65. package/src/grammy-telegram-client.ts +292 -0
  66. package/src/index.ts +68 -0
  67. package/src/launch-session.ts +620 -0
  68. package/src/markdown-html.ts +297 -0
  69. package/src/mermaid-image.ts +99 -0
  70. package/src/process-feed.ts +237 -0
  71. package/src/process-thread-store.ts +98 -0
  72. package/src/topic-title.ts +35 -0
  73. package/src/types.ts +138 -0
@@ -0,0 +1,297 @@
1
+ import { parseManagedResultImagePath } from "@leitwerk-dev/worker-protocol";
2
+ import MarkdownIt from "markdown-it";
3
+ import type Token from "markdown-it/lib/token.mjs";
4
+ import { type DefaultTreeAdapterMap, parseFragment } from "parse5";
5
+
6
+ const TELEGRAM_HARD_LIMIT = 4096;
7
+ const DEFAULT_TELEGRAM_SOFT_LIMIT = 3900;
8
+ const SAFE_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:", "tg:"]);
9
+ const TELEGRAM_INLINE_TAGS = new Map<string, "b" | "i" | "u" | "s">([
10
+ ["b", "b"],
11
+ ["strong", "b"],
12
+ ["i", "i"],
13
+ ["em", "i"],
14
+ ["u", "u"],
15
+ ["ins", "u"],
16
+ ["s", "s"],
17
+ ["strike", "s"],
18
+ ["del", "s"],
19
+ ]);
20
+ const BLOCK_TAGS = new Set([
21
+ "article",
22
+ "aside",
23
+ "blockquote",
24
+ "body",
25
+ "dd",
26
+ "div",
27
+ "dl",
28
+ "dt",
29
+ "figcaption",
30
+ "figure",
31
+ "footer",
32
+ "form",
33
+ "header",
34
+ "main",
35
+ "nav",
36
+ "p",
37
+ "section",
38
+ "table",
39
+ "tbody",
40
+ "td",
41
+ "tfoot",
42
+ "th",
43
+ "thead",
44
+ "tr",
45
+ ]);
46
+ const HEADING_TAG_PATTERN = /^h[1-6]$/;
47
+
48
+ const markdown = new MarkdownIt("commonmark", {
49
+ html: true,
50
+ linkify: false,
51
+ });
52
+
53
+ export type TelegramResultVisual =
54
+ | { kind: "image"; imageId: string; alt: string }
55
+ | { kind: "mermaid"; source: string };
56
+
57
+ export type TelegramResultPart = { kind: "html"; html: string } | TelegramResultVisual;
58
+
59
+ markdown.renderer.rules.image = (tokens, index) => escapeTelegramHtml(tokens[index]?.content ?? "");
60
+
61
+ type Parse5Node = DefaultTreeAdapterMap["node"];
62
+ type Parse5Element = DefaultTreeAdapterMap["element"];
63
+ type Parse5TextNode = DefaultTreeAdapterMap["textNode"];
64
+
65
+ export function escapeTelegramHtml(value: string): string {
66
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
67
+ }
68
+
69
+ export function escapeTelegramAttribute(value: string): string {
70
+ return escapeTelegramHtml(value).replaceAll('"', "&quot;");
71
+ }
72
+
73
+ function isElement(node: Parse5Node): node is Parse5Element {
74
+ return "tagName" in node;
75
+ }
76
+
77
+ function isTextNode(node: Parse5Node): node is Parse5TextNode {
78
+ return node.nodeName === "#text";
79
+ }
80
+
81
+ function clampMaxChars(maxChars: number): number {
82
+ return Math.min(Math.max(maxChars, 1), TELEGRAM_HARD_LIMIT);
83
+ }
84
+
85
+ function normalizeLineEndings(value: string): string {
86
+ return value.replace(/\r\n?/g, "\n").trim();
87
+ }
88
+
89
+ function attr(element: Parse5Element, name: string): string | null {
90
+ return element.attrs.find((candidate) => candidate.name.toLowerCase() === name)?.value ?? null;
91
+ }
92
+
93
+ function safeHref(value: string | null): string | null {
94
+ if (!value) return null;
95
+ try {
96
+ const parsed = new URL(value);
97
+ return SAFE_LINK_PROTOCOLS.has(parsed.protocol) ? value : null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ function renderChildren(element: Pick<Parse5Element, "childNodes">): string {
104
+ return element.childNodes.map(renderNode).join("");
105
+ }
106
+
107
+ function collectText(node: Parse5Node): string {
108
+ if (isTextNode(node)) return node.value;
109
+ if (!isElement(node)) return "";
110
+ if (node.tagName.toLowerCase() === "br") return "\n";
111
+ return node.childNodes.map(collectText).join("");
112
+ }
113
+
114
+ function withTrailingNewline(value: string): string {
115
+ const trimmed = value.trimEnd();
116
+ return trimmed ? `${trimmed}\n` : "";
117
+ }
118
+
119
+ function renderNode(node: Parse5Node): string {
120
+ if (isTextNode(node)) return escapeTelegramHtml(node.value);
121
+ if (!isElement(node)) return "";
122
+
123
+ const tagName = node.tagName.toLowerCase();
124
+ if (tagName === "script" || tagName === "style") return "";
125
+ if (tagName === "br") return "\n";
126
+ if (tagName === "hr") return "\n—\n";
127
+ if (tagName === "img") return escapeTelegramHtml(attr(node, "alt") ?? attr(node, "title") ?? "");
128
+ if (tagName === "pre") {
129
+ return withTrailingNewline(
130
+ `<pre><code>${escapeTelegramHtml(collectText(node).replace(/\n$/, ""))}</code></pre>`,
131
+ );
132
+ }
133
+ if (tagName === "code") return `<code>${escapeTelegramHtml(collectText(node))}</code>`;
134
+ if (tagName === "a") {
135
+ const children = renderChildren(node);
136
+ const href = safeHref(attr(node, "href"));
137
+ return href ? `<a href="${escapeTelegramAttribute(href)}">${children}</a>` : children;
138
+ }
139
+ const inlineTag = TELEGRAM_INLINE_TAGS.get(tagName);
140
+ if (inlineTag) return `<${inlineTag}>${renderChildren(node)}</${inlineTag}>`;
141
+ if (HEADING_TAG_PATTERN.test(tagName))
142
+ return withTrailingNewline(`<b>${renderChildren(node)}</b>`);
143
+ if (tagName === "li") return withTrailingNewline(`• ${renderChildren(node).trim()}`);
144
+ if (tagName === "ul" || tagName === "ol") return withTrailingNewline(renderChildren(node));
145
+ if (BLOCK_TAGS.has(tagName)) return withTrailingNewline(renderChildren(node));
146
+ return renderChildren(node);
147
+ }
148
+
149
+ function normalizeTelegramHtml(html: string): string {
150
+ return parseFragment(html).childNodes.map(renderNode).join("").trim();
151
+ }
152
+
153
+ export function telegramHtmlToPlainText(html: string): string {
154
+ return parseFragment(normalizeTelegramHtml(html)).childNodes.map(collectText).join("").trim();
155
+ }
156
+
157
+ function takeEncodedChunk(
158
+ value: string,
159
+ maxChars: number,
160
+ encodeChar: (char: string) => string,
161
+ ): { chunk: string; remaining: string } {
162
+ let encoded = "";
163
+ let rawEnd = 0;
164
+ let lastBoundary: { rawEnd: number; encodedEnd: number } | null = null;
165
+
166
+ for (const char of value) {
167
+ const encodedChar = encodeChar(char);
168
+ if (encoded.length + encodedChar.length > maxChars) break;
169
+ encoded += encodedChar;
170
+ rawEnd += char.length;
171
+ if (/\s/u.test(char)) lastBoundary = { rawEnd, encodedEnd: encoded.length };
172
+ }
173
+
174
+ if (rawEnd === value.length) return { chunk: encoded, remaining: "" };
175
+ if (rawEnd === 0) {
176
+ const [firstChar = ""] = value;
177
+ return { chunk: encodeChar(firstChar), remaining: value.slice(firstChar.length) };
178
+ }
179
+
180
+ const split =
181
+ lastBoundary && lastBoundary.encodedEnd >= Math.floor(maxChars * 0.5)
182
+ ? lastBoundary
183
+ : { rawEnd, encodedEnd: encoded.length };
184
+ return { chunk: encoded.slice(0, split.encodedEnd), remaining: value.slice(split.rawEnd) };
185
+ }
186
+
187
+ function splitEncodedText(
188
+ value: string,
189
+ maxChars: number,
190
+ encodeChar: (char: string) => string,
191
+ ): string[] {
192
+ let remaining = normalizeLineEndings(value);
193
+ if (!remaining) return [];
194
+
195
+ const chunks: string[] = [];
196
+ const max = clampMaxChars(maxChars);
197
+ while (remaining) {
198
+ const next = takeEncodedChunk(remaining, max, encodeChar);
199
+ chunks.push(next.chunk);
200
+ remaining = next.remaining;
201
+ }
202
+ return chunks;
203
+ }
204
+
205
+ export function splitPlainTelegramText(
206
+ value: string,
207
+ maxChars = DEFAULT_TELEGRAM_SOFT_LIMIT,
208
+ ): string[] {
209
+ return splitEncodedText(value, maxChars, (char) => char);
210
+ }
211
+
212
+ export function splitTelegramHtml(value: string, maxChars = DEFAULT_TELEGRAM_SOFT_LIMIT): string[] {
213
+ const normalized = normalizeLineEndings(value);
214
+ if (!normalized) return [];
215
+ const max = clampMaxChars(maxChars);
216
+ if (normalized.length <= max) return [normalized];
217
+
218
+ const safeHtml = normalizeTelegramHtml(normalized);
219
+ return safeHtml.length <= max
220
+ ? [safeHtml]
221
+ : splitEncodedText(telegramHtmlToPlainText(safeHtml), max, escapeTelegramHtml);
222
+ }
223
+
224
+ export function renderMarkdownToTelegramHtml(markdownText: string): string {
225
+ const normalized = normalizeLineEndings(markdownText);
226
+ return normalized ? normalizeTelegramHtml(markdown.render(normalized)) : "";
227
+ }
228
+
229
+ function resultVisual(
230
+ token: Token,
231
+ context: { instanceId: string; turnRecordId: string },
232
+ ): TelegramResultVisual | null {
233
+ if (token.type === "fence" && token.info.trim().split(/\s+/, 1)[0]?.toLowerCase() === "mermaid") {
234
+ return { kind: "mermaid", source: token.content.trim() };
235
+ }
236
+ if (token.type !== "image") return null;
237
+ const image = parseManagedResultImagePath(token.attrGet("src") ?? "");
238
+ if (
239
+ !image ||
240
+ image.instanceId !== context.instanceId ||
241
+ image.turnRecordId !== context.turnRecordId
242
+ )
243
+ return null;
244
+ return { kind: "image", imageId: image.imageId, alt: token.content };
245
+ }
246
+
247
+ /**
248
+ * Extracts only top-level visual blocks. Inline and list-nested images remain
249
+ * ordinary rendered Markdown so media delivery never has to reconstruct open
250
+ * formatting containers around Telegram uploads.
251
+ */
252
+ export function renderResultMarkdownForTelegram(input: {
253
+ markdown: string;
254
+ instanceId: string;
255
+ turnRecordId: string;
256
+ }): TelegramResultPart[] {
257
+ const normalized = normalizeLineEndings(input.markdown);
258
+ if (!normalized) return [];
259
+ const context = { instanceId: input.instanceId, turnRecordId: input.turnRecordId };
260
+ const tokens = markdown.parse(normalized, {});
261
+ const parts: TelegramResultPart[] = [];
262
+ let textTokens: Token[] = [];
263
+ const flushHtml = (): void => {
264
+ const html = normalizeTelegramHtml(markdown.renderer.render(textTokens, markdown.options, {}));
265
+ if (html) parts.push({ kind: "html", html });
266
+ textTokens = [];
267
+ };
268
+
269
+ for (let index = 0; index < tokens.length; index += 1) {
270
+ const token = tokens[index];
271
+ if (!token) continue;
272
+ let visual = token.level === 0 ? resultVisual(token, context) : null;
273
+ let consumed = 0;
274
+ const inline = tokens[index + 1];
275
+ if (
276
+ !visual &&
277
+ token.level === 0 &&
278
+ token.type === "paragraph_open" &&
279
+ inline?.type === "inline" &&
280
+ inline.children?.length === 1 &&
281
+ tokens[index + 2]?.type === "paragraph_close"
282
+ ) {
283
+ visual = resultVisual(inline.children[0] as Token, context);
284
+ if (visual?.kind === "image") consumed = 2;
285
+ else visual = null;
286
+ }
287
+ if (!visual) {
288
+ textTokens.push(token);
289
+ continue;
290
+ }
291
+ flushHtml();
292
+ parts.push(visual);
293
+ index += consumed;
294
+ }
295
+ flushHtml();
296
+ return parts;
297
+ }
@@ -0,0 +1,99 @@
1
+ import { Worker } from "node:worker_threads";
2
+
3
+ const MAX_MERMAID_SOURCE_CHARS = 20_000;
4
+ const MAX_MERMAID_SOURCE_LINES = 500;
5
+ const MERMAID_RENDER_TIMEOUT_MS = 8_000;
6
+
7
+ const RENDER_WORKER_SOURCE = String.raw`
8
+ const { parentPort, workerData } = require("node:worker_threads");
9
+ const MAX_SVG_BYTES = 2 * 1024 * 1024;
10
+ const MAX_SVG_ELEMENTS = 2_000;
11
+ const TARGET_WIDTH = 1_600;
12
+ const MAX_TARGET_HEIGHT = 5_000;
13
+ const MAX_TARGET_PIXELS = 8_000_000;
14
+ const MAX_PNG_BYTES = 10 * 1024 * 1024;
15
+
16
+ function fail(message) { throw new Error(message); }
17
+ function svgDimensions(svg) {
18
+ const match = /<svg[^>]*\bviewBox=["']\s*[-+\d.e]+\s+[-+\d.e]+\s+([-+\d.e]+)\s+([-+\d.e]+)\s*["']/i.exec(svg);
19
+ if (!match) fail("Rendered Mermaid SVG has no bounded viewBox");
20
+ const width = Number(match[1]);
21
+ const height = Number(match[2]);
22
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
23
+ fail("Rendered Mermaid SVG dimensions are invalid");
24
+ }
25
+ return { width, height };
26
+ }
27
+
28
+ (async () => {
29
+ const [{ renderMermaidSVG, THEMES }, { default: sharp }] = await Promise.all([
30
+ import("beautiful-mermaid"),
31
+ import("sharp"),
32
+ ]);
33
+ const svg = renderMermaidSVG(workerData.source, THEMES["zinc-light"]);
34
+ if (Buffer.byteLength(svg, "utf8") > MAX_SVG_BYTES) fail("Rendered Mermaid SVG is too large");
35
+ const elementCount = (svg.match(/<[a-zA-Z][^>]*>/g) || []).length;
36
+ if (elementCount > MAX_SVG_ELEMENTS) fail("Rendered Mermaid diagram is too complex");
37
+ const dimensions = svgDimensions(svg);
38
+ const targetHeight = Math.ceil((dimensions.height / dimensions.width) * TARGET_WIDTH);
39
+ if (targetHeight > MAX_TARGET_HEIGHT || TARGET_WIDTH * targetHeight > MAX_TARGET_PIXELS) {
40
+ fail("Rendered Mermaid diagram dimensions are too large");
41
+ }
42
+ const png = await sharp(Buffer.from(svg), { limitInputPixels: MAX_TARGET_PIXELS })
43
+ .resize({ width: TARGET_WIDTH, height: targetHeight, fit: "fill" })
44
+ .flatten({ background: "#ffffff" })
45
+ .png()
46
+ .toBuffer();
47
+ if (png.byteLength > MAX_PNG_BYTES) fail("Rendered Mermaid PNG is too large");
48
+ const bytes = Uint8Array.from(png);
49
+ parentPort.postMessage({ ok: true, bytes }, [bytes.buffer]);
50
+ })().catch((error) => {
51
+ parentPort.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) });
52
+ });
53
+ `;
54
+
55
+ export async function renderMermaidPng(source: string): Promise<Uint8Array> {
56
+ const normalized = source.trim();
57
+ if (!normalized) throw new Error("Mermaid source is empty");
58
+ if (normalized.length > MAX_MERMAID_SOURCE_CHARS) {
59
+ throw new Error(`Mermaid source exceeds ${MAX_MERMAID_SOURCE_CHARS} characters`);
60
+ }
61
+ if (normalized.split("\n").length > MAX_MERMAID_SOURCE_LINES) {
62
+ throw new Error(`Mermaid source exceeds ${MAX_MERMAID_SOURCE_LINES} lines`);
63
+ }
64
+
65
+ return new Promise<Uint8Array>((resolve, reject) => {
66
+ const worker = new Worker(RENDER_WORKER_SOURCE, {
67
+ eval: true,
68
+ workerData: { source: normalized },
69
+ resourceLimits: {
70
+ maxOldGenerationSizeMb: 96,
71
+ maxYoungGenerationSizeMb: 24,
72
+ stackSizeMb: 4,
73
+ },
74
+ });
75
+ let settled = false;
76
+ const finish = (work: () => void): void => {
77
+ if (settled) return;
78
+ settled = true;
79
+ clearTimeout(timer);
80
+ void worker.terminate();
81
+ work();
82
+ };
83
+ const timer = setTimeout(() => {
84
+ finish(() => reject(new Error("Mermaid rendering timed out")));
85
+ }, MERMAID_RENDER_TIMEOUT_MS);
86
+ worker.once("message", (message: unknown) => {
87
+ const result = message as { ok?: boolean; bytes?: Uint8Array; error?: string };
88
+ if (result.ok && result.bytes instanceof Uint8Array) {
89
+ finish(() => resolve(result.bytes as Uint8Array));
90
+ return;
91
+ }
92
+ finish(() => reject(new Error(result.error || "Mermaid rendering failed")));
93
+ });
94
+ worker.once("error", (error) => finish(() => reject(error)));
95
+ worker.once("exit", (code) => {
96
+ if (code !== 0) finish(() => reject(new Error(`Mermaid renderer exited with code ${code}`)));
97
+ });
98
+ });
99
+ }
@@ -0,0 +1,237 @@
1
+ import {
2
+ formatPathTypeLabel,
3
+ type ProcessInstance,
4
+ type ProcessLeafOutcomeSnapshot,
5
+ type ProcessLifecycleStatus,
6
+ type ProcessTurnRecord,
7
+ type ProcessTurnRecordPathType,
8
+ } from "@leitwerk-dev/domain";
9
+ import type { ProcessActionSummaryLike } from "@leitwerk-dev/process-sdk";
10
+ import {
11
+ escapeTelegramHtml as escapeHtml,
12
+ escapeTelegramAttribute,
13
+ renderMarkdownToTelegramHtml,
14
+ } from "./markdown-html.js";
15
+
16
+ const MAX_SUBMITTED_FIELD_VALUE_CHARS = 500;
17
+
18
+ /**
19
+ * Formats an internal turn ID (e.g. "generate_plan", "run_llm_review") into
20
+ * a human-readable label by splitting on underscores / hyphens and capitalising
21
+ * each word.
22
+ */
23
+ export function formatTurnIdLabel(turnId: string): string {
24
+ return turnId
25
+ .split(/[_-]+/)
26
+ .filter((part) => part.length > 0)
27
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
28
+ .join(" ");
29
+ }
30
+
31
+ type TelegramActionSummary = Pick<ProcessActionSummaryLike, "id" | "label" | "form"> & {
32
+ preview?: {
33
+ kind?: string;
34
+ turnId?: string;
35
+ lifecycleStatus?: string;
36
+ } | null;
37
+ };
38
+
39
+ export function processLabel(process: ProcessInstance): string {
40
+ return process.title?.trim() || process.externalId?.trim() || process.processId;
41
+ }
42
+
43
+ function actionLabel(action: Pick<ProcessActionSummaryLike, "id" | "label">): string {
44
+ return action.label.trim() || action.id;
45
+ }
46
+
47
+ function actionListLines(
48
+ actions: readonly Pick<ProcessActionSummaryLike, "id" | "label">[] = [],
49
+ recoveryActions: readonly string[] = [],
50
+ ): string[] {
51
+ const labels = [
52
+ ...actions.map(actionLabel),
53
+ ...recoveryActions.map((label) => label.trim()).filter((label) => label.length > 0),
54
+ ];
55
+ return labels.length > 0
56
+ ? ["Available actions:", ...labels.map((label) => `- ${escapeHtml(label)}`)]
57
+ : [];
58
+ }
59
+
60
+ function stringifySubmittedFieldValue(value: unknown): string {
61
+ if (typeof value === "string") return value.trim();
62
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
63
+ if (Array.isArray(value)) {
64
+ return value
65
+ .map((entry) => stringifySubmittedFieldValue(entry))
66
+ .filter((entry) => entry.length > 0)
67
+ .join(", ")
68
+ .trim();
69
+ }
70
+ return "";
71
+ }
72
+
73
+ function trimSubmittedValue(value: string): string {
74
+ return value.length > MAX_SUBMITTED_FIELD_VALUE_CHARS
75
+ ? `${value.slice(0, MAX_SUBMITTED_FIELD_VALUE_CHARS - 1)}…`
76
+ : value;
77
+ }
78
+
79
+ function submittedActionFields(
80
+ action: TelegramActionSummary,
81
+ values: Record<string, unknown>,
82
+ ): Array<{ label: string; value: string }> {
83
+ const submittedFields: Array<{ label: string; value: string }> = [];
84
+ const seenFieldIds = new Set<string>();
85
+ for (const field of action.form?.fields ?? []) {
86
+ seenFieldIds.add(field.id);
87
+ const value = stringifySubmittedFieldValue(values[field.id]);
88
+ if (value) submittedFields.push({ label: field.label, value: trimSubmittedValue(value) });
89
+ }
90
+ for (const [fieldId, rawValue] of Object.entries(values)) {
91
+ if (seenFieldIds.has(fieldId)) continue;
92
+ const value = stringifySubmittedFieldValue(rawValue);
93
+ if (value) submittedFields.push({ label: fieldId, value: trimSubmittedValue(value) });
94
+ }
95
+ return submittedFields;
96
+ }
97
+
98
+ function actionNextLine(action: TelegramActionSummary): string {
99
+ if (action.preview?.kind === "fixed_turn" && action.preview.turnId) {
100
+ return `Next: running ${escapeHtml(action.preview.turnId)}; result will be posted here.`;
101
+ }
102
+ if (action.preview?.kind === "terminal" && action.preview.lifecycleStatus) {
103
+ return `Next: process will become ${escapeHtml(action.preview.lifecycleStatus)}.`;
104
+ }
105
+ return "Next: the process will update shortly.";
106
+ }
107
+
108
+ export function buildProcessCreatedMessage(input: {
109
+ process: ProcessInstance;
110
+ serverBaseUrl: string;
111
+ }): string {
112
+ const url = `${input.serverBaseUrl.replace(/\/$/, "")}/processes/${input.process.id}`;
113
+ return [
114
+ "🚀 <b>Process created</b>",
115
+ `Title: ${escapeHtml(processLabel(input.process))}`,
116
+ `Status: ${escapeHtml(input.process.lifecycleStatus)}`,
117
+ `Web UI: <a href="${escapeTelegramAttribute(url)}">open process</a>`,
118
+ ].join("\n");
119
+ }
120
+
121
+ export function buildTurnStartedMessage(
122
+ turnRecord: ProcessTurnRecord,
123
+ options?: {
124
+ turnDescription?: string | null;
125
+ modelLabel?: string | null;
126
+ },
127
+ ): string {
128
+ const description = options?.turnDescription?.trim() || turnRecord.turnId;
129
+ const pathLabel = formatPathTypeLabel(turnRecord.pathType);
130
+ const base = `▶️ <b>Started</b>: ${escapeHtml(description)} — ${escapeHtml(pathLabel)}`;
131
+ const modelLabel = options?.modelLabel?.trim() ?? null;
132
+ return modelLabel ? `${base} (model: ${escapeHtml(modelLabel)})` : base;
133
+ }
134
+
135
+ export function buildLeafOutcomeMessage(input: {
136
+ snapshot: ProcessLeafOutcomeSnapshot;
137
+ markdownHtml?: string;
138
+ }): string {
139
+ const markdown = input.snapshot.fallbackMarkdown?.trim();
140
+ if (!markdown) {
141
+ return "✅ <b>Result available</b>\n\nOpen the Web UI for the full result.";
142
+ }
143
+ const body = input.markdownHtml ?? renderMarkdownToTelegramHtml(markdown);
144
+ return body ? `✅ <b>Result</b>\n\n${body}` : "✅ <b>Result</b>";
145
+ }
146
+
147
+ export function buildTurnOutcomeMessage(input: {
148
+ turnId: string;
149
+ outcome: string;
150
+ markdown: string;
151
+ markdownHtml?: string;
152
+ pathType?: ProcessTurnRecordPathType | null;
153
+ }): string {
154
+ const pathSuffix = input.pathType ? ` (${escapeHtml(formatPathTypeLabel(input.pathType))})` : "";
155
+ const heading = `✅ <b>Result</b>: ${escapeHtml(`${input.turnId}.${input.outcome}`)}${pathSuffix}`;
156
+ const body = input.markdownHtml ?? renderMarkdownToTelegramHtml(input.markdown.trim());
157
+ return body ? `${heading}\n\n${body}` : heading;
158
+ }
159
+
160
+ export function buildLifecycleMessage(input: {
161
+ process: ProcessInstance;
162
+ status: ProcessLifecycleStatus;
163
+ }): string | null {
164
+ if (input.status === "completed") {
165
+ return `🏁 <b>Completed</b>: ${escapeHtml(processLabel(input.process))}`;
166
+ }
167
+ if (input.status === "aborted") {
168
+ return `🛑 <b>Aborted</b>: ${escapeHtml(processLabel(input.process))}`;
169
+ }
170
+ if (input.status === "error") {
171
+ return `⚠️ <b>Process needs recovery</b>: ${escapeHtml(processLabel(input.process))}`;
172
+ }
173
+ return null;
174
+ }
175
+
176
+ export function buildActionsPromptMessage(input: {
177
+ process: ProcessInstance;
178
+ actions?: readonly Pick<ProcessActionSummaryLike, "id" | "label">[];
179
+ recoveryActions?: readonly string[];
180
+ currentTurnDescription?: string | null;
181
+ currentTurnPathType?: ProcessTurnRecordPathType | null;
182
+ }): string {
183
+ const rawTurn = input.currentTurnDescription?.trim() || input.process.selectedTurnId;
184
+ const turnDisplay = rawTurn ? formatTurnIdLabel(rawTurn) : "none";
185
+ const turnLine = `Turn: ${escapeHtml(turnDisplay)}`;
186
+ const pathLine = input.currentTurnPathType
187
+ ? `Path: ${escapeHtml(formatPathTypeLabel(input.currentTurnPathType))}`
188
+ : null;
189
+ return [
190
+ "⏸ <b>Action required</b>",
191
+ "",
192
+ `${escapeHtml(processLabel(input.process))}`,
193
+ `Status: ${escapeHtml(input.process.lifecycleStatus)}`,
194
+ turnLine,
195
+ ...(pathLine ? [pathLine] : []),
196
+ ...actionListLines(input.actions, input.recoveryActions),
197
+ ].join("\n");
198
+ }
199
+
200
+ export function buildStatusMessage(input: {
201
+ process: ProcessInstance;
202
+ actions?: readonly Pick<ProcessActionSummaryLike, "id" | "label">[];
203
+ currentTurnDescription?: string | null;
204
+ currentTurnPathType?: ProcessTurnRecordPathType | null;
205
+ }): string {
206
+ const rawTurn = input.currentTurnDescription?.trim() || input.process.selectedTurnId;
207
+ const turnDisplay = rawTurn ? formatTurnIdLabel(rawTurn) : "none";
208
+ const turnLine = `Turn: ${escapeHtml(turnDisplay)}`;
209
+ const pathLine = input.currentTurnPathType
210
+ ? `Path: ${escapeHtml(formatPathTypeLabel(input.currentTurnPathType))}`
211
+ : null;
212
+ const actionLines = actionListLines(input.actions);
213
+ return [
214
+ `<b>${escapeHtml(processLabel(input.process))}</b>`,
215
+ `Status: ${escapeHtml(input.process.lifecycleStatus)}`,
216
+ turnLine,
217
+ ...(pathLine ? [pathLine] : []),
218
+ ...(actionLines.length > 0 ? ["", ...actionLines] : []),
219
+ ].join("\n");
220
+ }
221
+
222
+ export function buildActionSubmittedMessage(input: {
223
+ action: TelegramActionSummary;
224
+ values: Record<string, unknown>;
225
+ }): string {
226
+ const fields = submittedActionFields(input.action, input.values);
227
+ return [
228
+ `✅ <b>Submitted action</b>: ${escapeHtml(actionLabel(input.action))}`,
229
+ ...(fields.length > 0
230
+ ? [
231
+ "Input:",
232
+ ...fields.map((field) => `- ${escapeHtml(field.label)}: ${escapeHtml(field.value)}`),
233
+ ]
234
+ : ["Input: none"]),
235
+ actionNextLine(input.action),
236
+ ].join("\n");
237
+ }