polygram 0.24.1 → 0.25.1

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.
@@ -40,7 +40,11 @@
40
40
 
41
41
  const fs = require('node:fs');
42
42
  const path = require('node:path');
43
- const { validateAttachmentPath } = require('../process/channels-tool-dispatcher');
43
+ const {
44
+ validateAttachmentPath,
45
+ MAX_FILES_PER_REPLY,
46
+ } = require('../process/channels-tool-dispatcher');
47
+ const { resolveMaxFileOverride } = require('../attachments');
44
48
  const { TELEGRAM_MAX_CAPTION_LENGTH } = require('./format');
45
49
 
46
50
  // Portable multipart ceilings. Photos are capped tighter than video and
@@ -108,6 +112,7 @@ function statMediaFile(source) {
108
112
  return fs.statSync(source, { bigint: true });
109
113
  }
110
114
 
115
+
111
116
  function createMediaFileIdCache({ maxEntries = FILE_ID_CACHE_MAX_ENTRIES } = {}) {
112
117
  const entries = new Map();
113
118
  const limit = Number.isInteger(maxEntries) && maxEntries > 0
@@ -239,6 +244,10 @@ function collectMediaRescueEntries(blocks) {
239
244
  * @param {number} [deps.maxOtherMediaBytes] — video/animation per-file cap,
240
245
  * already clamped to OTHER_MEDIA_UPLOAD_CEILING by the caller
241
246
  * @param {number} [deps.maxTotalMediaBytes] — per-reply budget
247
+ * @param {number} [deps.maxMediaPerMessage] — per-reply attachment count,
248
+ * clamped to MAX_MEDIA_PER_MESSAGE. The reply-tool path passes the same
249
+ * ceiling reply(files) enforces, so one syntax can't fan out wider than
250
+ * the other.
242
251
  * @param {boolean} [deps.allowUrlMedia] — false when a self-hosted Bot
243
252
  * API server is configured (see module doc)
244
253
  * @param {(kind: string, detail: object) => void} [deps.logEvent]
@@ -256,6 +265,7 @@ function createRichMediaResolver({
256
265
  maxPhotoBytes = PHOTO_UPLOAD_CEILING,
257
266
  maxOtherMediaBytes = OTHER_MEDIA_UPLOAD_CEILING,
258
267
  maxTotalMediaBytes = MAX_TOTAL_MEDIA_BYTES,
268
+ maxMediaPerMessage = MAX_MEDIA_PER_MESSAGE,
259
269
  allowUrlMedia = true,
260
270
  logEvent = null,
261
271
  validatePath = validateAttachmentPath,
@@ -263,6 +273,15 @@ function createRichMediaResolver({
263
273
  fileSize = null,
264
274
  fileIdCache = null,
265
275
  } = {}) {
276
+ // A caller asking for zero media means zero, not "use the default" — a
277
+ // ceiling option must never widen on the way through. Only a value that is
278
+ // not a count at all falls back.
279
+ const mediaCap = Math.min(
280
+ Number.isInteger(maxMediaPerMessage) && maxMediaPerMessage >= 0
281
+ ? maxMediaPerMessage
282
+ : MAX_MEDIA_PER_MESSAGE,
283
+ MAX_MEDIA_PER_MESSAGE,
284
+ );
266
285
  return function resolveMedia(descriptors) {
267
286
  const results = [];
268
287
  const reasons = [];
@@ -279,7 +298,7 @@ function createRichMediaResolver({
279
298
  for (const d of descriptors || []) {
280
299
  const src = typeof d?.src === 'string' ? d.src : '';
281
300
  if (!src) { reject('empty-src'); continue; }
282
- if (accepted >= MAX_MEDIA_PER_MESSAGE) { reject('media-cap'); continue; }
301
+ if (accepted >= mediaCap) { reject('media-cap'); continue; }
283
302
 
284
303
  if (HTTP_URL_RE.test(src)) {
285
304
  if (!allowUrlMedia) { reject('url-local-api'); continue; }
@@ -343,28 +362,163 @@ function createRichMediaResolver({
343
362
  };
344
363
  }
345
364
 
346
- function createMediaDeliveryContext({
365
+ /**
366
+ * Resolver options for one reply call, derived from exactly the inputs the
367
+ * caller has. Separated from the factory below so the wiring can be asserted
368
+ * as data — the value of every gate that decides what a prompt-injected reply
369
+ * may upload, by name, rather than by whatever the resolver happened to
370
+ * default to.
371
+ *
372
+ * No option that can WIDEN the trust boundary is defaulted permissively:
373
+ * `allowUrlMedia` defaults OFF and `validatePath`/`fileStat` are deliberately
374
+ * not injectable here — call sites get the module's secure implementations.
375
+ *
376
+ * @param {object} args
377
+ * @param {string[]} args.allowedRoots — computed ONCE per reply by the caller
378
+ * and shared with its reply(files) validation, so the two can't diverge
379
+ * @param {string|number} args.chatId
380
+ * @param {string|number|null} [args.threadId]
381
+ * @param {object|null} [args.config] — bot-filtered config, for the per-chat
382
+ * file-size override (never for roots: those follow the running session)
383
+ * @param {object|null} [args.fileIdCache]
384
+ * @param {Function|null} [args.logEvent]
385
+ * @param {?string} [args.botName]
386
+ * @param {?string} [args.transport] — event tag for the delivering verb
387
+ * @param {boolean} [args.allowUrlMedia]
388
+ * @param {number} [args.maxMediaPerMessage]
389
+ */
390
+ function richMediaResolverOptions({
347
391
  allowedRoots = [],
348
- tg,
349
- bot,
350
- chatId,
392
+ chatId = null,
351
393
  threadId = null,
352
- replyToMessageId = null,
394
+ config = null,
395
+ fileIdCache = null,
396
+ logEvent = null,
353
397
  botName = null,
398
+ transport = null,
399
+ allowUrlMedia = false,
400
+ maxMediaPerMessage = MAX_MEDIA_PER_MESSAGE,
401
+ } = {}) {
402
+ // api.js's outbound size cap keys on FILE_FIELD_BY_METHOD, which has no
403
+ // rich_message entry — nothing downstream re-checks these bytes, so these
404
+ // caps are the only per-file limit on this payload.
405
+ const override = resolveMaxFileOverride(config, chatId, threadId);
406
+ return {
407
+ allowedRoots,
408
+ fileIdCache,
409
+ maxPhotoBytes: Math.min(PHOTO_UPLOAD_CEILING, override ?? PHOTO_UPLOAD_CEILING),
410
+ maxOtherMediaBytes: Math.min(OTHER_MEDIA_UPLOAD_CEILING, override ?? OTHER_MEDIA_UPLOAD_CEILING),
411
+ maxTotalMediaBytes: MAX_TOTAL_MEDIA_BYTES,
412
+ maxMediaPerMessage,
413
+ allowUrlMedia,
414
+ logEvent: typeof logEvent === 'function'
415
+ // transport goes AFTER the spread: a resolver detail may not shadow the
416
+ // field the soak groups by.
417
+ ? (kind, detail) => logEvent(kind, {
418
+ chat_id: chatId,
419
+ thread_id: threadId,
420
+ bot: botName,
421
+ ...detail,
422
+ ...(transport ? { transport } : {}),
423
+ })
424
+ : null,
425
+ };
426
+ }
427
+
428
+ /**
429
+ * The one place either rich path builds its media resolver. Duplicating this
430
+ * wiring verbatim at two call sites is how the two trust boundaries drift
431
+ * apart; see richMediaResolverOptions for what each option decides.
432
+ */
433
+ function makeRichMediaResolver(args) {
434
+ return createRichMediaResolver(richMediaResolverOptions(args));
435
+ }
436
+
437
+ /**
438
+ * The reply tool's media boundary, whole: a resolver deciding what this call
439
+ * may upload, and the preflight that re-checks each item immediately before
440
+ * it does. Both from the same roots and the same stat, which is the property
441
+ * that makes them agree.
442
+ *
443
+ * It lives here, rather than as an object literal at the wiring site, so it
444
+ * can be tested by BEHAVIOR. The values below are the reply tool's security
445
+ * and resource envelope; expressed at a call site they would be pinned by
446
+ * nothing, since polygram.js is never executed by a test — deleting the
447
+ * fan-out ceiling there would widen it 5× with a green suite.
448
+ *
449
+ * @param {object} deps
450
+ * @param {object|null} [deps.config] — for the per-chat file-size override
451
+ * @param {object|null} [deps.fileIdCache] — shared with the streamer path
452
+ * @param {Function|null} [deps.logEvent]
453
+ * @param {?string} [deps.botName]
454
+ * @returns {(call: {allowedRoots: string[], chatId, threadId}) =>
455
+ * {resolveMedia: Function, mediaContext: object}}
456
+ */
457
+ function makeReplyMediaWiring({
458
+ config = null,
459
+ fileIdCache = null,
354
460
  logEvent = null,
355
- setDeliveryError = () => {},
356
- logger = console,
461
+ botName = null,
462
+ } = {}) {
463
+ return function replyMediaWiring({ allowedRoots, chatId, threadId = null } = {}) {
464
+ return {
465
+ resolveMedia: makeRichMediaResolver({
466
+ allowedRoots,
467
+ chatId,
468
+ threadId,
469
+ config,
470
+ fileIdCache,
471
+ // Unconditional, unlike the streamer path: `files:` cannot upload a
472
+ // URL at all, and a URL Telegram fetches server-side is an
473
+ // exfiltration beacon for prompt-injected content. The display hint
474
+ // teaches local paths only, so nothing legitimate is lost.
475
+ allowUrlMedia: false,
476
+ // The same ceiling `files:` enforces: above it that param errors, and
477
+ // silently accepting five times as many through image syntax would
478
+ // make the narrower limit meaningless.
479
+ maxMediaPerMessage: MAX_FILES_PER_REPLY,
480
+ logEvent,
481
+ botName,
482
+ transport: 'send',
483
+ }),
484
+ mediaContext: createMediaPreflight({ allowedRoots, fileIdCache }),
485
+ };
486
+ };
487
+ }
488
+
489
+ /**
490
+ * The non-network half of the delivery context: everything a send needs to
491
+ * re-check local media immediately before upload and to keep the file_id
492
+ * cache honest afterwards.
493
+ *
494
+ * Split out because the send path needs exactly this and nothing else — it
495
+ * has no placeholder bubble to delete, no rescue ladder, and no partial-
496
+ * delivery warning to flush. Its `fileStat`/`validatePath` MUST be the same
497
+ * implementations the resolver used: a stat that isn't bigint produces
498
+ * fingerprints that can never match the resolved ones, and every media send
499
+ * would then degrade silently with nothing in the logs saying why.
500
+ *
501
+ * Asked for bytes (`withBytes`), the check binds to a DESCRIPTOR rather than
502
+ * a path: open, fstat that descriptor, compare, and read through it. What is
503
+ * uploaded is then provably the bytes that were fingerprinted — a path-backed
504
+ * handle is re-opened by name at request-build time, and again on every
505
+ * retry, so a file swapped after the check but before (or between) those
506
+ * reads would upload its new contents under the old verdict. The buffer also
507
+ * makes a 429 retry re-send the same bytes instead of re-reading the path.
508
+ * Cost, stated: the reply's media is held in memory for the duration of the
509
+ * send, bounded by the per-reply budget (maxTotalMediaBytes).
510
+ *
511
+ * @returns {{preflightMedia: Function, rememberLocal: Function,
512
+ * learnRichResult: Function, evictCachedBlocks: Function}}
513
+ */
514
+ function createMediaPreflight({
515
+ allowedRoots = [],
516
+ fileIdCache = null,
357
517
  validatePath = validateAttachmentPath,
358
518
  fileStat = statMediaFile,
359
- fileIdCache = null,
519
+ logger = console,
360
520
  } = {}) {
361
521
  const roots = Object.freeze([...(allowedRoots || [])]);
362
- const failures = { text: 0, media: 0, deletion: 0 };
363
- let warningFlushed = false;
364
-
365
- function recordFailure(kind, count = 1) {
366
- if (Object.hasOwn(failures, kind)) failures[kind] += Math.max(0, Number(count) || 0);
367
- }
368
522
 
369
523
  function evict(kind, media) {
370
524
  if (media && typeof media.source === 'string') {
@@ -372,7 +526,7 @@ function createMediaDeliveryContext({
372
526
  }
373
527
  }
374
528
 
375
- function preflight(media, kind = 'photo', { preferFileId = true } = {}) {
529
+ function preflight(media, kind = 'photo', { preferFileId = true, withBytes = false } = {}) {
376
530
  if (!MEDIA_KINDS.has(kind)) return { ok: false };
377
531
  if (typeof media === 'string') return { ok: HTTP_URL_RE.test(media), value: media };
378
532
  if (!media || typeof media.source !== 'string' || typeof media.fingerprint !== 'string') {
@@ -398,10 +552,31 @@ function createMediaDeliveryContext({
398
552
  const currentId = fileIdCache.get?.(kind, media.source, media.fingerprint) || null;
399
553
  if (currentId !== fileId) fileId = null;
400
554
  }
401
- return {
402
- ok: true,
403
- value: preferFileId && fileId ? fileId : { source: media.source },
404
- };
555
+ // A cached id needs no bytes: Telegram already holds the file.
556
+ if (preferFileId && fileId) return { ok: true, value: fileId };
557
+ if (!withBytes) return { ok: true, value: { source: media.source } };
558
+
559
+ let fd;
560
+ try { fd = fs.openSync(check.resolved, 'r'); }
561
+ catch {
562
+ evict(kind, media);
563
+ return { ok: false };
564
+ }
565
+ try {
566
+ // The path check above proved the NAME resolves somewhere allowed; this
567
+ // proves the OPEN FILE is still the one that was fingerprinted. Between
568
+ // the two, the name could have been repointed.
569
+ if (statFingerprint(fs.fstatSync(fd, { bigint: true })) !== media.fingerprint) {
570
+ evict(kind, media);
571
+ return { ok: false };
572
+ }
573
+ return { ok: true, value: { source: media.source, bytes: fs.readFileSync(fd) } };
574
+ } catch {
575
+ evict(kind, media);
576
+ return { ok: false };
577
+ } finally {
578
+ try { fs.closeSync(fd); } catch { /* the read already decided the outcome */ }
579
+ }
405
580
  }
406
581
 
407
582
  function rememberLocal(kind, media, fileId) {
@@ -411,16 +586,6 @@ function createMediaDeliveryContext({
411
586
  return fileIdCache.set?.(kind, media.source, media.fingerprint, fileId) === true;
412
587
  }
413
588
 
414
- function learnDirectResult(kind, media, result) {
415
- try {
416
- const fileId = returnedMediaFileId(kind, result?.[kind]);
417
- return rememberLocal(kind, media, fileId);
418
- } catch (err) {
419
- logger.warn?.(`[rich-media] cache learning failed (${err?.name || 'Error'})`);
420
- return false;
421
- }
422
- }
423
-
424
589
  function learnRichResult(blocks, result) {
425
590
  try {
426
591
  if (result?._notModified || !Array.isArray(result?.rich_message?.blocks)) return false;
@@ -449,6 +614,52 @@ function createMediaDeliveryContext({
449
614
  return evicted;
450
615
  }
451
616
 
617
+ return Object.freeze({
618
+ preflightMedia: preflight,
619
+ rememberLocal,
620
+ learnRichResult,
621
+ evictCachedBlocks,
622
+ });
623
+ }
624
+
625
+ function createMediaDeliveryContext({
626
+ allowedRoots = [],
627
+ tg,
628
+ bot,
629
+ chatId,
630
+ threadId = null,
631
+ replyToMessageId = null,
632
+ botName = null,
633
+ logEvent = null,
634
+ setDeliveryError = () => {},
635
+ logger = console,
636
+ validatePath = validateAttachmentPath,
637
+ fileStat = statMediaFile,
638
+ fileIdCache = null,
639
+ } = {}) {
640
+ const {
641
+ preflightMedia: preflight,
642
+ rememberLocal,
643
+ learnRichResult,
644
+ evictCachedBlocks,
645
+ } = createMediaPreflight({ allowedRoots, fileIdCache, validatePath, fileStat, logger });
646
+ const failures = { text: 0, media: 0, deletion: 0 };
647
+ let warningFlushed = false;
648
+
649
+ function recordFailure(kind, count = 1) {
650
+ if (Object.hasOwn(failures, kind)) failures[kind] += Math.max(0, Number(count) || 0);
651
+ }
652
+
653
+ function learnDirectResult(kind, media, result) {
654
+ try {
655
+ const fileId = returnedMediaFileId(kind, result?.[kind]);
656
+ return rememberLocal(kind, media, fileId);
657
+ } catch (err) {
658
+ logger.warn?.(`[rich-media] cache learning failed (${err?.name || 'Error'})`);
659
+ return false;
660
+ }
661
+ }
662
+
452
663
  async function deletePlaceholder(messageId, meta = {}) {
453
664
  try {
454
665
  await tg(bot, 'deleteMessage', {
@@ -603,6 +814,10 @@ function createMediaDeliveryContext({
603
814
 
604
815
  module.exports = {
605
816
  createRichMediaResolver,
817
+ richMediaResolverOptions,
818
+ makeRichMediaResolver,
819
+ makeReplyMediaWiring,
820
+ createMediaPreflight,
606
821
  createMediaDeliveryContext,
607
822
  createMediaFileIdCache,
608
823
  collectMediaRescueEntries,
@@ -15,11 +15,26 @@
15
15
  * leaves sendRichMessage untracked: a tracked pending row would persist the
16
16
  * failed attempt, the plain fallback would then insert its own rows, and the
17
17
  * agent's preloaded history would show the same answer twice.
18
+ *
19
+ * Media: blocks arrive JSON-safe, local files as `{source, fingerprint}`
20
+ * envelopes, and are materialized into uploadable values immediately before
21
+ * the call — through the caller's preflight, which re-validates roots and
22
+ * re-stats the file. A source that changed since it was resolved aborts the
23
+ * whole send before a byte is uploaded, and the strategy re-renders without
24
+ * it. This function still never throws: that abort is a `wentRich: false`
25
+ * like any other, with `fallback` naming the class so the caller can decide
26
+ * whether a different render is worth one more attempt.
18
27
  */
19
28
 
20
29
  'use strict';
21
30
 
22
31
  const { createRichCapabilityLatch } = require('./rich-capability-latch');
32
+ const {
33
+ materializeMediaBlocks,
34
+ defaultMakeInputFile,
35
+ MEDIA_SOURCE_CHANGED,
36
+ } = require('./rich-edit');
37
+ const { countMediaBlocks } = require('./rich');
23
38
 
24
39
  /**
25
40
  * @param {object} deps
@@ -40,10 +55,17 @@ const { createRichCapabilityLatch } = require('./rich-capability-latch');
40
55
  * transcript row; best-effort, never blocks delivery
41
56
  * @param {object} [deps.capabilityLatch] — shared latch decision; pass the SAME
42
57
  * instance the edit path uses so a bare 404 on either counts toward one run
58
+ * @param {(source: string, bytes?: Buffer) => *} [deps.makeInputFile] — source
59
+ * (plus the preflighted bytes, when the check read them) → uploadable file
60
+ * for grammy (test seam)
43
61
  * @param {object} [deps.logger]
44
62
  * @returns {(args: {bot, chatId: string, threadId?: (string|number|null), blocks: Array,
45
- * sourceText: string, replyParams?: object, meta?: object})
46
- * => Promise<{wentRich: boolean, result?: *}>}
63
+ * sourceText: string, replyParams?: object, mediaContext?: object, meta?: object})
64
+ * => Promise<{wentRich: boolean, result?: *, fallback?: string}>}
65
+ * `fallback` names the failure class. Only 'media-source-changed' is acted
66
+ * on by the caller (it is the one a different render could fix); the rest
67
+ * —'capability', 'content-error', 'no-message-id', 'error' — distinguish
68
+ * otherwise identical plain-fallback outcomes for the soak.
47
69
  */
48
70
  function createRichSender({
49
71
  tg,
@@ -59,6 +81,7 @@ function createRichSender({
59
81
  stripUrlCreds = (s) => s,
60
82
  insertSentRow = null,
61
83
  capabilityLatch = null,
84
+ makeInputFile = defaultMakeInputFile,
62
85
  logger = console,
63
86
  } = {}) {
64
87
  // Shared with the edit path when the caller passes one in: both trip the
@@ -76,20 +99,26 @@ function createRichSender({
76
99
  blocks,
77
100
  sourceText,
78
101
  replyParams = null,
102
+ mediaContext = null,
79
103
  meta = {},
80
104
  }) {
81
105
  if (getRichKnownUnsupported()) return { wentRich: false };
82
106
  if (!Array.isArray(blocks) || blocks.length === 0) return { wentRich: false };
83
107
 
84
- const params = {
85
- chat_id: chatId,
86
- rich_message: { blocks },
87
- };
88
- if (threadId != null) params.message_thread_id = threadId;
89
- if (replyParams) params.reply_parameters = replyParams;
90
-
91
108
  let result;
92
109
  try {
110
+ const params = {
111
+ chat_id: chatId,
112
+ rich_message: {
113
+ // Inside the try, and before the call: this throws synchronously
114
+ // when a local source no longer matches what was resolved, and the
115
+ // whole point is that nothing uploads when it does.
116
+ blocks: materializeMediaBlocks(blocks, makeInputFile, mediaContext?.preflightMedia),
117
+ },
118
+ };
119
+ if (threadId != null) params.message_thread_id = threadId;
120
+ if (replyParams) params.reply_parameters = replyParams;
121
+
93
122
  result = await tg(bot, 'sendRichMessage', params, {
94
123
  ...meta,
95
124
  source: meta.source || 'bot-reply-rich-send',
@@ -97,8 +126,7 @@ function createRichSender({
97
126
  richSourceText: sourceText,
98
127
  });
99
128
  } catch (err) {
100
- classifyFailure(err, chatId, threadId);
101
- return { wentRich: false };
129
+ return { wentRich: false, fallback: classifyFailure(err, chatId, threadId, blocks, mediaContext) };
102
130
  }
103
131
 
104
132
  latch.recordHealthyOutcome();
@@ -109,15 +137,19 @@ function createRichSender({
109
137
  // failure so the caller delivers plain rather than reporting a success the
110
138
  // agent cannot act on. Trade-off, stated plainly: if the server DID create
111
139
  // a bubble, the user sees the reply twice. That is the louder failure of
112
- // the two, and the response shape is unverified until the live gate runs.
140
+ // the two.
113
141
  const messageId = result?.message_id;
114
142
  if (messageId == null) {
115
143
  logEvent('rich-content-fallback', {
116
144
  chat_id: chatId, thread_id: threadId, bot: botName,
117
145
  transport: 'send',
146
+ media_count: safeMediaCount(blocks),
118
147
  error: 'response carried no message_id',
119
148
  });
120
- return { wentRich: false };
149
+ // Its own class, not 'content-error': that class carries a side effect
150
+ // (evicting the cached ids the server rejected), and a response we
151
+ // could not read says nothing about whether those ids are stale.
152
+ return { wentRich: false, fallback: 'no-message-id' };
121
153
  }
122
154
 
123
155
  // The message has landed. Nothing below may change that verdict: a throw
@@ -148,6 +180,10 @@ function createRichSender({
148
180
  bot: botName,
149
181
  transport: 'send',
150
182
  block_count: blocks.length,
183
+ // Paired with the same field on the fallback event: media that
184
+ // silently stops being delivered is otherwise invisible, because no
185
+ // rich-media event fires on a send-path delivery failure.
186
+ media_count: safeMediaCount(blocks),
151
187
  char_count: sourceText?.length ?? null,
152
188
  message_id: messageId,
153
189
  });
@@ -171,10 +207,39 @@ function createRichSender({
171
207
  logger?.error?.(`[telegram] rich-send bookkeeping failed after delivery: ${e.message}`);
172
208
  }
173
209
 
210
+ // Last, and in its own try: the send path is ~80% of output, so without
211
+ // this the shared file_id cache would only ever be filled by the streamer
212
+ // and every reply would re-upload the same unchanged file. But it is the
213
+ // least important thing that happens after delivery — ahead of the
214
+ // transcript row it would be one caller-supplied dependency away from
215
+ // costing a landed message its history, which is the duplicate-answer
216
+ // failure this module exists to avoid.
217
+ try {
218
+ mediaContext?.learnRichResult?.(blocks, result);
219
+ } catch (e) {
220
+ logger?.error?.(`[telegram] rich-send cache learning failed after delivery: ${e.message}`);
221
+ }
222
+
174
223
  return { wentRich: true, result };
175
224
  };
176
225
 
177
- function classifyFailure(err, chatId, threadId) {
226
+ // Classifies one failure, applies its side effects, and names the class so
227
+ // the caller can tell a re-renderable failure from a terminal one. It never
228
+ // decides whether the reply is delivered — that is always "yes, as plain".
229
+ function classifyFailure(err, chatId, threadId, blocks, mediaContext) {
230
+ // FIRST: this one never reached Telegram, so it says nothing about the
231
+ // server's capabilities. Classified as a capability error (the regex can
232
+ // match an arbitrary message) it would latch rich off over a swapped file.
233
+ if (err?.code === MEDIA_SOURCE_CHANGED) {
234
+ logEvent('rich-content-fallback', {
235
+ chat_id: chatId, thread_id: threadId, bot: botName,
236
+ transport: 'send',
237
+ media_count: safeMediaCount(blocks),
238
+ error: 'media-source-changed',
239
+ });
240
+ return 'media-source-changed';
241
+ }
242
+
178
243
  if (safeTest(isRichCapabilityError, err)) {
179
244
  if (latch.recordCapabilityError(err, 'send')) {
180
245
  logCapabilityLatched(err, chatId);
@@ -185,7 +250,7 @@ function createRichSender({
185
250
  error: redactBotToken(errText(err))?.slice(0, 200),
186
251
  });
187
252
  }
188
- return;
253
+ return 'capability';
189
254
  }
190
255
 
191
256
  // A rejection of this payload proves the endpoint is present and
@@ -193,12 +258,18 @@ function createRichSender({
193
258
  latch.recordHealthyOutcome();
194
259
 
195
260
  if (safeTest(isRichContentError, err)) {
261
+ // A file_id Telegram has forgotten still has a MATCHING fingerprint, so
262
+ // preflight would hand it back forever. Drop it here and the next reply
263
+ // re-uploads the bytes.
264
+ try { mediaContext?.evictCachedBlocks?.(blocks); }
265
+ catch (e) { logger?.error?.(`[telegram] rich-send cache eviction failed: ${e.message}`); }
196
266
  logEvent('rich-content-fallback', {
197
267
  chat_id: chatId, thread_id: threadId, bot: botName,
198
268
  transport: 'send',
269
+ media_count: safeMediaCount(blocks),
199
270
  error: redactBotToken(errText(err))?.slice(0, 200),
200
271
  });
201
- return;
272
+ return 'content-error';
202
273
  }
203
274
 
204
275
  // Soak note: api.js already logs telegram-api-error for the same failure,
@@ -208,6 +279,7 @@ function createRichSender({
208
279
  error_class: err?.name || 'Error',
209
280
  error: redactBotToken(errText(err))?.slice(0, 200),
210
281
  });
282
+ return 'error';
211
283
  }
212
284
 
213
285
  function logCapabilityLatched(err, chatId) {
@@ -229,6 +301,13 @@ function safeTest(fn, err) {
229
301
  catch { return false; }
230
302
  }
231
303
 
304
+ // Instrumentation only. A malformed block tree must not become the reason a
305
+ // failure goes unlogged or a delivered message is reported as lost.
306
+ function safeMediaCount(blocks) {
307
+ try { return countMediaBlocks(blocks); }
308
+ catch { return null; }
309
+ }
310
+
232
311
  function errText(err) {
233
312
  if (!err) return '';
234
313
  return String(err.description || err.message || err);
@@ -147,8 +147,15 @@ function plainTextOf(tokens) {
147
147
  out += plainTextOf(t.tokens);
148
148
  } else if (t.type === 'text' || t.type === 'codespan' || t.type === 'escape') {
149
149
  out += t.text ?? '';
150
- } else if (t.type === 'link' || t.type === 'image') {
150
+ } else if (t.type === 'link') {
151
151
  out += plainTextOf(t.tokens) || t.text || t.href || '';
152
+ } else if (t.type === 'image') {
153
+ // Never fall back to the destination. A link's href is something the
154
+ // author chose to publish; an image's is a filesystem path far more
155
+ // often than not, and an uncaptioned image nested where inline tokens
156
+ // are flattened (a heading, a table cell, inside bold) would render
157
+ // that path as visible text. Uncaptioned images flatten to nothing.
158
+ out += plainTextOf(t.tokens) || t.text || '';
152
159
  } else if (t.type === 'br') {
153
160
  out += '\n';
154
161
  } else if (Array.isArray(t.tokens)) {
@@ -467,6 +474,12 @@ function blockFromToken(token) {
467
474
  }
468
475
  }
469
476
 
477
+ // A task item's `[ ]`/`[x]` marker survives inside the item's child
478
+ // tokens — marked strips it only from the container token's own .text,
479
+ // so flattening through the children re-surfaces it next to the real
480
+ // checkbox the has_checkbox flag renders. Strip it from the leader.
481
+ const TASK_MARKER_RE = /^\s*\[[ xX]\]\s*/;
482
+
470
483
  function listItemFromToken(item, listToken, index) {
471
484
  const { inline, blockTokens } = splitListItemTokens(item.tokens);
472
485
  const nestedBlocks = blocksFromTokens(blockTokens);
@@ -475,7 +488,8 @@ function listItemFromToken(item, listToken, index) {
475
488
  blocks.push(...blocksFromInlineTokens(inline));
476
489
  if (!blocks.length && !nestedBlocks.length) blocks.push({ type: 'paragraph', text: '' });
477
490
  } else {
478
- const leaderText = plainTextOf(inline);
491
+ let leaderText = plainTextOf(inline);
492
+ if (item.task) leaderText = leaderText.replace(TASK_MARKER_RE, '');
479
493
  if (leaderText.trim() || !nestedBlocks.length) blocks.push({ type: 'paragraph', text: leaderText });
480
494
  }
481
495
  blocks.push(...nestedBlocks);
@@ -761,6 +775,18 @@ function stripMediaMarkdown(markdown) {
761
775
  return projected.trim() ? projected : '';
762
776
  }
763
777
 
778
+ // Does this string still carry media markdown? Deliberately the union of the
779
+ // patterns stripMediaMarkdown removes — a complete construct, a wrapper tag,
780
+ // and the dangling unterminated fragment — so a caller checking "did anything
781
+ // survive that the stripped body would not contain?" cannot disagree with the
782
+ // stripper it would fall back to.
783
+ function carriesMediaMarkdown(text) {
784
+ if (typeof text !== 'string' || text.length === 0) return false;
785
+ return IMAGE_RE.test(text)
786
+ || MEDIA_WRAP_RE.test(text)
787
+ || TRAILING_IMAGE_FRAGMENT_RE.test(text);
788
+ }
789
+
764
790
  /**
765
791
  * toTelegramRichBlocks(markdown, opts) -> { blocks: RichBlock[], usedRich: boolean }
766
792
  *
@@ -908,10 +934,12 @@ module.exports = {
908
934
  isRichContentError,
909
935
  errorMessage,
910
936
  stripMediaMarkdown,
937
+ carriesMediaMarkdown,
911
938
  countMediaBlocks,
912
939
  // exported for tests / introspection, not part of the public contract
913
940
  _plainTextOf: plainTextOf,
914
941
  _blocksFromTokens: blocksFromTokens,
915
942
  _stripFencedCodeBlocks: stripFencedCodeBlocks,
943
+ IMAGE_RE,
916
944
  _collectMediaDescriptors: collectMediaDescriptors,
917
945
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.24.1",
3
+ "version": "0.25.1",
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": {