polygram 0.41.2 → 0.41.3

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
3
3
  "name": "polygram",
4
- "version": "0.41.2",
4
+ "version": "0.41.3",
5
5
  "description": "Telegram integration for Claude Code that preserves the OpenClaw per-chat session model. Migration target for OpenClaw users. Multi-bot, multi-chat, per-topic isolation; SQLite transcripts; inline-keyboard approvals. Bundles /polygram:status|logs|pair-code|approvals admin commands plus history (transcript queries) and polygram-send (out-of-turn IPC sends with file-upload validation) skills.",
6
6
  "keywords": [
7
7
  "telegram",
@@ -133,7 +133,8 @@ function createPollLoop({
133
133
  : null;
134
134
  const chatLabel = chatConfig?.name || chatId;
135
135
  const label = topicName ? `${chatLabel}/${topicName}` : chatLabel;
136
- logger.log?.(`[${botName}] ← ${label}: ${(m.text || m.caption || '(media)').slice(0, 60)}`);
136
+ const preview = m.text || m.caption || (m.rich_message ? '(rich message)' : '(media)');
137
+ logger.log?.(`[${botName}] ← ${label}: ${preview.slice(0, 60)}`);
137
138
  }
138
139
  try {
139
140
  await bot.handleUpdate(update);
@@ -320,6 +320,7 @@ function chunkMarkdownText(text, limit) {
320
320
  module.exports = {
321
321
  chunkText,
322
322
  chunkMarkdownText,
323
+ surrogateSafeCut,
323
324
  // Internals exported for tests; not part of the stable API.
324
325
  parseFenceSpans,
325
326
  scanParenAwareBreakpoints,
@@ -0,0 +1,254 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Inbound rich messages → plain text.
5
+ *
6
+ * Telegram delivers a rich message as `Message.rich_message`
7
+ * ({ blocks: RichBlock[] }) with no `text` and no `caption`. Everything
8
+ * after intake (the stored row, the gate, the prompt, replay, history) reads
9
+ * `msg.text`, so intake renders the block tree into it once.
10
+ *
11
+ * The output is plain text with just enough markdown structure (headings,
12
+ * list markers, quotes, code fences, table rows, link targets) for the agent
13
+ * to read the message the way the user saw it. Media inside blocks is not
14
+ * downloaded; a placeholder says it was there and was not attached.
15
+ *
16
+ * The outbound direction (markdown → blocks) lives in ./rich.js. Its
17
+ * flattenRichText keeps only the visible text, which is right for a styling
18
+ * retry but loses what the agent needs here: link targets, custom-emoji alt
19
+ * text and math expressions.
20
+ */
21
+
22
+ const { surrogateSafeCut } = require('./chunk');
23
+
24
+ // Telegram allows 16 levels of nested formatting and blocks. Blocks, inline
25
+ // nodes and the arrays wrapping them each count one level here, so legal
26
+ // input can reach about 33; past 64 the tree is malformed and that branch
27
+ // stops rendering instead of recursing further.
28
+ const MAX_DEPTH = 64;
29
+
30
+ // Quote prefixes and list indents repeat per nesting level, so a message
31
+ // within Telegram's own 32,768-character limit can render many times larger.
32
+ // Hold the rendered text to that same budget.
33
+ const MAX_RENDERED_CHARS = 32_768;
34
+ const TRUNCATED_MARKER = '\n[rich message truncated]';
35
+
36
+ // Every rendered message starts with this line. Command, abort and pairing
37
+ // matchers all anchor at the start of the text, so content the sender may
38
+ // not even have seen (a collapsed details block, say) can never be read as
39
+ // "/new" or "stop". It also tells the agent the text was derived from blocks.
40
+ const RICH_TEXT_HEADER = '[rich message]';
41
+
42
+ function str(v) {
43
+ return typeof v === 'string' ? v : '';
44
+ }
45
+
46
+ function inlineText(node, depth = 0) {
47
+ if (node == null || depth > MAX_DEPTH) return '';
48
+ if (typeof node === 'string') return node;
49
+ if (Array.isArray(node)) return node.map((n) => inlineText(n, depth + 1)).join('');
50
+ if (typeof node !== 'object') return '';
51
+ switch (node.type) {
52
+ case 'custom_emoji': return str(node.alternative_text);
53
+ case 'mathematical_expression': return node.expression ? `$${str(node.expression)}$` : '';
54
+ case 'button': return buttonText(node.button, depth + 1);
55
+ case 'anchor': return '';
56
+ case 'url': {
57
+ const label = inlineText(node.text, depth + 1);
58
+ const url = str(node.url);
59
+ // Keep the link target: the agent can't click the visible label.
60
+ if (!url || url === label) return label;
61
+ return label ? `[${label}](${url})` : url;
62
+ }
63
+ default: return inlineText(node.text, depth + 1);
64
+ }
65
+ }
66
+
67
+ function buttonText(button, depth = 0) {
68
+ const label = `[button: ${inlineText(button?.text, depth)}]`;
69
+ return str(button?.url) ? `${label}(${button.url})` : label;
70
+ }
71
+
72
+ // RichBlockCaption is { text, credit? }; a table caption is bare RichText.
73
+ function captionText(caption, depth) {
74
+ if (caption && typeof caption === 'object' && !Array.isArray(caption) && caption.type == null) {
75
+ const text = inlineText(caption.text, depth);
76
+ const credit = inlineText(caption.credit, depth);
77
+ return credit ? `${text} — ${credit}` : text;
78
+ }
79
+ return inlineText(caption, depth);
80
+ }
81
+
82
+ // Every line gets a marker, blank ones included, so a multi-paragraph quote
83
+ // stays one quote.
84
+ function quote(body, credit, depth) {
85
+ const by = inlineText(credit, depth);
86
+ return [body, by && `— ${by}`].filter(Boolean).join('\n')
87
+ .split('\n').map((line) => (line ? `> ${line}` : '>')).join('\n');
88
+ }
89
+
90
+ function renderList(items, depth) {
91
+ if (!Array.isArray(items)) return '';
92
+ return items.map((item) => {
93
+ if (!item || typeof item !== 'object') return '';
94
+ const box = item.has_checkbox ? (item.is_checked ? '[x] ' : '[ ] ') : '';
95
+ const head = `${str(item.label) || '-'} ${box}`;
96
+ const body = renderBlocks(item.blocks, depth, '\n');
97
+ const [first = '', ...rest] = body.split('\n');
98
+ return [(head + first).trimEnd(), ...rest.map((line) => (line ? ` ${line}` : line))].join('\n');
99
+ }).filter(Boolean).join('\n');
100
+ }
101
+
102
+ function renderTable(block, depth) {
103
+ const rows = Array.isArray(block.cells) ? block.cells : [];
104
+ const lines = rows.map((row) => (Array.isArray(row) ? row : []).flatMap((cell) => {
105
+ const text = inlineText(cell?.text, depth).replace(/\n+/g, ' ');
106
+ // Pad a column-spanning cell so the cells after it in the row stay under
107
+ // their headers. Row spans are not reconstructed.
108
+ const span = Math.min(Math.max(Math.trunc(Number(cell?.colspan)) || 1, 1), 20);
109
+ return [text, ...Array(span - 1).fill('')];
110
+ }).join(' | '));
111
+ return [captionText(block.caption, depth), ...lines].filter(Boolean).join('\n');
112
+ }
113
+
114
+ // A fence longer than any backtick run in the code, so the code can't close it.
115
+ function fence(code, language) {
116
+ const longest = (code.match(/`+/g) || []).reduce((max, run) => Math.max(max, run.length), 0);
117
+ const ticks = '`'.repeat(Math.max(3, longest + 1));
118
+ return `${ticks}${language}\n${code}\n${ticks}`;
119
+ }
120
+
121
+ function mediaLabel(block) {
122
+ const media = block[block.type];
123
+ const named = (kind, name) => (name ? `${kind}: ${name}` : kind);
124
+ let label;
125
+ switch (block.type) {
126
+ case 'photo': label = 'photo'; break;
127
+ case 'animation': label = 'animation'; break;
128
+ case 'voice_note': label = 'voice'; break;
129
+ case 'video': label = named('video', str(media?.file_name)); break;
130
+ case 'audio': label = named('audio', str(media?.title) || str(media?.file_name)); break;
131
+ case 'document': label = named('document', str(media?.file_name)); break;
132
+ default: return null;
133
+ }
134
+ return `[${label} — not attached]`;
135
+ }
136
+
137
+ function renderBlock(block, depth) {
138
+ if (!block || typeof block !== 'object' || depth > MAX_DEPTH) return '';
139
+ const media = mediaLabel(block);
140
+ if (media) {
141
+ const caption = captionText(block.caption, depth);
142
+ return caption ? `${media} ${caption}` : media;
143
+ }
144
+ switch (block.type) {
145
+ case 'paragraph':
146
+ case 'footer':
147
+ return inlineText(block.text, depth);
148
+ case 'heading': {
149
+ const text = inlineText(block.text, depth);
150
+ const level = Math.min(6, Math.max(1, Math.trunc(Number(block.size)) || 1));
151
+ return text && `${'#'.repeat(level)} ${text}`;
152
+ }
153
+ case 'pre':
154
+ return fence(inlineText(block.text, depth), str(block.language).replace(/[\s`]/g, ''));
155
+ case 'divider':
156
+ return '---';
157
+ case 'mathematical_expression':
158
+ return block.expression ? `$$${str(block.expression)}$$` : '';
159
+ case 'anchor':
160
+ return '';
161
+ case 'list':
162
+ return renderList(block.items, depth);
163
+ case 'blockquote':
164
+ return quote(renderBlocks(block.blocks, depth), block.credit, depth);
165
+ case 'expandable_blockquote':
166
+ case 'pullquote':
167
+ return quote(inlineText(block.text, depth), block.credit, depth);
168
+ case 'collage':
169
+ case 'slideshow':
170
+ return [renderBlocks(block.blocks, depth), captionText(block.caption, depth)].filter(Boolean).join('\n');
171
+ case 'table':
172
+ return renderTable(block, depth);
173
+ case 'details':
174
+ return [inlineText(block.summary, depth), renderBlocks(block.blocks, depth)].filter(Boolean).join('\n');
175
+ case 'map': {
176
+ const loc = block.location;
177
+ const where = loc && Number.isFinite(loc.latitude) && Number.isFinite(loc.longitude)
178
+ ? `[map: ${loc.latitude},${loc.longitude}]`
179
+ : '[map]';
180
+ const caption = captionText(block.caption, depth);
181
+ return caption ? `${where} ${caption}` : where;
182
+ }
183
+ case 'buttons':
184
+ return (Array.isArray(block.buttons) ? block.buttons : [])
185
+ .map((button) => buttonText(button, depth))
186
+ .join(' ');
187
+ default: {
188
+ // A block type newer than this renderer: keep whatever readable content
189
+ // it carries rather than dropping the message's text on the floor.
190
+ const parts = [
191
+ inlineText(block.text, depth),
192
+ renderBlocks(block.blocks, depth),
193
+ renderList(block.items, depth),
194
+ captionText(block.caption, depth),
195
+ ].filter(Boolean);
196
+ if (parts.length) return parts.join('\n');
197
+ return typeof block.type === 'string' ? `[${block.type}]` : '';
198
+ }
199
+ }
200
+ }
201
+
202
+ function renderBlocks(blocks, depth, separator = '\n\n') {
203
+ if (!Array.isArray(blocks) || depth > MAX_DEPTH) return '';
204
+ return blocks.map((b) => renderBlock(b, depth + 1)).filter(Boolean).join(separator);
205
+ }
206
+
207
+ /**
208
+ * Render a RichMessage ({ blocks, is_rtl? }) to plain text. Never throws on
209
+ * malformed input; returns '' when there is nothing readable.
210
+ */
211
+ function richMessageToText(richMessage) {
212
+ if (!richMessage || typeof richMessage !== 'object') return '';
213
+ const text = renderBlocks(richMessage.blocks, 0).trim();
214
+ if (text.length <= MAX_RENDERED_CHARS) return text;
215
+ return text.slice(0, surrogateSafeCut(text, MAX_RENDERED_CHARS)) + TRUNCATED_MARKER;
216
+ }
217
+
218
+ function renderInto(msg) {
219
+ if (!msg || typeof msg !== 'object' || msg.text || msg.caption || !msg.rich_message) return;
220
+ const text = richMessageToText(msg.rich_message);
221
+ if (text) msg.text = `${RICH_TEXT_HEADER}\n${text}`;
222
+ }
223
+
224
+ /**
225
+ * Give a rich message (and the rich message it replies to) a `text`, so
226
+ * every reader after intake sees its content. Mutates and returns `msg`.
227
+ * A message that already has `text` or `caption` is left alone.
228
+ *
229
+ * A rich message sent by another bot stays without text, as before: AI bots
230
+ * reply in rich messages, and dispatching them would let two bots in a group
231
+ * answer each other turn after turn. A user forwarding a bot's message is
232
+ * the sender here, so forwards still render. So do anonymous admins and
233
+ * channel posts: Telegram sends those from a placeholder bot account with
234
+ * `sender_chat` set, but a person wrote them.
235
+ */
236
+ function normalizeRichInbound(msg, { logger = console } = {}) {
237
+ const fromOtherBot = msg?.from?.is_bot === true && !msg?.sender_chat;
238
+ const targets = [fromOtherBot ? null : msg, msg?.reply_to_message];
239
+ for (const target of targets) {
240
+ try {
241
+ renderInto(target);
242
+ } catch (err) {
243
+ logger.error?.(`rich message ${target?.message_id ?? '?'} could not be rendered: ${err?.message || err}`);
244
+ }
245
+ }
246
+ return msg;
247
+ }
248
+
249
+ module.exports = {
250
+ richMessageToText,
251
+ normalizeRichInbound,
252
+ RICH_TEXT_HEADER,
253
+ MAX_RENDERED_CHARS,
254
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.41.2",
3
+ "version": "0.41.3",
4
4
  "description": "Telegram daemon for Claude Code that preserves the OpenClaw per-chat session model. Migration path for OpenClaw users moving to Claude Code.",
5
5
  "main": "lib/ipc/client.js",
6
6
  "bin": {
package/polygram.js CHANGED
@@ -189,6 +189,7 @@ const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
189
189
  const { createRichSender, sendRichWithStylingRetry } = require('./lib/telegram/rich-send');
190
190
  const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
191
191
  const { createRichEditStrategy } = require('./lib/telegram/rich-edit-dispatch');
192
+ const { normalizeRichInbound } = require('./lib/telegram/rich-inbound');
192
193
  const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
193
194
  const { composingMarker } = require('./lib/telegram/composing-marker');
194
195
  const { buildPolygramDisplayHint } = require('./lib/telegram/display-hint');
@@ -3464,6 +3465,10 @@ function createBot(token) {
3464
3465
  }
3465
3466
  if (!chatConfig) return;
3466
3467
 
3468
+ // A rich message has no text of its own; give it one before anything
3469
+ // (the stored row, the gate, the prompt) reads it.
3470
+ normalizeRichInbound(ctx.message);
3471
+
3467
3472
  // Record every inbound msg, even unaddressed ones — needed for reply-to
3468
3473
  // lookups and the transcript skill.
3469
3474
  recordInbound(ctx.message);
@@ -3519,6 +3524,9 @@ function createBot(token) {
3519
3524
  }
3520
3525
  const chatId = ctx.editedMessage.chat.id.toString();
3521
3526
  if (!knownChat(chatId)) return;
3527
+ // Same rendering as a fresh message, or the upsert below would blank the
3528
+ // stored text of an edited rich message.
3529
+ normalizeRichInbound(ctx.editedMessage);
3522
3530
  // 0.12.0 spec §3 (HARD): read the OLD text BEFORE recordInbound overwrites the row — the
3523
3531
  // post-turn changed-guard compares it, and the re-dispatch quotes it in reply_to so claude sees
3524
3532
  // the before/after. Reading after recordInbound would yield the new text (useless).