polygram 0.25.1 → 0.26.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.
- package/.claude-plugin/plugin.json +1 -1
- package/lib/telegram/rich-dispatch.js +88 -11
- package/lib/telegram/rich-edit.js +52 -1
- package/lib/telegram/rich-send.js +9 -3
- package/lib/telegram/rich-styling-latch.js +80 -0
- package/lib/telegram/rich.js +306 -27
- package/package.json +1 -1
- package/polygram.js +39 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://anthropic.com/claude-code/plugin.schema.json",
|
|
3
3
|
"name": "polygram",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.26.0",
|
|
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",
|
|
@@ -30,28 +30,53 @@ const {
|
|
|
30
30
|
toTelegramRichBlocks,
|
|
31
31
|
stripMediaMarkdown,
|
|
32
32
|
carriesMediaMarkdown,
|
|
33
|
+
flattenStyledBlocks,
|
|
34
|
+
blocksAreStyled,
|
|
33
35
|
RICH_MAX_LEN,
|
|
34
36
|
} = require('./rich');
|
|
35
37
|
|
|
38
|
+
// A block text field is a string OR an array of strings and typed nodes, and
|
|
39
|
+
// the nodes nest. Reduce either to the strings a reader would SEE, so a
|
|
40
|
+
// predicate about visible text cannot be dodged by adding styling to the
|
|
41
|
+
// paragraph that carries the leak.
|
|
42
|
+
function visibleStrings(value, out = []) {
|
|
43
|
+
if (typeof value === 'string') { out.push(value); return out; }
|
|
44
|
+
if (Array.isArray(value)) {
|
|
45
|
+
for (const part of value) visibleStrings(part, out);
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
if (value && typeof value === 'object') {
|
|
49
|
+
if (typeof value.text === 'string' || Array.isArray(value.text)) visibleStrings(value.text, out);
|
|
50
|
+
// `url` is not visible text, and a destination is not what this guard is
|
|
51
|
+
// about — the media check below would otherwise match a URL containing
|
|
52
|
+
// image markdown and degrade a perfectly good reply.
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const textMatches = (value, predicate) => visibleStrings(value).some(predicate);
|
|
58
|
+
|
|
36
59
|
// Every string a block tree can put on screen: block text, media captions,
|
|
37
60
|
// details summaries, and table cells. Walked rather than JSON.stringify'd so
|
|
38
|
-
// the check sees the same values the reader will
|
|
61
|
+
// the check sees the same values the reader will — and through the styled
|
|
62
|
+
// array form too, since a styled paragraph is where a leak would otherwise
|
|
63
|
+
// hide from a string-only test.
|
|
39
64
|
function someBlockText(blocks, predicate) {
|
|
40
65
|
for (const b of blocks || []) {
|
|
41
|
-
if (
|
|
42
|
-
if (
|
|
66
|
+
if (b?.text != null && textMatches(b.text, predicate)) return true;
|
|
67
|
+
if (b?.caption?.text != null && textMatches(b.caption.text, predicate)) return true;
|
|
43
68
|
if (typeof b?.summary === 'string' && predicate(b.summary)) return true;
|
|
44
69
|
if (Array.isArray(b?.cells)) {
|
|
45
70
|
for (const row of b.cells) {
|
|
46
71
|
for (const cell of row || []) {
|
|
47
|
-
if (
|
|
72
|
+
if (cell?.text != null && textMatches(cell.text, predicate)) return true;
|
|
48
73
|
}
|
|
49
74
|
}
|
|
50
75
|
}
|
|
51
76
|
if (Array.isArray(b?.blocks) && someBlockText(b.blocks, predicate)) return true;
|
|
52
77
|
if (Array.isArray(b?.items)) {
|
|
53
78
|
for (const item of b.items) {
|
|
54
|
-
if (
|
|
79
|
+
if (item?.text != null && textMatches(item.text, predicate)) return true;
|
|
55
80
|
if (Array.isArray(item?.blocks) && someBlockText(item.blocks, predicate)) return true;
|
|
56
81
|
}
|
|
57
82
|
}
|
|
@@ -80,6 +105,14 @@ const REJECT_ALL_MEDIA = (descriptors) => (descriptors || []).map(() => ({
|
|
|
80
105
|
* delivered text-only. One function returns both halves because they MUST be
|
|
81
106
|
* built from the same roots and the same stat: a resolver and a preflight
|
|
82
107
|
* that disagree reject every file with nothing in the logs to say why.
|
|
108
|
+
* @param {() => boolean} [deps.isInlineStylingEnabled] — process-wide styling
|
|
109
|
+
* verdict, re-read per reply. False → render flat, exactly as before styling
|
|
110
|
+
* existed.
|
|
111
|
+
* @param {() => void} [deps.onStylingRejected] — a styled send was refused and
|
|
112
|
+
* the flattened re-render of the SAME content landed. One variable changed
|
|
113
|
+
* between the two, so this is the only evidence about styling worth
|
|
114
|
+
* recording; the caller decides when enough of it is a verdict.
|
|
115
|
+
* @param {() => void} [deps.onStylingAccepted] — a styled send landed
|
|
83
116
|
* @param {(s: string) => string} [deps.redactError] — strips bot tokens from logged
|
|
84
117
|
* error text; network error shapes can embed the request URL
|
|
85
118
|
* @param {number} [deps.richMaxLen]
|
|
@@ -93,6 +126,9 @@ function createRichDeliveryFactory({
|
|
|
93
126
|
getRichKnownUnsupported = () => false,
|
|
94
127
|
toRichBlocks = toTelegramRichBlocks,
|
|
95
128
|
makeMediaWiring = null,
|
|
129
|
+
isInlineStylingEnabled = () => false,
|
|
130
|
+
onStylingRejected = () => {},
|
|
131
|
+
onStylingAccepted = () => {},
|
|
96
132
|
richMaxLen = RICH_MAX_LEN,
|
|
97
133
|
redactError = (s) => s,
|
|
98
134
|
logger = console,
|
|
@@ -151,13 +187,18 @@ function createRichDeliveryFactory({
|
|
|
151
187
|
// busiest path and in one synchronous pass.
|
|
152
188
|
if (media && text.length > richMaxLen) return { handled: false, text: body };
|
|
153
189
|
|
|
190
|
+
// Re-read per reply so a latch that trips mid-turn takes effect on the
|
|
191
|
+
// next one, and so a chat is never stuck styling into a server that
|
|
192
|
+
// has already refused it.
|
|
193
|
+
let styled = isInlineStylingEnabled() === true;
|
|
194
|
+
|
|
154
195
|
// `partial` is deliberately never set: final mode is the only one that
|
|
155
196
|
// both resolves media and emits the complete tree.
|
|
156
|
-
const render = (resolveMedia) => {
|
|
197
|
+
const render = (resolveMedia, inlineStyling = styled) => {
|
|
157
198
|
try {
|
|
158
199
|
const rendered = resolveMedia
|
|
159
|
-
? toRichBlocks(text, { resolveMedia })
|
|
160
|
-
: toRichBlocks(body);
|
|
200
|
+
? toRichBlocks(text, { resolveMedia, inlineStyling })
|
|
201
|
+
: toRichBlocks(body, { inlineStyling });
|
|
161
202
|
if (!rendered?.usedRich) return null;
|
|
162
203
|
// The gate that decides "this looks like media" is looser than the
|
|
163
204
|
// parser that turns it into media: a destination containing a space
|
|
@@ -173,7 +214,7 @@ function createRichDeliveryFactory({
|
|
|
173
214
|
// and carries the same latent leak. It is untouched here on purpose
|
|
174
215
|
// — a separate change, with its own soak.
|
|
175
216
|
if (resolveMedia && someBlockText(rendered.blocks, carriesMediaMarkdown)) {
|
|
176
|
-
const stripped = toRichBlocks(body);
|
|
217
|
+
const stripped = toRichBlocks(body, { inlineStyling });
|
|
177
218
|
return stripped?.usedRich ? stripped.blocks : null;
|
|
178
219
|
}
|
|
179
220
|
return rendered.blocks;
|
|
@@ -232,12 +273,48 @@ function createRichDeliveryFactory({
|
|
|
232
273
|
// everything. That yields honest "(media unavailable)" lines, and a
|
|
233
274
|
// reply whose only rich trigger WAS the media demotes to plain by
|
|
234
275
|
// itself, collapsing this ladder to two steps.
|
|
276
|
+
let retryBlocks = null;
|
|
235
277
|
if (out && !out.wentRich && out.fallback === 'media-source-changed' && media) {
|
|
236
|
-
|
|
237
|
-
if (
|
|
278
|
+
retryBlocks = render(REJECT_ALL_MEDIA);
|
|
279
|
+
if (retryBlocks) out = await attempt(retryBlocks);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// The server refused this payload and the only unusual thing in it is
|
|
283
|
+
// the styling, so strip that before giving up the structure. Losing
|
|
284
|
+
// every heading and table because one code span was unwelcome would be
|
|
285
|
+
// the worse trade.
|
|
286
|
+
//
|
|
287
|
+
// The retry is also the experiment, which is why it flattens the tree
|
|
288
|
+
// that was REFUSED rather than re-rendering the source: re-rendering
|
|
289
|
+
// would resolve media a second time and could differ in ways nothing
|
|
290
|
+
// here can see, and then a success would have changed two things. This
|
|
291
|
+
// way the two payloads differ in exactly one respect, so
|
|
292
|
+
// refused-then-accepted is evidence about styling and nothing else.
|
|
293
|
+
const lastBlocks = out?.wentRich ? null : (retryBlocks ?? blocks);
|
|
294
|
+
const contentRefused = out?.fallback === 'content-error' || out?.fallback === 'content-limit';
|
|
295
|
+
if (styled && out && !out.wentRich && contentRefused && blocksAreStyled(lastBlocks)) {
|
|
296
|
+
styled = false;
|
|
297
|
+
const retried = await attempt(flattenStyledBlocks(lastBlocks));
|
|
298
|
+
// Retry on either class — a flatter payload may well be what an
|
|
299
|
+
// oversized reply needed — but only ONE of them is evidence.
|
|
300
|
+
// Flattening removes styling AND shrinks the payload, so a refusal
|
|
301
|
+
// that named a limit is explained by the shrink; counting it would
|
|
302
|
+
// let two oversized replies disable styling for the process.
|
|
303
|
+
if (retried?.wentRich && out.fallback === 'content-error') {
|
|
304
|
+
try { onStylingRejected(); }
|
|
305
|
+
catch (err) { logger?.error?.(`[rich-dispatch] styling verdict failed: ${redactError(err.message)}`); }
|
|
306
|
+
}
|
|
307
|
+
out = retried;
|
|
238
308
|
}
|
|
239
309
|
|
|
240
310
|
if (!out?.wentRich) return { handled: false, text: body };
|
|
311
|
+
if (styled) {
|
|
312
|
+
// A styled payload the server accepted — the evidence that ends any
|
|
313
|
+
// run of suspicion, so two unrelated content errors far apart cannot
|
|
314
|
+
// add up to a verdict.
|
|
315
|
+
try { onStylingAccepted(); }
|
|
316
|
+
catch (err) { logger?.error?.(`[rich-dispatch] styling verdict failed: ${redactError(err.message)}`); }
|
|
317
|
+
}
|
|
241
318
|
|
|
242
319
|
const messageId = out.result?.message_id;
|
|
243
320
|
return {
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
'use strict';
|
|
18
18
|
|
|
19
19
|
const path = require('node:path');
|
|
20
|
-
const { countMediaBlocks } = require('./rich');
|
|
20
|
+
const { countMediaBlocks, flattenStyledBlocks, blocksAreStyled } = require('./rich');
|
|
21
21
|
|
|
22
22
|
const MEDIA_SOURCE_CHANGED = 'RICH_MEDIA_SOURCE_CHANGED';
|
|
23
23
|
const MEDIA_BLOCK_KINDS = new Set(['photo', 'video', 'animation']);
|
|
@@ -111,6 +111,10 @@ function defaultMakeInputFile(source, bytes = null) {
|
|
|
111
111
|
* @param {(text: string) => string} [deps.sanitizeFallbackText] — applied to
|
|
112
112
|
* sourceText on every plain-fallback edit (polygram wires
|
|
113
113
|
* stripMediaMarkdown; default identity preserves legacy callers)
|
|
114
|
+
* @param {() => void} [deps.onStylingRejected] — a styled payload was refused
|
|
115
|
+
* and the SAME tree, flattened, was accepted. The two differ in exactly one
|
|
116
|
+
* respect, which is what makes it evidence about styling.
|
|
117
|
+
* @param {() => void} [deps.onStylingAccepted] — a styled payload landed
|
|
114
118
|
* @returns {(args: {bot, chatId: string, threadId: (string|null), messageId: number, blocks: Array, sourceText: string, phase?: string, mediaContext?: object, hadReplyAnchor?: boolean}) => Promise<{result: *, wentRich: boolean, bubbleRemoved?: boolean}>}
|
|
115
119
|
*/
|
|
116
120
|
function createRichEditor({
|
|
@@ -120,6 +124,7 @@ function createRichEditor({
|
|
|
120
124
|
redactBotToken,
|
|
121
125
|
isRichCapabilityError,
|
|
122
126
|
isRichContentError,
|
|
127
|
+
isRichLimitError = () => false,
|
|
123
128
|
getRichKnownUnsupported = () => false,
|
|
124
129
|
setRichKnownUnsupported = () => {},
|
|
125
130
|
getApiRoot = () => null,
|
|
@@ -127,6 +132,8 @@ function createRichEditor({
|
|
|
127
132
|
makeInputFile = defaultMakeInputFile,
|
|
128
133
|
sanitizeFallbackText = (s) => s,
|
|
129
134
|
capabilityLatch = null,
|
|
135
|
+
onStylingRejected = () => {},
|
|
136
|
+
onStylingAccepted = () => {},
|
|
130
137
|
} = {}) {
|
|
131
138
|
const latch = capabilityLatch || {
|
|
132
139
|
recordCapabilityError: () => { setRichKnownUnsupported(); return true; },
|
|
@@ -171,6 +178,7 @@ function createRichEditor({
|
|
|
171
178
|
}
|
|
172
179
|
|
|
173
180
|
let fallbackKind = null;
|
|
181
|
+
let limitRefusal = false;
|
|
174
182
|
try {
|
|
175
183
|
const res = await tg(bot, 'editMessageText', {
|
|
176
184
|
chat_id: chatId,
|
|
@@ -184,6 +192,9 @@ function createRichEditor({
|
|
|
184
192
|
},
|
|
185
193
|
}, { source: 'bot-reply-stream-edit-rich', botName, richSourceText: sourceText });
|
|
186
194
|
latch.recordHealthyOutcome();
|
|
195
|
+
if (blocksAreStyled(blocks)) {
|
|
196
|
+
try { onStylingAccepted(); } catch { /* a verdict must not cost a delivered edit */ }
|
|
197
|
+
}
|
|
187
198
|
mediaContext?.learnRichResult?.(blocks, res);
|
|
188
199
|
// Record successful rich deliveries without storing message content.
|
|
189
200
|
logEvent('rich-message-sent', {
|
|
@@ -221,6 +232,9 @@ function createRichEditor({
|
|
|
221
232
|
}
|
|
222
233
|
} else if (isRichContentError(err)) {
|
|
223
234
|
fallbackKind = 'content-error';
|
|
235
|
+
// A refusal that named a limit is explained by the retry being
|
|
236
|
+
// smaller, not by it being unstyled — retry, but do not count it.
|
|
237
|
+
limitRefusal = (() => { try { return isRichLimitError(err) === true; } catch { return false; } })();
|
|
224
238
|
// The server read and rejected this payload, so the endpoint is
|
|
225
239
|
// demonstrably there — that breaks any run of ambiguous 404s.
|
|
226
240
|
latch.recordHealthyOutcome();
|
|
@@ -244,6 +258,43 @@ function createRichEditor({
|
|
|
244
258
|
}
|
|
245
259
|
}
|
|
246
260
|
|
|
261
|
+
// A refused styled payload gets one more rich attempt without the
|
|
262
|
+
// styling, before the bubble degrades to plain text. The streamer is the
|
|
263
|
+
// path where that matters most: its bubbles are edited repeatedly, so a
|
|
264
|
+
// server that dislikes typed nodes would otherwise flatten every one of
|
|
265
|
+
// them to plain for the process lifetime — losing headings and tables
|
|
266
|
+
// that have nothing to do with the refusal.
|
|
267
|
+
//
|
|
268
|
+
// Flattens the REFUSED tree rather than asking for a re-render: no media
|
|
269
|
+
// is resolved twice, and the two payloads differ in exactly one respect,
|
|
270
|
+
// so an acceptance here says something about styling and nothing else.
|
|
271
|
+
if (fallbackKind === 'content-error' && blocksAreStyled(blocks)) {
|
|
272
|
+
try {
|
|
273
|
+
const res = await tg(bot, 'editMessageText', {
|
|
274
|
+
chat_id: chatId,
|
|
275
|
+
message_id: messageId,
|
|
276
|
+
rich_message: {
|
|
277
|
+
blocks: materializeMediaBlocks(
|
|
278
|
+
flattenStyledBlocks(blocks),
|
|
279
|
+
makeInputFile,
|
|
280
|
+
mediaContext?.preflightMedia,
|
|
281
|
+
),
|
|
282
|
+
},
|
|
283
|
+
}, { source: 'bot-reply-stream-edit-rich-unstyled', botName, richSourceText: sourceText });
|
|
284
|
+
if (!limitRefusal) {
|
|
285
|
+
try { onStylingRejected(); } catch { /* the edit landed either way */ }
|
|
286
|
+
}
|
|
287
|
+
logEvent('rich-styling-fallback', {
|
|
288
|
+
chat_id: chatId, thread_id: threadId, bot: botName,
|
|
289
|
+
transport: 'edit',
|
|
290
|
+
});
|
|
291
|
+
return { result: res, wentRich: true };
|
|
292
|
+
} catch {
|
|
293
|
+
// Both shapes refused, so the blocks were the problem and this says
|
|
294
|
+
// nothing about styling. Fall through to the plain edit below.
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
247
298
|
const fallbackText = sanitizeFallbackText(sourceText);
|
|
248
299
|
const canRescue = fallbackKind === 'content-error'
|
|
249
300
|
&& (phase === 'final' || phase === 'seal')
|
|
@@ -64,8 +64,11 @@ const { countMediaBlocks } = require('./rich');
|
|
|
64
64
|
* => Promise<{wentRich: boolean, result?: *, fallback?: string}>}
|
|
65
65
|
* `fallback` names the failure class. Only 'media-source-changed' is acted
|
|
66
66
|
* on by the caller (it is the one a different render could fix); the rest
|
|
67
|
-
* —'capability', 'content-error', 'no-message-id',
|
|
68
|
-
* otherwise identical plain-fallback outcomes for the
|
|
67
|
+
* —'capability', 'content-error', 'content-limit', 'no-message-id',
|
|
68
|
+
* 'error' — distinguish otherwise identical plain-fallback outcomes for the
|
|
69
|
+
* soak. 'content-limit' is a content error that named a LIMIT: worth its own
|
|
70
|
+
* name because a smaller retry succeeding says nothing about WHY the first
|
|
71
|
+
* payload was refused.
|
|
69
72
|
*/
|
|
70
73
|
function createRichSender({
|
|
71
74
|
tg,
|
|
@@ -75,6 +78,7 @@ function createRichSender({
|
|
|
75
78
|
isRichCapabilityError,
|
|
76
79
|
isRichCapabilityErrorExplicit,
|
|
77
80
|
isRichContentError,
|
|
81
|
+
isRichLimitError = () => false,
|
|
78
82
|
getRichKnownUnsupported = () => false,
|
|
79
83
|
setRichKnownUnsupported = () => {},
|
|
80
84
|
getApiRoot = () => null,
|
|
@@ -263,13 +267,15 @@ function createRichSender({
|
|
|
263
267
|
// re-uploads the bytes.
|
|
264
268
|
try { mediaContext?.evictCachedBlocks?.(blocks); }
|
|
265
269
|
catch (e) { logger?.error?.(`[telegram] rich-send cache eviction failed: ${e.message}`); }
|
|
270
|
+
const limited = safeTest(isRichLimitError, err);
|
|
266
271
|
logEvent('rich-content-fallback', {
|
|
267
272
|
chat_id: chatId, thread_id: threadId, bot: botName,
|
|
268
273
|
transport: 'send',
|
|
269
274
|
media_count: safeMediaCount(blocks),
|
|
275
|
+
limit: limited,
|
|
270
276
|
error: redactBotToken(errText(err))?.slice(0, 200),
|
|
271
277
|
});
|
|
272
|
-
return 'content-error';
|
|
278
|
+
return limited ? 'content-limit' : 'content-error';
|
|
273
279
|
}
|
|
274
280
|
|
|
275
281
|
// Soak note: api.js already logs telegram-api-error for the same failure,
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared decision for when to stop emitting inline styling.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately NOT the capability latch. That one answers "can this server do
|
|
5
|
+
* rich at all", and tripping it costs every heading, table and task list on
|
|
6
|
+
* every path. This one answers a much smaller question — "does this server
|
|
7
|
+
* accept typed RichText nodes inside block text" — and tripping it costs
|
|
8
|
+
* bold, italic, code spans and links. A server that predates typed nodes
|
|
9
|
+
* still renders rich perfectly well, so conflating the two would trade the
|
|
10
|
+
* whole feature for a sub-feature.
|
|
11
|
+
*
|
|
12
|
+
* The failure mode this guards is therefore "no styling", never "no rich".
|
|
13
|
+
*
|
|
14
|
+
* Evidence, and why it is weaker than the capability latch's:
|
|
15
|
+
*
|
|
16
|
+
* A content-class rejection does not say WHY the payload was refused. The
|
|
17
|
+
* styled render and the flattened one differ in exactly one respect, so a
|
|
18
|
+
* styled send that is rejected and whose flattened retry SUCCEEDS is a
|
|
19
|
+
* controlled experiment with one variable — that is the only evidence
|
|
20
|
+
* counted here. A rejection whose retry also fails says nothing about
|
|
21
|
+
* styling (the blocks themselves were bad) and buys no strike.
|
|
22
|
+
*
|
|
23
|
+
* One such result could still be a coincidence: two payloads, two moments,
|
|
24
|
+
* possibly a transient in between. Two in a row are the verdict. Same
|
|
25
|
+
* "consecutive rich attempts" meaning as the capability latch — a healthy
|
|
26
|
+
* styled send clears the count, and attempts that never happen cannot.
|
|
27
|
+
*
|
|
28
|
+
* Untripping is not offered. A process that has decided to stop styling
|
|
29
|
+
* degrades to exactly today's output, which is a state the fleet ran in for
|
|
30
|
+
* two releases; re-arming on a timer would trade that certainty for a retry
|
|
31
|
+
* of an experiment the operator can rerun by restarting.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
'use strict';
|
|
35
|
+
|
|
36
|
+
const DEFAULT_STRIKES = 2;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} deps
|
|
40
|
+
* @param {() => void} deps.setUnsupported — called once, when the verdict lands
|
|
41
|
+
* @param {number} [deps.strikes] — consecutive confirmations required
|
|
42
|
+
* @returns {{recordStylingRejection: () => boolean, recordHealthyOutcome: () => void,
|
|
43
|
+
* get tripped(): boolean}}
|
|
44
|
+
*/
|
|
45
|
+
function createRichStylingLatch({ setUnsupported = () => {}, strikes = DEFAULT_STRIKES } = {}) {
|
|
46
|
+
const required = Number.isInteger(strikes) && strikes > 0 ? strikes : DEFAULT_STRIKES;
|
|
47
|
+
let consecutive = 0;
|
|
48
|
+
let tripped = false;
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
/**
|
|
52
|
+
* Record one confirmed styling rejection: a styled send refused, whose
|
|
53
|
+
* flattened re-render then landed. Callers must not report anything
|
|
54
|
+
* weaker — an unconfirmed rejection is not evidence about styling.
|
|
55
|
+
*
|
|
56
|
+
* @returns {boolean} true when THIS call tripped the latch (log once)
|
|
57
|
+
*/
|
|
58
|
+
recordStylingRejection() {
|
|
59
|
+
if (tripped) return false;
|
|
60
|
+
consecutive += 1;
|
|
61
|
+
if (consecutive < required) return false;
|
|
62
|
+
tripped = true;
|
|
63
|
+
try { setUnsupported(); } catch { /* the verdict stands either way */ }
|
|
64
|
+
return true;
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A styled payload the server accepted. Proof that typed nodes work here,
|
|
69
|
+
* so any run of suspicion ends — otherwise two unrelated content errors,
|
|
70
|
+
* months apart, would eventually disable a working feature.
|
|
71
|
+
*/
|
|
72
|
+
recordHealthyOutcome() {
|
|
73
|
+
if (!tripped) consecutive = 0;
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
get tripped() { return tripped; },
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { createRichStylingLatch, DEFAULT_STYLING_STRIKES: DEFAULT_STRIKES };
|
package/lib/telegram/rich.js
CHANGED
|
@@ -169,6 +169,239 @@ function plainTextOf(tokens) {
|
|
|
169
169
|
return out;
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
// ─── Inline styling ──────────────────────────────────────────────────
|
|
173
|
+
//
|
|
174
|
+
// The typed-node counterpart to plainTextOf. Bold, italic, code spans and
|
|
175
|
+
// links become RichText nodes instead of losing their formatting; a run with
|
|
176
|
+
// nothing styled in it comes back as the SAME plain string plainTextOf would
|
|
177
|
+
// have produced.
|
|
178
|
+
//
|
|
179
|
+
// That last rule is load-bearing, not tidiness. The streamer dedups payloads
|
|
180
|
+
// with JSON.stringify, so wrapping unstyled text in an array would re-send
|
|
181
|
+
// every bubble that had not changed; the length gate and the plain fallback
|
|
182
|
+
// are both derived from the flat text; and every existing block-text
|
|
183
|
+
// assertion in the suite keeps meaning what it meant.
|
|
184
|
+
//
|
|
185
|
+
// Structure, not markup: a node's `text` is a value nothing downstream
|
|
186
|
+
// re-parses, so a literal `<b>`, `&` or backtick inside agent-relayed content
|
|
187
|
+
// stays literal. That is the whole reason to prefer typed nodes over the
|
|
188
|
+
// `html`/`markdown` string fields, which api.js refuses at the choke point.
|
|
189
|
+
|
|
190
|
+
// marked token type → node discriminator. Everything absent from this map
|
|
191
|
+
// keeps flattening to its text, which is always safe. Each entry is here
|
|
192
|
+
// because a live probe echoed it back intact — `strikethrough` was accepted
|
|
193
|
+
// under that spelling and refused under `strike`, so the name is the
|
|
194
|
+
// server's answer rather than a guess.
|
|
195
|
+
const INLINE_STYLE_NODES = new Map([
|
|
196
|
+
['strong', 'bold'],
|
|
197
|
+
['em', 'italic'],
|
|
198
|
+
['del', 'strikethrough'],
|
|
199
|
+
]);
|
|
200
|
+
|
|
201
|
+
// Which fields carry styling, threaded rather than read from module state so
|
|
202
|
+
// nothing here depends on render order and a nested walk could narrow it if a
|
|
203
|
+
// field ever needed that.
|
|
204
|
+
//
|
|
205
|
+
// Paragraphs, headings, list items and table cells all carry it. The last two
|
|
206
|
+
// were held back at first: one live run reported them PRESERVED and an
|
|
207
|
+
// identical repeat REJECTED, which is rate pressure's signature rather than a
|
|
208
|
+
// field's answer. A paced run with the control passing reported both
|
|
209
|
+
// PRESERVED, so they render styled on evidence rather than on the optimistic
|
|
210
|
+
// reading of a contradiction.
|
|
211
|
+
const FLAT = Object.freeze({ styled: false });
|
|
212
|
+
const styledCtx = (styled) => (styled ? Object.freeze({ styled: true }) : FLAT);
|
|
213
|
+
|
|
214
|
+
// The one call every text-emitting site goes through.
|
|
215
|
+
function textOf(tokens, ctx) {
|
|
216
|
+
return ctx?.styled ? richTextOf(tokens) : plainTextOf(tokens);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Bounds, both of them the same argument as the media fan-out cap: agent
|
|
220
|
+
// output is influenced by content the agent read, so anything unbounded in it
|
|
221
|
+
// is a lever. Telegram caps blocks and nesting; it says nothing about nodes
|
|
222
|
+
// per block, and a reply can reach five figures without trying.
|
|
223
|
+
//
|
|
224
|
+
// Past either bound the run flattens — the text is identical, only the
|
|
225
|
+
// formatting is lost, which is exactly the degrade the whole feature is
|
|
226
|
+
// designed around.
|
|
227
|
+
const MAX_STYLE_NODES_PER_BLOCK = 200;
|
|
228
|
+
// The API's documented nesting limit is 16 and marked reaches 38 from 25
|
|
229
|
+
// emphasis markers, so this sits well below both. Nothing legible needs it:
|
|
230
|
+
// bold inside a link inside a list is depth 3.
|
|
231
|
+
const MAX_STYLE_DEPTH = 8;
|
|
232
|
+
|
|
233
|
+
// Only http(s) destinations become link nodes. A typed url node hands
|
|
234
|
+
// Telegram a destination to make clickable, which is a trust boundary the
|
|
235
|
+
// FLAT rendering never crossed — it discarded the destination entirely. So
|
|
236
|
+
// `javascript:`, `data:`, `file:` and anything else keeps the link's text and
|
|
237
|
+
// drops the node; the reader loses a hyperlink they could not safely have
|
|
238
|
+
// been given.
|
|
239
|
+
const SAFE_URL_RE = /^https?:\/\//i;
|
|
240
|
+
|
|
241
|
+
function isEmptyRichText(value) {
|
|
242
|
+
if (typeof value === 'string') return value.length === 0;
|
|
243
|
+
return !Array.isArray(value) || value.length === 0;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function richTextOf(tokens, depth = 0) {
|
|
247
|
+
const parts = [];
|
|
248
|
+
let nodes = 0;
|
|
249
|
+
// Adjacent plain runs coalesce, so a sentence never fragments into a node
|
|
250
|
+
// per word — fewer parts to render, and a far more readable payload.
|
|
251
|
+
const pushText = (text) => {
|
|
252
|
+
if (!text) return;
|
|
253
|
+
const last = parts.length ? parts[parts.length - 1] : null;
|
|
254
|
+
if (typeof last === 'string') parts[parts.length - 1] = last + text;
|
|
255
|
+
else parts.push(text);
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
// Splice a nested result into this run: strings coalesce with their
|
|
259
|
+
// neighbours, nodes keep their identity.
|
|
260
|
+
const absorb = (value) => {
|
|
261
|
+
if (typeof value === 'string') { pushText(value); return; }
|
|
262
|
+
for (const part of value) {
|
|
263
|
+
if (typeof part === 'string') pushText(part);
|
|
264
|
+
else parts.push(part);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
for (const t of tokens || []) {
|
|
269
|
+
// marked wraps a list item's inline run in a block-level 'text' token
|
|
270
|
+
// whose .text is the RAW source (markers included) and whose .tokens
|
|
271
|
+
// carry the parsed children. Recurse, or every marker ships to the chat
|
|
272
|
+
// as a literal character — the same trap plainTextOf names above, and
|
|
273
|
+
// the reason a list item rendered `**urgent**` verbatim.
|
|
274
|
+
if (t.type === 'text' && Array.isArray(t.tokens)) { absorb(richTextOf(t.tokens, depth)); continue; }
|
|
275
|
+
if (t.type === 'text' || t.type === 'escape') { pushText(t.text ?? ''); continue; }
|
|
276
|
+
if (t.type === 'br') { pushText('\n'); continue; }
|
|
277
|
+
|
|
278
|
+
// Past either bound, everything left in this run flattens. Checked here
|
|
279
|
+
// rather than after the walk so a pathological reply is never built at all.
|
|
280
|
+
const exhausted = nodes >= MAX_STYLE_NODES_PER_BLOCK || depth >= MAX_STYLE_DEPTH;
|
|
281
|
+
|
|
282
|
+
if (t.type === 'codespan') {
|
|
283
|
+
const text = t.text ?? '';
|
|
284
|
+
if (!text) continue;
|
|
285
|
+
if (exhausted) { pushText(text); continue; }
|
|
286
|
+
nodes += 1;
|
|
287
|
+
parts.push({ type: 'code', text });
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const styled = INLINE_STYLE_NODES.get(t.type);
|
|
292
|
+
if (styled) {
|
|
293
|
+
if (exhausted) { pushText(plainTextOf([t])); continue; }
|
|
294
|
+
const inner = richTextOf(t.tokens, depth + 1);
|
|
295
|
+
if (isEmptyRichText(inner)) continue;
|
|
296
|
+
nodes += 1;
|
|
297
|
+
parts.push({ type: styled, text: inner });
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (t.type === 'link') {
|
|
302
|
+
// The flat label decides the guards below and is the fallback for every
|
|
303
|
+
// branch that declines to emit a node — a rejected link still shows its
|
|
304
|
+
// text.
|
|
305
|
+
const flatLabel = plainTextOf(t.tokens) || t.text || '';
|
|
306
|
+
if (exhausted
|
|
307
|
+
|| typeof t.href !== 'string'
|
|
308
|
+
|| !SAFE_URL_RE.test(t.href)
|
|
309
|
+
|| !flatLabel) {
|
|
310
|
+
// A link with no destination, a non-http scheme, or no text is not a
|
|
311
|
+
// link node. Keep what the reader can see, drop what they cannot
|
|
312
|
+
// safely be handed.
|
|
313
|
+
pushText(flatLabel || plainTextOf([t]));
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
// A styled label — `[**bold** link](…)` — is ordinary markdown, and a
|
|
317
|
+
// probe confirmed nested nodes survive inside a url node. Counted at
|
|
318
|
+
// depth+1 so a label cannot dodge the nesting ceiling.
|
|
319
|
+
const label = richTextOf(t.tokens, depth + 1);
|
|
320
|
+
nodes += 1;
|
|
321
|
+
parts.push({
|
|
322
|
+
type: 'url',
|
|
323
|
+
text: isEmptyRichText(label) ? flatLabel : label,
|
|
324
|
+
url: t.href,
|
|
325
|
+
});
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Everything else — images, raw html, anything marked grows later —
|
|
330
|
+
// keeps the flattened form. Images especially: they are block-level media
|
|
331
|
+
// on this pipeline and must never become inline nodes.
|
|
332
|
+
pushText(plainTextOf([t]));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (parts.length === 0) return '';
|
|
336
|
+
if (parts.every((p) => typeof p === 'string')) return parts.join('');
|
|
337
|
+
return parts;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// The visible text of a rich-text value, whatever shape it is in: the string
|
|
341
|
+
// itself, or every string a node tree would put on screen.
|
|
342
|
+
function flattenRichText(value) {
|
|
343
|
+
if (typeof value === 'string') return value;
|
|
344
|
+
if (Array.isArray(value)) return value.map(flattenRichText).join('');
|
|
345
|
+
if (value && typeof value === 'object') return flattenRichText(value.text ?? '');
|
|
346
|
+
return '';
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Strip styling from an ALREADY-RENDERED block tree, leaving everything else
|
|
351
|
+
* — structure, media, captions, alignment — bit for bit as it was.
|
|
352
|
+
*
|
|
353
|
+
* Used as the retry rung after a refused styled payload. Flattening in place
|
|
354
|
+
* rather than re-rendering the source matters for two reasons: nothing is
|
|
355
|
+
* resolved a second time (media stays exactly the values that were checked,
|
|
356
|
+
* with no second pass over the filesystem), and the retry differs from the
|
|
357
|
+
* refused payload in EXACTLY ONE respect. That is what makes a
|
|
358
|
+
* refused-then-accepted pair evidence about styling rather than about
|
|
359
|
+
* whatever else a re-render might have changed.
|
|
360
|
+
*/
|
|
361
|
+
function flattenStyledBlocks(blocks) {
|
|
362
|
+
return (blocks || []).map((b) => {
|
|
363
|
+
if (!b || typeof b !== 'object') return b;
|
|
364
|
+
const out = { ...b };
|
|
365
|
+
if (Array.isArray(b.text)) out.text = flattenRichText(b.text);
|
|
366
|
+
if (b.caption && Array.isArray(b.caption.text)) {
|
|
367
|
+
out.caption = { ...b.caption, text: flattenRichText(b.caption.text) };
|
|
368
|
+
}
|
|
369
|
+
if (Array.isArray(b.cells)) {
|
|
370
|
+
out.cells = b.cells.map((row) => (row || []).map((cell) => (
|
|
371
|
+
cell && Array.isArray(cell.text) ? { ...cell, text: flattenRichText(cell.text) } : cell
|
|
372
|
+
)));
|
|
373
|
+
}
|
|
374
|
+
if (Array.isArray(b.blocks)) out.blocks = flattenStyledBlocks(b.blocks);
|
|
375
|
+
if (Array.isArray(b.items)) {
|
|
376
|
+
out.items = b.items.map((item) => {
|
|
377
|
+
if (!item || typeof item !== 'object') return item;
|
|
378
|
+
const next = { ...item };
|
|
379
|
+
if (Array.isArray(item.text)) next.text = flattenRichText(item.text);
|
|
380
|
+
if (Array.isArray(item.blocks)) next.blocks = flattenStyledBlocks(item.blocks);
|
|
381
|
+
return next;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
return out;
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Does this tree carry any typed node at all? */
|
|
389
|
+
function blocksAreStyled(blocks) {
|
|
390
|
+
for (const b of blocks || []) {
|
|
391
|
+
if (!b || typeof b !== 'object') continue;
|
|
392
|
+
if (Array.isArray(b.text) || Array.isArray(b.caption?.text)) return true;
|
|
393
|
+
if (Array.isArray(b.cells) && b.cells.some((row) => (row || []).some((c) => Array.isArray(c?.text)))) return true;
|
|
394
|
+
if (Array.isArray(b.blocks) && blocksAreStyled(b.blocks)) return true;
|
|
395
|
+
if (Array.isArray(b.items)) {
|
|
396
|
+
for (const item of b.items) {
|
|
397
|
+
if (Array.isArray(item?.text)) return true;
|
|
398
|
+
if (Array.isArray(item?.blocks) && blocksAreStyled(item.blocks)) return true;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
|
|
172
405
|
const DETAILS_BLOCK_RE = /<details[^>]*>(?:\s*<summary[^>]*>([\s\S]*?)<\/summary>)?([\s\S]*?)<\/details>/i;
|
|
173
406
|
const DETAILS_OPEN_RE = /<details[^>]*>/i;
|
|
174
407
|
const DETAILS_CLOSE_RE = /<\/details>/i;
|
|
@@ -323,15 +556,15 @@ function inlineHasMedia(tokens) {
|
|
|
323
556
|
// list-item content that way); images inside links/bold stay flattened
|
|
324
557
|
// to their alt text by plainTextOf — splitting mid-link would produce
|
|
325
558
|
// stranger output than the flattening does.
|
|
326
|
-
function blocksFromInlineTokens(inlineTokens) {
|
|
559
|
+
function blocksFromInlineTokens(inlineTokens, ctx = FLAT) {
|
|
327
560
|
const out = [];
|
|
328
561
|
let textRun = [];
|
|
329
562
|
let group = null;
|
|
330
563
|
const flushText = () => {
|
|
331
564
|
if (!textRun.length) return;
|
|
332
|
-
const
|
|
565
|
+
const run = textRun;
|
|
333
566
|
textRun = [];
|
|
334
|
-
if (
|
|
567
|
+
if (plainTextOf(run).trim()) out.push({ type: 'paragraph', text: textOf(run, ctx) });
|
|
335
568
|
};
|
|
336
569
|
const walk = (tokens) => {
|
|
337
570
|
for (const t of tokens || []) {
|
|
@@ -370,30 +603,32 @@ function blocksFromInlineTokens(inlineTokens) {
|
|
|
370
603
|
// objects. Returns an array (a single markdown token can occasionally
|
|
371
604
|
// need zero blocks — e.g. a bare 'space' token — or, in principle,
|
|
372
605
|
// more than one).
|
|
373
|
-
function blockFromToken(token) {
|
|
606
|
+
function blockFromToken(token, ctx = FLAT) {
|
|
374
607
|
switch (token.type) {
|
|
375
608
|
case 'paragraph': {
|
|
376
609
|
if (inlineHasMedia(token.tokens)) {
|
|
377
|
-
return blocksFromInlineTokens(token.tokens);
|
|
610
|
+
return blocksFromInlineTokens(token.tokens, ctx);
|
|
378
611
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
612
|
+
// Emptiness is decided on the FLAT projection: a styled run is never
|
|
613
|
+
// whitespace-only when its plain form is not, and asking the question
|
|
614
|
+
// once keeps the two branches from disagreeing.
|
|
615
|
+
if (!plainTextOf(token.tokens).trim()) return [];
|
|
616
|
+
return [{ type: 'paragraph', text: textOf(token.tokens, ctx) }];
|
|
382
617
|
}
|
|
383
618
|
case 'heading': {
|
|
384
619
|
const size = Math.min(6, Math.max(1, token.depth || 1));
|
|
385
|
-
return [{ type: 'heading', text:
|
|
620
|
+
return [{ type: 'heading', text: textOf(token.tokens, ctx), size }];
|
|
386
621
|
}
|
|
387
622
|
case 'code': {
|
|
388
623
|
return [{ type: 'pre', text: token.text || '' }];
|
|
389
624
|
}
|
|
390
625
|
case 'blockquote': {
|
|
391
|
-
const blocks = blocksFromTokens(token.tokens);
|
|
626
|
+
const blocks = blocksFromTokens(token.tokens, ctx);
|
|
392
627
|
if (!blocks.length) return [];
|
|
393
628
|
return [{ type: 'blockquote', blocks }];
|
|
394
629
|
}
|
|
395
630
|
case 'list': {
|
|
396
|
-
const items = (token.items || []).map((item, i) => listItemFromToken(item, token, i)).filter(Boolean);
|
|
631
|
+
const items = (token.items || []).map((item, i) => listItemFromToken(item, token, i, ctx)).filter(Boolean);
|
|
397
632
|
if (!items.length) return [];
|
|
398
633
|
return [{ type: 'list', items }];
|
|
399
634
|
}
|
|
@@ -402,15 +637,18 @@ function blockFromToken(token) {
|
|
|
402
637
|
const align = token.align?.[column];
|
|
403
638
|
return align === 'center' || align === 'right' ? align : 'left';
|
|
404
639
|
};
|
|
640
|
+
// Header and body cells are the same field with the same shape, so
|
|
641
|
+
// they carry styling alike — a bold header with plain bold body cells
|
|
642
|
+
// would be a distinction the markdown never made.
|
|
405
643
|
const headerRow = (token.header || []).map((cell, column) => ({
|
|
406
|
-
text:
|
|
644
|
+
text: textOf(cell.tokens, ctx),
|
|
407
645
|
is_header: true,
|
|
408
646
|
align: cellAlignment(column),
|
|
409
647
|
valign: 'top',
|
|
410
648
|
}));
|
|
411
649
|
const rows = (token.rows || []).map((row) =>
|
|
412
650
|
row.map((cell, column) => ({
|
|
413
|
-
text:
|
|
651
|
+
text: textOf(cell.tokens, ctx),
|
|
414
652
|
align: cellAlignment(column),
|
|
415
653
|
valign: 'top',
|
|
416
654
|
})));
|
|
@@ -439,7 +677,7 @@ function blockFromToken(token) {
|
|
|
439
677
|
if (prefix) out.push({ type: 'paragraph', text: prefix });
|
|
440
678
|
const summary = (m[1] || '').replace(HTML_TAG_STRIP_RE, '').trim();
|
|
441
679
|
const innerMarkdown = (m[2] || '').trim();
|
|
442
|
-
const blocks = innerMarkdown ? blocksFromTokens(_lexer.lexer(innerMarkdown)) : [];
|
|
680
|
+
const blocks = innerMarkdown ? blocksFromTokens(_lexer.lexer(innerMarkdown), ctx) : [];
|
|
443
681
|
out.push({
|
|
444
682
|
type: 'details',
|
|
445
683
|
summary: summary || DEFAULT_DETAILS_SUMMARY,
|
|
@@ -447,7 +685,7 @@ function blockFromToken(token) {
|
|
|
447
685
|
is_open: false,
|
|
448
686
|
});
|
|
449
687
|
const suffix = src.slice(m.index + m[0].length);
|
|
450
|
-
if (suffix.trim()) out.push(...blocksFromTokens(_lexer.lexer(suffix)));
|
|
688
|
+
if (suffix.trim()) out.push(...blocksFromTokens(_lexer.lexer(suffix), ctx));
|
|
451
689
|
return out;
|
|
452
690
|
}
|
|
453
691
|
// A whole <tg-collage>/<tg-slideshow> span in one token (GFM
|
|
@@ -480,17 +718,36 @@ function blockFromToken(token) {
|
|
|
480
718
|
// checkbox the has_checkbox flag renders. Strip it from the leader.
|
|
481
719
|
const TASK_MARKER_RE = /^\s*\[[ xX]\]\s*/;
|
|
482
720
|
|
|
483
|
-
|
|
721
|
+
// Strips it from either text representation. A styled run keeps the marker in
|
|
722
|
+
// its leading string, so the array form has to be handled explicitly — and a
|
|
723
|
+
// leading string that was ONLY the marker leaves an empty run behind.
|
|
724
|
+
function stripTaskMarker(value, isTask) {
|
|
725
|
+
if (!isTask) return value;
|
|
726
|
+
if (typeof value === 'string') return value.replace(TASK_MARKER_RE, '');
|
|
727
|
+
if (!Array.isArray(value) || typeof value[0] !== 'string') return value;
|
|
728
|
+
const head = value[0].replace(TASK_MARKER_RE, '');
|
|
729
|
+
return head ? [head, ...value.slice(1)] : value.slice(1);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function listItemFromToken(item, listToken, index, ctx = FLAT) {
|
|
484
733
|
const { inline, blockTokens } = splitListItemTokens(item.tokens);
|
|
485
|
-
|
|
734
|
+
// A list item's text IS a nested paragraph, so styling reaches it through
|
|
735
|
+
// the paragraph branch — nothing special to do here now that the field is
|
|
736
|
+
// confirmed.
|
|
737
|
+
const nestedBlocks = blocksFromTokens(blockTokens, ctx);
|
|
486
738
|
const blocks = [];
|
|
487
739
|
if (inlineHasMedia(inline)) {
|
|
488
|
-
blocks.push(...blocksFromInlineTokens(inline));
|
|
740
|
+
blocks.push(...blocksFromInlineTokens(inline, ctx));
|
|
489
741
|
if (!blocks.length && !nestedBlocks.length) blocks.push({ type: 'paragraph', text: '' });
|
|
490
742
|
} else {
|
|
491
|
-
|
|
492
|
-
if (
|
|
493
|
-
|
|
743
|
+
// Emptiness is decided on the flat projection, as everywhere else.
|
|
744
|
+
if (plainTextOf(inline).trim() || !nestedBlocks.length) {
|
|
745
|
+
// The marker strip applies to the styled form too: it arrives in the
|
|
746
|
+
// FIRST string of the run, which is a place the flat path never had to
|
|
747
|
+
// look, and a styled task item would otherwise show it beside the real
|
|
748
|
+
// checkbox.
|
|
749
|
+
blocks.push({ type: 'paragraph', text: stripTaskMarker(textOf(inline, ctx), item.task === true) });
|
|
750
|
+
}
|
|
494
751
|
}
|
|
495
752
|
blocks.push(...nestedBlocks);
|
|
496
753
|
|
|
@@ -536,7 +793,7 @@ function splitListItemTokens(tokens) {
|
|
|
536
793
|
// details blocks with real paragraph content inside render correctly
|
|
537
794
|
// rather than getting silently split into a stray open-tag paragraph +
|
|
538
795
|
// unrelated nested blocks + a stray close-tag paragraph.
|
|
539
|
-
function blocksFromTokens(tokens) {
|
|
796
|
+
function blocksFromTokens(tokens, ctx = FLAT) {
|
|
540
797
|
const out = [];
|
|
541
798
|
const list = tokens || [];
|
|
542
799
|
let i = 0;
|
|
@@ -555,7 +812,7 @@ function blocksFromTokens(tokens) {
|
|
|
555
812
|
if (tj.type === 'html' && DETAILS_CLOSE_RE.test(rawj)) { closeRaw = rawj; break; }
|
|
556
813
|
inner.push(tj);
|
|
557
814
|
}
|
|
558
|
-
const nestedBlocks = blocksFromTokens(inner);
|
|
815
|
+
const nestedBlocks = blocksFromTokens(inner, ctx);
|
|
559
816
|
// The close tag's html token can carry content on adjacent lines
|
|
560
817
|
// (an HTML block runs until a blank line): text before </details>
|
|
561
818
|
// belongs inside the collapsible body, text after it is ordinary
|
|
@@ -573,7 +830,7 @@ function blocksFromTokens(tokens) {
|
|
|
573
830
|
blocks: nestedBlocks.length ? nestedBlocks : [{ type: 'paragraph', text: '' }],
|
|
574
831
|
is_open: false,
|
|
575
832
|
});
|
|
576
|
-
if (after.trim()) out.push(...blocksFromTokens(_lexer.lexer(after)));
|
|
833
|
+
if (after.trim()) out.push(...blocksFromTokens(_lexer.lexer(after), ctx));
|
|
577
834
|
i = j + 1; // skip past the close token (or to the end if never closed)
|
|
578
835
|
continue;
|
|
579
836
|
}
|
|
@@ -598,7 +855,7 @@ function blocksFromTokens(tokens) {
|
|
|
598
855
|
if (tj.type === 'html' && MEDIA_WRAP_CLOSE_RE.test(rawj)) break;
|
|
599
856
|
inner.push(tj);
|
|
600
857
|
}
|
|
601
|
-
const innerBlocks = blocksFromTokens(inner);
|
|
858
|
+
const innerBlocks = blocksFromTokens(inner, ctx);
|
|
602
859
|
const rest = [];
|
|
603
860
|
for (const b of innerBlocks) {
|
|
604
861
|
if (b.type === '_media') items.push({ type: '_media', src: b.src, caption: b.caption });
|
|
@@ -610,7 +867,7 @@ function blocksFromTokens(tokens) {
|
|
|
610
867
|
i = j + 1;
|
|
611
868
|
continue;
|
|
612
869
|
}
|
|
613
|
-
out.push(...blockFromToken(t));
|
|
870
|
+
out.push(...blockFromToken(t, ctx));
|
|
614
871
|
i++;
|
|
615
872
|
}
|
|
616
873
|
return out;
|
|
@@ -811,13 +1068,18 @@ function carriesMediaMarkdown(text) {
|
|
|
811
1068
|
* When media was the ONLY gate trigger and none of it resolved, the
|
|
812
1069
|
* whole render demotes to `usedRich: false` so prose doesn't ship as
|
|
813
1070
|
* oversized rich paragraphs.
|
|
1071
|
+
*
|
|
1072
|
+
* opts.inlineStyling (boolean, default false) — emit typed RichText nodes for
|
|
1073
|
+
* bold/italic/code/links instead of flattening them. Off by default so every
|
|
1074
|
+
* caller that has not opted in is byte-identical, and so the fallback after a
|
|
1075
|
+
* styling rejection is this same call with the flag cleared.
|
|
814
1076
|
*/
|
|
815
1077
|
function toTelegramRichBlocks(markdown, opts = {}) {
|
|
816
1078
|
const usedRich = needsRichRendering(markdown);
|
|
817
1079
|
if (!usedRich) return { blocks: [], usedRich: false };
|
|
818
1080
|
|
|
819
1081
|
const tokens = _lexer.lexer(markdown);
|
|
820
|
-
let blocks = blocksFromTokens(tokens);
|
|
1082
|
+
let blocks = blocksFromTokens(tokens, styledCtx(opts.inlineStyling === true));
|
|
821
1083
|
|
|
822
1084
|
const descriptors = collectMediaDescriptors(blocks);
|
|
823
1085
|
let results = null;
|
|
@@ -912,6 +1174,19 @@ function isRichCapabilityError(err) {
|
|
|
912
1174
|
|
|
913
1175
|
const RICH_CONTENT_ERR_RE = /RICH_MESSAGE_[A-Z_]+|can'?t parse (?:input)?rich\s*block|rich message.*(?:too (?:many|long)|invalid)|wrong remote file identifier specified/i;
|
|
914
1176
|
|
|
1177
|
+
// A content error that names a LIMIT rather than a shape. Worth separating
|
|
1178
|
+
// because the styling retry flattens the payload, which makes it smaller and
|
|
1179
|
+
// shallower as well as unstyled — so an oversized reply that succeeds on the
|
|
1180
|
+
// retry would otherwise read as "this server refuses typed nodes", and two of
|
|
1181
|
+
// them would disable styling for the process. Retry either way; count only
|
|
1182
|
+
// the one where styling is the plausible cause.
|
|
1183
|
+
const RICH_LIMIT_ERR_RE = /too (?:many|long|large|big)|_TOO_(?:MANY|LONG|LARGE)|exceed|limit/i;
|
|
1184
|
+
|
|
1185
|
+
function isRichLimitError(err) {
|
|
1186
|
+
if (!err) return false;
|
|
1187
|
+
return RICH_LIMIT_ERR_RE.test(errorMessage(err));
|
|
1188
|
+
}
|
|
1189
|
+
|
|
915
1190
|
function isRichContentError(err) {
|
|
916
1191
|
if (!err) return false;
|
|
917
1192
|
return RICH_CONTENT_ERR_RE.test(errorMessage(err));
|
|
@@ -932,12 +1207,16 @@ module.exports = {
|
|
|
932
1207
|
isRichCapabilityErrorExplicit,
|
|
933
1208
|
isRichMessageFieldRejection,
|
|
934
1209
|
isRichContentError,
|
|
1210
|
+
isRichLimitError,
|
|
935
1211
|
errorMessage,
|
|
936
1212
|
stripMediaMarkdown,
|
|
937
1213
|
carriesMediaMarkdown,
|
|
1214
|
+
flattenStyledBlocks,
|
|
1215
|
+
blocksAreStyled,
|
|
938
1216
|
countMediaBlocks,
|
|
939
1217
|
// exported for tests / introspection, not part of the public contract
|
|
940
1218
|
_plainTextOf: plainTextOf,
|
|
1219
|
+
_richTextOf: richTextOf,
|
|
941
1220
|
_blocksFromTokens: blocksFromTokens,
|
|
942
1221
|
_stripFencedCodeBlocks: stripFencedCodeBlocks,
|
|
943
1222
|
IMAGE_RE,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0",
|
|
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
|
@@ -122,6 +122,7 @@ const { chunkMarkdownText } = require('./lib/telegram/chunk');
|
|
|
122
122
|
const {
|
|
123
123
|
toTelegramRichBlocks, resolveRichTextEnabled, isRichCapabilityError, isRichContentError,
|
|
124
124
|
isRichCapabilityErrorExplicit, isRichMessageFieldRejection, stripMediaMarkdown,
|
|
125
|
+
isRichLimitError,
|
|
125
126
|
} = require('./lib/telegram/rich');
|
|
126
127
|
const {
|
|
127
128
|
makeRichMediaResolver,
|
|
@@ -133,6 +134,7 @@ const {
|
|
|
133
134
|
} = require('./lib/telegram/rich-media');
|
|
134
135
|
const { createRichEditor } = require('./lib/telegram/rich-edit');
|
|
135
136
|
const { createRichCapabilityLatch } = require('./lib/telegram/rich-capability-latch');
|
|
137
|
+
const { createRichStylingLatch } = require('./lib/telegram/rich-styling-latch');
|
|
136
138
|
|
|
137
139
|
// What a reply consisting only of media the delivering path cannot render
|
|
138
140
|
// degrades to. Silence would leave the user with nothing and the agent
|
|
@@ -398,6 +400,14 @@ let richKnownUnsupported = false;
|
|
|
398
400
|
// 404 — a single shared flag would let the reply tool's probe permanently
|
|
399
401
|
// disable the streamer's working rich edits.
|
|
400
402
|
let richSendKnownUnsupported = false;
|
|
403
|
+
// A THIRD verdict, and deliberately not one of the two above. Those answer
|
|
404
|
+
// "can this server do rich at all", and tripping either costs every heading,
|
|
405
|
+
// table and task list. This one answers "does it accept typed RichText nodes
|
|
406
|
+
// inside block text", and tripping it costs bold, italic, code spans and
|
|
407
|
+
// links. A server that predates typed nodes still renders rich perfectly
|
|
408
|
+
// well, so the failure mode here must be "no styling", never "no rich".
|
|
409
|
+
let richInlineStylingUnsupported = false;
|
|
410
|
+
let richStylingLatch = null;
|
|
401
411
|
|
|
402
412
|
// Extracted to lib/telegram/rich-edit.js so the capability/content/
|
|
403
413
|
// transient error-classification + fallback wiring is directly unit-
|
|
@@ -1331,7 +1341,13 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1331
1341
|
});
|
|
1332
1342
|
const toRichPayload = (text, opts) => {
|
|
1333
1343
|
if (richKnownUnsupported || !resolveRichTextEnabled(config, chatId, threadId)) return null;
|
|
1334
|
-
|
|
1344
|
+
// Re-read per payload, like the gate above: a latch that trips on the
|
|
1345
|
+
// reply-tool path takes the streamer with it on the next flush.
|
|
1346
|
+
const payload = toTelegramRichBlocks(text, {
|
|
1347
|
+
...opts,
|
|
1348
|
+
resolveMedia: resolveRichMedia,
|
|
1349
|
+
inlineStyling: !richInlineStylingUnsupported,
|
|
1350
|
+
});
|
|
1335
1351
|
if (!opts.partial && payload?.usedRich) {
|
|
1336
1352
|
return {
|
|
1337
1353
|
...payload,
|
|
@@ -3237,6 +3253,14 @@ async function main() {
|
|
|
3237
3253
|
else richKnownUnsupported = true;
|
|
3238
3254
|
},
|
|
3239
3255
|
});
|
|
3256
|
+
richStylingLatch = createRichStylingLatch({
|
|
3257
|
+
setUnsupported: () => {
|
|
3258
|
+
richInlineStylingUnsupported = true;
|
|
3259
|
+
logEvent('rich-styling-latched', { bot: BOT_NAME });
|
|
3260
|
+
console.warn('[telegram] inline styling disabled for this process — '
|
|
3261
|
+
+ 'a styled payload was refused and the same content landed flattened, twice');
|
|
3262
|
+
},
|
|
3263
|
+
});
|
|
3240
3264
|
richEditMessageText = createRichEditor({
|
|
3241
3265
|
tg,
|
|
3242
3266
|
botName: BOT_NAME,
|
|
@@ -3244,12 +3268,18 @@ async function main() {
|
|
|
3244
3268
|
redactBotToken,
|
|
3245
3269
|
isRichCapabilityError,
|
|
3246
3270
|
isRichContentError,
|
|
3271
|
+
isRichLimitError,
|
|
3247
3272
|
getRichKnownUnsupported: () => richKnownUnsupported,
|
|
3248
3273
|
setRichKnownUnsupported: () => { richKnownUnsupported = true; },
|
|
3249
3274
|
getApiRoot: () => config.bot?.apiRoot || null,
|
|
3250
3275
|
stripUrlCreds: stripUrlCredentials,
|
|
3251
3276
|
sanitizeFallbackText: stripMediaMarkdown,
|
|
3252
3277
|
capabilityLatch: richCapabilityLatch,
|
|
3278
|
+
// The SAME verdict the reply-tool path feeds. One renderer, one
|
|
3279
|
+
// server, one answer — a latch reachable from only one path would let
|
|
3280
|
+
// the other keep authoring payloads this server has already refused.
|
|
3281
|
+
onStylingRejected: () => richStylingLatch?.recordStylingRejection(),
|
|
3282
|
+
onStylingAccepted: () => richStylingLatch?.recordHealthyOutcome(),
|
|
3253
3283
|
});
|
|
3254
3284
|
richSendMessage = createRichSender({
|
|
3255
3285
|
tg,
|
|
@@ -3259,6 +3289,7 @@ async function main() {
|
|
|
3259
3289
|
isRichCapabilityError,
|
|
3260
3290
|
isRichCapabilityErrorExplicit,
|
|
3261
3291
|
isRichContentError,
|
|
3292
|
+
isRichLimitError,
|
|
3262
3293
|
getRichKnownUnsupported: () => richSendKnownUnsupported,
|
|
3263
3294
|
setRichKnownUnsupported: () => { richSendKnownUnsupported = true; },
|
|
3264
3295
|
getApiRoot: () => config.bot?.apiRoot || null,
|
|
@@ -3628,6 +3659,13 @@ async function main() {
|
|
|
3628
3659
|
sendRich: (args) => richSendMessage(args),
|
|
3629
3660
|
isRichTextEnabled: (chatId, threadId) => resolveRichTextEnabled(config, chatId, threadId),
|
|
3630
3661
|
getRichKnownUnsupported: () => richSendKnownUnsupported,
|
|
3662
|
+
// No config knob: the automatic flatten-and-retry below IS the control,
|
|
3663
|
+
// and it needs no operator to notice anything. A knob would add a state
|
|
3664
|
+
// where styling is off while the server accepts it, which nothing in
|
|
3665
|
+
// the system can detect or correct.
|
|
3666
|
+
isInlineStylingEnabled: () => !richInlineStylingUnsupported,
|
|
3667
|
+
onStylingRejected: () => richStylingLatch?.recordStylingRejection(),
|
|
3668
|
+
onStylingAccepted: () => richStylingLatch?.recordHealthyOutcome(),
|
|
3631
3669
|
redactError: redactBotToken,
|
|
3632
3670
|
// Media for one reply. The envelope itself (no URL media, the `files:`
|
|
3633
3671
|
// fan-out ceiling, the shared stat) lives in rich-media.js so it is
|