polygram 0.23.3 → 0.24.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.
@@ -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 ───────────────────────────────────────────
@@ -147,7 +139,13 @@ function plainTextOf(tokens) {
147
139
  if (!Array.isArray(tokens)) return '';
148
140
  let out = '';
149
141
  for (const t of tokens) {
150
- if (t.type === 'text' || t.type === 'codespan' || t.type === 'escape') {
142
+ if (t.type === 'text' && Array.isArray(t.tokens)) {
143
+ // marked wraps a list item's inline run in a block-level 'text'
144
+ // token whose .text is the RAW source (markers included) and whose
145
+ // .tokens carry the parsed inline children — recurse, or bold and
146
+ // code-span markers ship to the chat as literal characters.
147
+ out += plainTextOf(t.tokens);
148
+ } else if (t.type === 'text' || t.type === 'codespan' || t.type === 'escape') {
151
149
  out += t.text ?? '';
152
150
  } else if (t.type === 'link' || t.type === 'image') {
153
151
  out += plainTextOf(t.tokens) || t.text || t.href || '';
@@ -191,9 +189,89 @@ const DEFAULT_DETAILS_SUMMARY = 'Details';
191
189
  // backtrack, and this text is agent output a user can influence.
192
190
  const MEDIA_WRAP_OPEN_RE = /<tg-(collage|slideshow)(?:[ \t][^>]*)?>/i;
193
191
  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;
192
+ // A markdown target may carry an optional quoted title after the source.
193
+ const IMAGE_TITLE_RE = /^([\s\S]*?)[ \t]+"([^"]*)"$/;
194
+
195
+ // → { src, title }
196
+ function splitImageTarget(target) {
197
+ const raw = String(target ?? '').trim();
198
+ const m = IMAGE_TITLE_RE.exec(raw);
199
+ const src = m ? m[1].trim() : raw;
200
+ return { src, title: m ? m[2] : '' };
201
+ }
202
+
203
+ // Image constructs are scanned rather than matched by regex because their
204
+ // destination is not a regular language: it may contain balanced parentheses
205
+ // ("screenshot (1).png", "Docs (2024)/x.png") or be wrapped in <…> to hold
206
+ // spaces. A regex that stops at the first ')' ends mid-path and leaves the
207
+ // remainder of the filename behind as literal text — a partial path
208
+ // disclosure that reads as ordinary prose. The scanner is a single forward
209
+ // pass, so it is linear on adversarial input by construction.
210
+ //
211
+ // Returns { end, alt, src, title } for the construct starting at `start`, or
212
+ // null when it does not terminate on this line. Callers treat null as
213
+ // "no safe parse" and drop the construct rather than emit a fragment of it.
214
+ function parseImageAt(line, start) {
215
+ if (line[start] !== '!' || line[start + 1] !== '[') return null;
216
+ let i = start + 2;
217
+ while (i < line.length && line[i] !== ']') {
218
+ if (line[i] === '\\') i += 1;
219
+ i += 1;
220
+ }
221
+ if (i >= line.length) return null;
222
+ const alt = line.slice(start + 2, i);
223
+ i += 1;
224
+ if (line[i] !== '(') return null;
225
+ i += 1;
226
+
227
+ let src = '';
228
+ let title = '';
229
+ if (line[i] === '<') {
230
+ const close = line.indexOf('>', i + 1);
231
+ if (close === -1) return null;
232
+ src = line.slice(i + 1, close);
233
+ i = close + 1;
234
+ // Optional quoted title, then the closing paren.
235
+ const rest = line.slice(i);
236
+ const m = /^[ \t]*(?:"([^"\n]*)")?[ \t]*\)/.exec(rest);
237
+ if (!m) return null;
238
+ title = m[1] || '';
239
+ i += m[0].length;
240
+ } else {
241
+ const targetStart = i;
242
+ let depth = 1;
243
+ while (i < line.length) {
244
+ const c = line[i];
245
+ if (c === '\\') { i += 2; continue; }
246
+ if (c === '(') depth += 1;
247
+ else if (c === ')') { depth -= 1; if (depth === 0) break; }
248
+ i += 1;
249
+ }
250
+ if (i >= line.length || depth !== 0) return null;
251
+ ({ src, title } = splitImageTarget(line.slice(targetStart, i)));
252
+ i += 1;
253
+ }
254
+ return { end: i, alt, src, title };
255
+ }
256
+
257
+ // Walk one line's image constructs. `onImage` decides what each becomes in
258
+ // the projected text; an unparseable construct truncates the line there,
259
+ // since anything after it is the tail of a destination we could not read.
260
+ function rewriteImageConstructs(line, onImage) {
261
+ if (line.indexOf('![') === -1) return line;
262
+ let out = '';
263
+ let i = 0;
264
+ while (i < line.length) {
265
+ const next = line.indexOf('![', i);
266
+ if (next === -1) { out += line.slice(i); break; }
267
+ out += line.slice(i, next);
268
+ const parsed = parseImageAt(line, next);
269
+ if (!parsed) return out;
270
+ out += onImage(parsed);
271
+ i = parsed.end;
272
+ }
273
+ return out;
274
+ }
197
275
 
198
276
  function mediaDescriptor(src, caption) {
199
277
  return { type: '_media', src: src || '', caption: (caption || '').trim() };
@@ -201,11 +279,20 @@ function mediaDescriptor(src, caption) {
201
279
 
202
280
  // Pull image markdown out of a raw text span (used for wrapper bodies
203
281
  // that arrive as one opaque html token).
282
+ // Deliberately NOT the scanner above. This feeds the media RESOLVER — the
283
+ // path that validates and uploads local files — so its accepted-source class
284
+ // is a trust boundary, not a display concern. The scanner widened what counts
285
+ // as a destination to close a projection leak; applying that widening here
286
+ // would quietly extend what the resolver is asked to upload. The two are
287
+ // allowed to disagree in exactly this direction: the projection may strip
288
+ // more than the extractor resolves, never less.
289
+ const IMAGE_MD_EXTRACT_G_RE = /!\[([^\]\n]*)\]\(([^)\s]+)(?:[ \t]+"([^"\n]*)")?\)/g;
290
+
204
291
  function extractMediaItems(text) {
205
292
  const items = [];
206
- IMAGE_MD_G_RE.lastIndex = 0;
293
+ IMAGE_MD_EXTRACT_G_RE.lastIndex = 0;
207
294
  let m;
208
- while ((m = IMAGE_MD_G_RE.exec(text)) !== null) {
295
+ while ((m = IMAGE_MD_EXTRACT_G_RE.exec(text)) !== null) {
209
296
  items.push(mediaDescriptor(m[2], m[1] || m[3]));
210
297
  }
211
298
  return items;
@@ -659,10 +746,10 @@ function stripMediaMarkdown(markdown) {
659
746
  continue;
660
747
  }
661
748
  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, '');
749
+ let clean = rewriteImageConstructs(
750
+ line,
751
+ ({ alt, title }) => (alt || title || '').trim(),
752
+ ).replace(MEDIA_WRAP_TAG_G_RE, '');
666
753
  // Only a fragment on the FINAL line can still be completed by
667
754
  // text that hasn't streamed in yet; earlier lines can't (image
668
755
  // syntax never spans lines), so a fragment there is plain
@@ -767,10 +854,31 @@ function errorMessage(err) {
767
854
  return String(err.description || err.message || err.error_message || err);
768
855
  }
769
856
 
857
+ // The server NAMED the capability it cannot provide. Worth separating from
858
+ // a bare 404 because the two carry different confidence: this response can
859
+ // only come from a server that read our payload, while a 404 is also what a
860
+ // restarting or momentarily misrouted server returns. Callers that latch
861
+ // permanently use this to decide how much evidence one error is worth.
862
+ function isRichCapabilityErrorExplicit(err) {
863
+ if (!err) return false;
864
+ return RICH_CAPABILITY_ERR_RE.test(errorMessage(err));
865
+ }
866
+
867
+ // A rejection of the `rich_message` FIELD, as opposed to a missing METHOD.
868
+ // The distinction decides blast radius: both verbs carry this field, so a
869
+ // server that cannot read it cannot serve either — while "method
870
+ // sendRichMessage not found" says nothing about editMessageText, which a
871
+ // server may well implement and be serving right now.
872
+ 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;
873
+
874
+ function isRichMessageFieldRejection(err) {
875
+ if (!err) return false;
876
+ return RICH_MESSAGE_FIELD_ERR_RE.test(errorMessage(err));
877
+ }
878
+
770
879
  function isRichCapabilityError(err) {
771
880
  if (!err) return false;
772
- const msg = errorMessage(err);
773
- if (RICH_CAPABILITY_ERR_RE.test(msg)) return true;
881
+ if (isRichCapabilityErrorExplicit(err)) return true;
774
882
  // A 404 is sufficient because these checks only wrap rich-message calls.
775
883
  const status = err.error_code ?? err.status ?? err.statusCode;
776
884
  return status === 404;
@@ -783,11 +891,20 @@ function isRichContentError(err) {
783
891
  return RICH_CONTENT_ERR_RE.test(errorMessage(err));
784
892
  }
785
893
 
894
+ // Rich messages carry a larger Bot API character cap than plain ones. This is
895
+ // the value for surfaces that can import it; streamer.js is deliberately
896
+ // dependency-free and carries the same number as its own default, so the two
897
+ // must be changed together.
898
+ const RICH_MAX_LEN = 32768;
899
+
786
900
  module.exports = {
787
901
  needsRichRendering,
788
902
  toTelegramRichBlocks,
903
+ RICH_MAX_LEN,
789
904
  resolveRichTextEnabled,
790
905
  isRichCapabilityError,
906
+ isRichCapabilityErrorExplicit,
907
+ isRichMessageFieldRejection,
791
908
  isRichContentError,
792
909
  errorMessage,
793
910
  stripMediaMarkdown,