polygram 0.23.3 → 0.24.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.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Delivery strategy for the reply tool: render one reply as rich blocks, or
3
+ * decline and let the caller's chunked path deliver it.
4
+ *
5
+ * This is the piece the channels dispatcher injects into the shared reply
6
+ * pipeline. It lives here rather than in the dispatcher because rich-media.js
7
+ * requires the dispatcher module — importing the rich modules from there
8
+ * would close a require cycle — and because the decision logic is worth
9
+ * testing without a dispatcher around it.
10
+ *
11
+ * Text only. Rendering runs on media-stripped text, so `![caption](/abs/path)`
12
+ * degrades to its caption and image syntax cannot be the reason a reply goes
13
+ * rich. That keeps local paths out of the chat on every branch and keeps the
14
+ * media trust surface (path validation, size caps, TOCTOU) off this path
15
+ * entirely.
16
+ *
17
+ * Declining is always safe: the pipeline falls back to the chunked path that
18
+ * has always worked. Nothing here may throw its way out.
19
+ */
20
+
21
+ 'use strict';
22
+
23
+ const {
24
+ toTelegramRichBlocks,
25
+ stripMediaMarkdown,
26
+ RICH_MAX_LEN,
27
+ } = require('./rich');
28
+
29
+ /**
30
+ * @param {object} deps
31
+ * @param {object} deps.bot — grammy Bot instance
32
+ * @param {Function} deps.sendRich — createRichSender()'s sender
33
+ * @param {(chatId, threadId) => boolean} deps.isRichTextEnabled — resolved per call
34
+ * against live config, so a config change mid-session takes effect immediately
35
+ * @param {() => boolean} deps.getRichKnownUnsupported — process-wide capability latch
36
+ * @param {Function} [deps.toRichBlocks] — markdown → { blocks, usedRich }
37
+ * @param {(s: string) => string} [deps.redactError] — strips bot tokens from logged
38
+ * error text; network error shapes can embed the request URL
39
+ * @param {number} [deps.richMaxLen]
40
+ * @param {object} [deps.logger]
41
+ * @returns {(ctx: {sessionKey, sessionCwd, chatId, threadId}) => Function} strategy factory
42
+ */
43
+ function createRichDeliveryFactory({
44
+ bot,
45
+ sendRich,
46
+ isRichTextEnabled,
47
+ getRichKnownUnsupported = () => false,
48
+ toRichBlocks = toTelegramRichBlocks,
49
+ richMaxLen = RICH_MAX_LEN,
50
+ redactError = (s) => s,
51
+ logger = console,
52
+ } = {}) {
53
+ if (typeof sendRich !== 'function') {
54
+ throw new TypeError('rich-dispatch: sendRich required');
55
+ }
56
+ if (typeof isRichTextEnabled !== 'function') {
57
+ throw new TypeError('rich-dispatch: isRichTextEnabled required');
58
+ }
59
+
60
+ // Per-call factory: the chat/topic identity is fixed for a reply, but the
61
+ // gate is re-resolved on every delivery so live config edits apply without
62
+ // a respawn.
63
+ return function makeDeliverText({ chatId, threadId } = {}) {
64
+ return async function deliverText({ text, replyToMessageId = null, meta = {} } = {}) {
65
+ // Flag off → this chat has not opted into rich at all. Behave exactly
66
+ // as before, raw markdown included: rewriting text here would change
67
+ // delivery for chats that asked for nothing.
68
+ if (!isRichTextEnabled(chatId, threadId)) return { handled: false };
69
+
70
+ // From here the chat IS rich-enabled, so no branch may render a local
71
+ // path — including the branches that end up delivering plain.
72
+ const body = stripMediaMarkdown(text) ?? '';
73
+
74
+ if (getRichKnownUnsupported()) return { handled: false, text: body };
75
+ // Measured on the fallback body, which is what a decline delivers.
76
+ if (body.length > richMaxLen) return { handled: false, text: body };
77
+
78
+ let blocks;
79
+ try {
80
+ const rendered = toRichBlocks(body);
81
+ if (!rendered?.usedRich) return { handled: false, text: body };
82
+ blocks = rendered.blocks;
83
+ } catch (err) {
84
+ logger?.error?.(`[rich-dispatch] render failed: ${redactError(err.message)}`);
85
+ return { handled: false, text: body };
86
+ }
87
+
88
+ let out;
89
+ try {
90
+ // Direct send is the only mechanism here; the plain-send-then-rich-edit
91
+ // contingency is deliberately unimplemented, gated on the live gate that
92
+ // establishes whether this verb honors message_thread_id and reply_parameters.
93
+ out = await sendRich({
94
+ bot,
95
+ chatId,
96
+ threadId,
97
+ blocks,
98
+ // The transcript keeps what the agent actually wrote; the operator's
99
+ // own DB is the accepted resting place for local paths, and the
100
+ // background secret sweep covers the row.
101
+ sourceText: text,
102
+ // Mirrors the chunked path's anchor. allow_sending_without_reply
103
+ // matters more here, not less: a long turn gives the user time to
104
+ // delete the message being answered, and without the flag Telegram
105
+ // rejects the whole send with MESSAGE_NOT_FOUND — which this path
106
+ // would misread as a generic rich failure and quietly downgrade.
107
+ replyParams: replyToMessageId != null
108
+ ? { message_id: replyToMessageId, allow_sending_without_reply: true }
109
+ : null,
110
+ meta,
111
+ });
112
+ } catch (err) {
113
+ // sendRich is contracted not to throw. Not depending on that is the
114
+ // difference between a flat reply and a lost one.
115
+ // The branch exists because the no-throw contract might be broken;
116
+ // it must not then assume the error is free of request URLs.
117
+ logger?.error?.(`[rich-dispatch] send threw unexpectedly: ${redactError(err.message)}`);
118
+ return { handled: false, text: body };
119
+ }
120
+
121
+ if (!out?.wentRich) return { handled: false, text: body };
122
+
123
+ const messageId = out.result?.message_id;
124
+ return {
125
+ handled: true,
126
+ sent: messageId != null ? [{ message_id: messageId }] : [],
127
+ failed: [],
128
+ results: [out.result],
129
+ };
130
+ };
131
+ };
132
+ }
133
+
134
+ module.exports = { createRichDeliveryFactory };
@@ -90,6 +90,11 @@ function defaultMakeInputFile(source) {
90
90
  * userinfo from apiRoot before logging
91
91
  * @param {(source: string) => *} [deps.makeInputFile] — { source } envelope →
92
92
  * uploadable file for grammy (test seam)
93
+ * @param {object} [deps.capabilityLatch] — shared latch decision (see
94
+ * rich-capability-latch.js). Pass the SAME instance the send path uses so a
95
+ * bare 404 on either counts toward one run of strikes. Omitted, every
96
+ * capability error latches immediately, which is this module's legacy
97
+ * behavior.
93
98
  * @param {(text: string) => string} [deps.sanitizeFallbackText] — applied to
94
99
  * sourceText on every plain-fallback edit (polygram wires
95
100
  * stripMediaMarkdown; default identity preserves legacy callers)
@@ -108,7 +113,12 @@ function createRichEditor({
108
113
  stripUrlCreds = (s) => s,
109
114
  makeInputFile = defaultMakeInputFile,
110
115
  sanitizeFallbackText = (s) => s,
116
+ capabilityLatch = null,
111
117
  } = {}) {
118
+ const latch = capabilityLatch || {
119
+ recordCapabilityError: () => { setRichKnownUnsupported(); return true; },
120
+ recordHealthyOutcome: () => {},
121
+ };
112
122
  async function rescueBestEffort({
113
123
  mediaContext,
114
124
  blocks,
@@ -160,6 +170,7 @@ function createRichEditor({
160
170
  ),
161
171
  },
162
172
  }, { source: 'bot-reply-stream-edit-rich', botName, richSourceText: sourceText });
173
+ latch.recordHealthyOutcome();
163
174
  mediaContext?.learnRichResult?.(blocks, res);
164
175
  // Record successful rich deliveries without storing message content.
165
176
  logEvent('rich-message-sent', {
@@ -178,15 +189,28 @@ function createRichEditor({
178
189
  error: 'media-source-changed',
179
190
  });
180
191
  } else if (isRichCapabilityError(err)) {
192
+ // This edit degrades either way; the latch decides whether every
193
+ // LATER rich message on every path degrades too. A bare 404 is also
194
+ // what a restarting bot-api server returns, so it takes two in a row.
181
195
  fallbackKind = 'capability';
182
- setRichKnownUnsupported();
183
- logEvent('rich-capability-latched', {
184
- chat_id: chatId, bot: botName,
185
- api_root: stripUrlCreds(getApiRoot() || 'cloud'),
186
- error: redactBotToken(err.message)?.slice(0, 200),
187
- });
196
+ if (latch.recordCapabilityError(err, 'edit')) {
197
+ logEvent('rich-capability-latched', {
198
+ chat_id: chatId, bot: botName,
199
+ api_root: stripUrlCreds(getApiRoot() || 'cloud'),
200
+ error: redactBotToken(err.message)?.slice(0, 200),
201
+ });
202
+ } else {
203
+ logEvent('rich-capability-strike', {
204
+ chat_id: chatId, thread_id: threadId, bot: botName,
205
+ transport: 'edit',
206
+ error: redactBotToken(err.message)?.slice(0, 200),
207
+ });
208
+ }
188
209
  } else if (isRichContentError(err)) {
189
210
  fallbackKind = 'content-error';
211
+ // The server read and rejected this payload, so the endpoint is
212
+ // demonstrably there — that breaks any run of ambiguous 404s.
213
+ latch.recordHealthyOutcome();
190
214
  mediaContext?.evictCachedBlocks?.(blocks);
191
215
  logEvent('rich-content-fallback', {
192
216
  chat_id: chatId, bot: botName,
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Rich-message send-with-fallback — the send-side counterpart to
3
+ * rich-edit.js.
4
+ *
5
+ * The asymmetry with rich-edit is deliberate. An edit acts on a bubble that
6
+ * already exists, so a transient failure can be rethrown for the streamer's
7
+ * retry logic to handle. A send has no bubble yet: its caller holds the only
8
+ * copy of the reply and owns a plain chunked path that always works. So this
9
+ * function NEVER throws and never rethrows. Every failure returns
10
+ * `wentRich: false` and the caller delivers plain — error classification
11
+ * decides only whether to latch the capability off, never whether the user
12
+ * gets the message.
13
+ *
14
+ * Transcript rows are inserted HERE, on success only. api.js deliberately
15
+ * leaves sendRichMessage untracked: a tracked pending row would persist the
16
+ * failed attempt, the plain fallback would then insert its own rows, and the
17
+ * agent's preloaded history would show the same answer twice.
18
+ */
19
+
20
+ 'use strict';
21
+
22
+ const { createRichCapabilityLatch } = require('./rich-capability-latch');
23
+
24
+ /**
25
+ * @param {object} deps
26
+ * @param {(bot, method, params, meta) => Promise<*>} deps.tg
27
+ * @param {string} deps.botName
28
+ * @param {(kind: string, detail: object) => void} deps.logEvent
29
+ * @param {(s: string) => string} deps.redactBotToken
30
+ * @param {(err) => boolean} deps.isRichCapabilityError
31
+ * @param {(err) => boolean} deps.isRichCapabilityErrorExplicit — capability error
32
+ * that NAMES the missing capability, as opposed to a bare 404
33
+ * @param {(err) => boolean} deps.isRichContentError
34
+ * @param {() => boolean} deps.getRichKnownUnsupported
35
+ * @param {() => void} deps.setRichKnownUnsupported — marks the latch tripped
36
+ * @param {() => (string|null)} [deps.getApiRoot] — for the latch-trip log line only
37
+ * @param {(url: string) => string} [deps.stripUrlCreds] — strips basic-auth
38
+ * userinfo from apiRoot before logging
39
+ * @param {(row: object) => void} [deps.insertSentRow] — persists the outbound
40
+ * transcript row; best-effort, never blocks delivery
41
+ * @param {object} [deps.capabilityLatch] — shared latch decision; pass the SAME
42
+ * instance the edit path uses so a bare 404 on either counts toward one run
43
+ * @param {object} [deps.logger]
44
+ * @returns {(args: {bot, chatId: string, threadId?: (string|number|null), blocks: Array,
45
+ * sourceText: string, replyParams?: object, meta?: object})
46
+ * => Promise<{wentRich: boolean, result?: *}>}
47
+ */
48
+ function createRichSender({
49
+ tg,
50
+ botName,
51
+ logEvent = () => {},
52
+ redactBotToken = (s) => s,
53
+ isRichCapabilityError,
54
+ isRichCapabilityErrorExplicit,
55
+ isRichContentError,
56
+ getRichKnownUnsupported = () => false,
57
+ setRichKnownUnsupported = () => {},
58
+ getApiRoot = () => null,
59
+ stripUrlCreds = (s) => s,
60
+ insertSentRow = null,
61
+ capabilityLatch = null,
62
+ logger = console,
63
+ } = {}) {
64
+ // Shared with the edit path when the caller passes one in: both trip the
65
+ // same process-wide flag, so a per-module counter would let either path
66
+ // latch on its first bare 404 while the other believed it was protected.
67
+ const latch = capabilityLatch || createRichCapabilityLatch({
68
+ isExplicit: isRichCapabilityErrorExplicit,
69
+ setUnsupported: setRichKnownUnsupported,
70
+ });
71
+
72
+ return async function sendRich({
73
+ bot,
74
+ chatId,
75
+ threadId = null,
76
+ blocks,
77
+ sourceText,
78
+ replyParams = null,
79
+ meta = {},
80
+ }) {
81
+ if (getRichKnownUnsupported()) return { wentRich: false };
82
+ if (!Array.isArray(blocks) || blocks.length === 0) return { wentRich: false };
83
+
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
+ let result;
92
+ try {
93
+ result = await tg(bot, 'sendRichMessage', params, {
94
+ ...meta,
95
+ source: meta.source || 'bot-reply-rich-send',
96
+ botName,
97
+ richSourceText: sourceText,
98
+ });
99
+ } catch (err) {
100
+ classifyFailure(err, chatId, threadId);
101
+ return { wentRich: false };
102
+ }
103
+
104
+ latch.recordHealthyOutcome();
105
+
106
+ // A resolved response with no message_id cannot be honored: the reply tool
107
+ // promises the agent an id it can edit, and without one there is no
108
+ // ownership claim and no transcript row either. Treat it as a content-class
109
+ // failure so the caller delivers plain rather than reporting a success the
110
+ // agent cannot act on. Trade-off, stated plainly: if the server DID create
111
+ // 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.
113
+ const messageId = result?.message_id;
114
+ if (messageId == null) {
115
+ logEvent('rich-content-fallback', {
116
+ chat_id: chatId, thread_id: threadId, bot: botName,
117
+ transport: 'send',
118
+ error: 'response carried no message_id',
119
+ });
120
+ return { wentRich: false };
121
+ }
122
+
123
+ // The message has landed. Nothing below may change that verdict: a throw
124
+ // escaping from here would be caught upstream as "rich did not happen",
125
+ // and the caller would deliver the very same reply again as plain text.
126
+ // The bookkeeping is best-effort; the send is not.
127
+ try {
128
+ if (typeof insertSentRow === 'function') {
129
+ insertSentRow({
130
+ chat_id: chatId,
131
+ thread_id: threadId != null ? String(threadId) : null,
132
+ msg_id: messageId,
133
+ text: sourceText || '',
134
+ direction: 'out',
135
+ status: 'sent',
136
+ source: meta.source || 'bot-reply-rich-send',
137
+ bot_name: botName,
138
+ turn_id: meta.turnId || null,
139
+ session_id: meta.sessionId || null,
140
+ reply_to_id: replyParams?.message_id ?? null,
141
+ ts: result?.date ? result.date * 1000 : Date.now(),
142
+ });
143
+ }
144
+
145
+ logEvent('rich-message-sent', {
146
+ chat_id: chatId,
147
+ thread_id: threadId,
148
+ bot: botName,
149
+ transport: 'send',
150
+ block_count: blocks.length,
151
+ char_count: sourceText?.length ?? null,
152
+ message_id: messageId,
153
+ });
154
+
155
+ // A dropped topic does not error — the message simply lands in the
156
+ // group's General topic instead, mis-delivering every rich reply in a
157
+ // forum chat with nothing in the logs to say so. Compare what came back
158
+ // against what was asked for, on every send rather than only at the
159
+ // one-off gate that first established the behavior.
160
+ if (threadId != null) {
161
+ const echoed = result?.message_thread_id;
162
+ if (echoed == null || String(echoed) !== String(threadId)) {
163
+ logEvent('rich-send-thread-mismatch', {
164
+ chat_id: chatId, bot: botName,
165
+ requested_thread_id: String(threadId),
166
+ echoed_thread_id: echoed == null ? null : String(echoed),
167
+ });
168
+ }
169
+ }
170
+ } catch (e) {
171
+ logger?.error?.(`[telegram] rich-send bookkeeping failed after delivery: ${e.message}`);
172
+ }
173
+
174
+ return { wentRich: true, result };
175
+ };
176
+
177
+ function classifyFailure(err, chatId, threadId) {
178
+ if (safeTest(isRichCapabilityError, err)) {
179
+ if (latch.recordCapabilityError(err, 'send')) {
180
+ logCapabilityLatched(err, chatId);
181
+ } else {
182
+ logEvent('rich-capability-strike', {
183
+ chat_id: chatId, thread_id: threadId, bot: botName,
184
+ transport: 'send',
185
+ error: redactBotToken(errText(err))?.slice(0, 200),
186
+ });
187
+ }
188
+ return;
189
+ }
190
+
191
+ // A rejection of this payload proves the endpoint is present and
192
+ // answering, so it breaks any run of ambiguous 404s.
193
+ latch.recordHealthyOutcome();
194
+
195
+ if (safeTest(isRichContentError, err)) {
196
+ logEvent('rich-content-fallback', {
197
+ chat_id: chatId, thread_id: threadId, bot: botName,
198
+ transport: 'send',
199
+ error: redactBotToken(errText(err))?.slice(0, 200),
200
+ });
201
+ return;
202
+ }
203
+
204
+ // Soak note: api.js already logs telegram-api-error for the same failure,
205
+ // exactly as it does for rich edits. Count one or the other, not both.
206
+ logEvent('rich-send-error', {
207
+ chat_id: chatId, thread_id: threadId, bot: botName,
208
+ error_class: err?.name || 'Error',
209
+ error: redactBotToken(errText(err))?.slice(0, 200),
210
+ });
211
+ }
212
+
213
+ function logCapabilityLatched(err, chatId) {
214
+ logEvent('rich-capability-latched', {
215
+ chat_id: chatId, bot: botName,
216
+ transport: 'send',
217
+ api_root: stripUrlCreds(getApiRoot() || 'cloud'),
218
+ error: redactBotToken(errText(err))?.slice(0, 200),
219
+ });
220
+ }
221
+ }
222
+
223
+ // Classification runs on whatever was thrown, including non-Error values.
224
+ // A predicate that chokes on an odd shape must not become the reason a
225
+ // reply is lost.
226
+ function safeTest(fn, err) {
227
+ if (typeof fn !== 'function') return false;
228
+ try { return fn(err) === true; }
229
+ catch { return false; }
230
+ }
231
+
232
+ function errText(err) {
233
+ if (!err) return '';
234
+ return String(err.description || err.message || err);
235
+ }
236
+
237
+ module.exports = { createRichSender };
@@ -22,7 +22,7 @@
22
22
  'use strict';
23
23
 
24
24
  const { Marked } = require('marked');
25
- const { getTopicConfig } = require('../session-key');
25
+ const { resolveBoolOverride } = require('../config-override');
26
26
 
27
27
  // ─── Per-chat opt-in resolution ──────────────────────────────────────
28
28
  //
@@ -30,15 +30,7 @@ const { getTopicConfig } = require('../session-key');
30
30
  // bot, then defaults. `config.bot` is already filtered to the active bot
31
31
  // during startup.
32
32
  function resolveRichTextEnabled(config, chatId, threadId = null) {
33
- if (!config) return false;
34
- const chat = config.chats?.[String(chatId)] || null;
35
- const topicCfg = (chat && threadId != null) ? getTopicConfig(chat, String(threadId)) : null;
36
- const pick = (v) => (typeof v === 'boolean' ? v : undefined);
37
- const resolved = pick(topicCfg?.richText)
38
- ?? pick(chat?.richText)
39
- ?? pick(config.bot?.richText)
40
- ?? pick(config.defaults?.richText);
41
- return resolved === true;
33
+ return resolveBoolOverride(config, 'richText', chatId, threadId);
42
34
  }
43
35
 
44
36
  // ─── Content-adaptive gate ───────────────────────────────────────────
@@ -191,9 +183,89 @@ const DEFAULT_DETAILS_SUMMARY = 'Details';
191
183
  // backtrack, and this text is agent output a user can influence.
192
184
  const MEDIA_WRAP_OPEN_RE = /<tg-(collage|slideshow)(?:[ \t][^>]*)?>/i;
193
185
  const MEDIA_WRAP_CLOSE_RE = /<\/tg-(?:collage|slideshow)>/i;
194
- // Extraction form of IMAGE_RE: alt, src, optional quoted title. Single
195
- // negated character classes only — linear on adversarial input.
196
- const IMAGE_MD_G_RE = /!\[([^\]\n]*)\]\(([^)\s]+)(?:[ \t]+"([^"\n]*)")?\)/g;
186
+ // A markdown target may carry an optional quoted title after the source.
187
+ const IMAGE_TITLE_RE = /^([\s\S]*?)[ \t]+"([^"]*)"$/;
188
+
189
+ // → { src, title }
190
+ function splitImageTarget(target) {
191
+ const raw = String(target ?? '').trim();
192
+ const m = IMAGE_TITLE_RE.exec(raw);
193
+ const src = m ? m[1].trim() : raw;
194
+ return { src, title: m ? m[2] : '' };
195
+ }
196
+
197
+ // Image constructs are scanned rather than matched by regex because their
198
+ // destination is not a regular language: it may contain balanced parentheses
199
+ // ("screenshot (1).png", "Docs (2024)/x.png") or be wrapped in <…> to hold
200
+ // spaces. A regex that stops at the first ')' ends mid-path and leaves the
201
+ // remainder of the filename behind as literal text — a partial path
202
+ // disclosure that reads as ordinary prose. The scanner is a single forward
203
+ // pass, so it is linear on adversarial input by construction.
204
+ //
205
+ // Returns { end, alt, src, title } for the construct starting at `start`, or
206
+ // null when it does not terminate on this line. Callers treat null as
207
+ // "no safe parse" and drop the construct rather than emit a fragment of it.
208
+ function parseImageAt(line, start) {
209
+ if (line[start] !== '!' || line[start + 1] !== '[') return null;
210
+ let i = start + 2;
211
+ while (i < line.length && line[i] !== ']') {
212
+ if (line[i] === '\\') i += 1;
213
+ i += 1;
214
+ }
215
+ if (i >= line.length) return null;
216
+ const alt = line.slice(start + 2, i);
217
+ i += 1;
218
+ if (line[i] !== '(') return null;
219
+ i += 1;
220
+
221
+ let src = '';
222
+ let title = '';
223
+ if (line[i] === '<') {
224
+ const close = line.indexOf('>', i + 1);
225
+ if (close === -1) return null;
226
+ src = line.slice(i + 1, close);
227
+ i = close + 1;
228
+ // Optional quoted title, then the closing paren.
229
+ const rest = line.slice(i);
230
+ const m = /^[ \t]*(?:"([^"\n]*)")?[ \t]*\)/.exec(rest);
231
+ if (!m) return null;
232
+ title = m[1] || '';
233
+ i += m[0].length;
234
+ } else {
235
+ const targetStart = i;
236
+ let depth = 1;
237
+ while (i < line.length) {
238
+ const c = line[i];
239
+ if (c === '\\') { i += 2; continue; }
240
+ if (c === '(') depth += 1;
241
+ else if (c === ')') { depth -= 1; if (depth === 0) break; }
242
+ i += 1;
243
+ }
244
+ if (i >= line.length || depth !== 0) return null;
245
+ ({ src, title } = splitImageTarget(line.slice(targetStart, i)));
246
+ i += 1;
247
+ }
248
+ return { end: i, alt, src, title };
249
+ }
250
+
251
+ // Walk one line's image constructs. `onImage` decides what each becomes in
252
+ // the projected text; an unparseable construct truncates the line there,
253
+ // since anything after it is the tail of a destination we could not read.
254
+ function rewriteImageConstructs(line, onImage) {
255
+ if (line.indexOf('![') === -1) return line;
256
+ let out = '';
257
+ let i = 0;
258
+ while (i < line.length) {
259
+ const next = line.indexOf('![', i);
260
+ if (next === -1) { out += line.slice(i); break; }
261
+ out += line.slice(i, next);
262
+ const parsed = parseImageAt(line, next);
263
+ if (!parsed) return out;
264
+ out += onImage(parsed);
265
+ i = parsed.end;
266
+ }
267
+ return out;
268
+ }
197
269
 
198
270
  function mediaDescriptor(src, caption) {
199
271
  return { type: '_media', src: src || '', caption: (caption || '').trim() };
@@ -201,11 +273,20 @@ function mediaDescriptor(src, caption) {
201
273
 
202
274
  // Pull image markdown out of a raw text span (used for wrapper bodies
203
275
  // that arrive as one opaque html token).
276
+ // Deliberately NOT the scanner above. This feeds the media RESOLVER — the
277
+ // path that validates and uploads local files — so its accepted-source class
278
+ // is a trust boundary, not a display concern. The scanner widened what counts
279
+ // as a destination to close a projection leak; applying that widening here
280
+ // would quietly extend what the resolver is asked to upload. The two are
281
+ // allowed to disagree in exactly this direction: the projection may strip
282
+ // more than the extractor resolves, never less.
283
+ const IMAGE_MD_EXTRACT_G_RE = /!\[([^\]\n]*)\]\(([^)\s]+)(?:[ \t]+"([^"\n]*)")?\)/g;
284
+
204
285
  function extractMediaItems(text) {
205
286
  const items = [];
206
- IMAGE_MD_G_RE.lastIndex = 0;
287
+ IMAGE_MD_EXTRACT_G_RE.lastIndex = 0;
207
288
  let m;
208
- while ((m = IMAGE_MD_G_RE.exec(text)) !== null) {
289
+ while ((m = IMAGE_MD_EXTRACT_G_RE.exec(text)) !== null) {
209
290
  items.push(mediaDescriptor(m[2], m[1] || m[3]));
210
291
  }
211
292
  return items;
@@ -659,10 +740,10 @@ function stripMediaMarkdown(markdown) {
659
740
  continue;
660
741
  }
661
742
  if (fence) { out.push(line); continue; }
662
- IMAGE_MD_G_RE.lastIndex = 0;
663
- let clean = line
664
- .replace(IMAGE_MD_G_RE, (_all, alt, _src, title) => (alt || title || '').trim())
665
- .replace(MEDIA_WRAP_TAG_G_RE, '');
743
+ let clean = rewriteImageConstructs(
744
+ line,
745
+ ({ alt, title }) => (alt || title || '').trim(),
746
+ ).replace(MEDIA_WRAP_TAG_G_RE, '');
666
747
  // Only a fragment on the FINAL line can still be completed by
667
748
  // text that hasn't streamed in yet; earlier lines can't (image
668
749
  // syntax never spans lines), so a fragment there is plain
@@ -767,10 +848,31 @@ function errorMessage(err) {
767
848
  return String(err.description || err.message || err.error_message || err);
768
849
  }
769
850
 
851
+ // The server NAMED the capability it cannot provide. Worth separating from
852
+ // a bare 404 because the two carry different confidence: this response can
853
+ // only come from a server that read our payload, while a 404 is also what a
854
+ // restarting or momentarily misrouted server returns. Callers that latch
855
+ // permanently use this to decide how much evidence one error is worth.
856
+ function isRichCapabilityErrorExplicit(err) {
857
+ if (!err) return false;
858
+ return RICH_CAPABILITY_ERR_RE.test(errorMessage(err));
859
+ }
860
+
861
+ // A rejection of the `rich_message` FIELD, as opposed to a missing METHOD.
862
+ // The distinction decides blast radius: both verbs carry this field, so a
863
+ // server that cannot read it cannot serve either — while "method
864
+ // sendRichMessage not found" says nothing about editMessageText, which a
865
+ // server may well implement and be serving right now.
866
+ const RICH_MESSAGE_FIELD_ERR_RE = /(?:unknown|unsupported|unrecognized)\s+(?:parameter|field)s?\s*["']?rich_message["']?|rich_message\s*["']?\s*(?:is\s+)?(?:unknown|unsupported|unrecognized|not\s+supported)|rich message must be non-empty/i;
867
+
868
+ function isRichMessageFieldRejection(err) {
869
+ if (!err) return false;
870
+ return RICH_MESSAGE_FIELD_ERR_RE.test(errorMessage(err));
871
+ }
872
+
770
873
  function isRichCapabilityError(err) {
771
874
  if (!err) return false;
772
- const msg = errorMessage(err);
773
- if (RICH_CAPABILITY_ERR_RE.test(msg)) return true;
875
+ if (isRichCapabilityErrorExplicit(err)) return true;
774
876
  // A 404 is sufficient because these checks only wrap rich-message calls.
775
877
  const status = err.error_code ?? err.status ?? err.statusCode;
776
878
  return status === 404;
@@ -783,11 +885,20 @@ function isRichContentError(err) {
783
885
  return RICH_CONTENT_ERR_RE.test(errorMessage(err));
784
886
  }
785
887
 
888
+ // Rich messages carry a larger Bot API character cap than plain ones. This is
889
+ // the value for surfaces that can import it; streamer.js is deliberately
890
+ // dependency-free and carries the same number as its own default, so the two
891
+ // must be changed together.
892
+ const RICH_MAX_LEN = 32768;
893
+
786
894
  module.exports = {
787
895
  needsRichRendering,
788
896
  toTelegramRichBlocks,
897
+ RICH_MAX_LEN,
789
898
  resolveRichTextEnabled,
790
899
  isRichCapabilityError,
900
+ isRichCapabilityErrorExplicit,
901
+ isRichMessageFieldRejection,
791
902
  isRichContentError,
792
903
  errorMessage,
793
904
  stripMediaMarkdown,