polygram 0.24.1 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/lib/process/channels-tool-dispatcher.js +24 -8
- package/lib/telegram/display-hint.js +14 -7
- package/lib/telegram/live-preview.js +28 -2
- package/lib/telegram/rich-dispatch.js +165 -46
- package/lib/telegram/rich-edit.js +29 -9
- package/lib/telegram/rich-media.js +246 -31
- package/lib/telegram/rich-send.js +95 -16
- package/lib/telegram/rich.js +30 -2
- package/package.json +1 -1
- package/polygram.js +63 -22
|
@@ -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.25.1",
|
|
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",
|
|
@@ -97,9 +97,10 @@ function validateAttachmentPath(filePath, allowedRoots) {
|
|
|
97
97
|
* @param {Function} deps.parseResponse — Review F#1: text → { text, sticker, stickers[], reaction, reactions[], ... }; required so [sticker:NAME] / [react:EMOJI] don't leak as literal text
|
|
98
98
|
* @param {Function} deps.sanitizeAssistantReply — Review F#1: text → { text, replaced, original? }; required so CLI canned strings (`No response requested.`) are intercepted
|
|
99
99
|
* @param {Function} [deps.processAndDeliverAgentText] — Review F#1: defaults to lib/telegram/process-agent-reply.js helper; DI-overridable for tests
|
|
100
|
-
* @param {Function} [deps.makeDeliverText] — ({sessionKey, sessionCwd, chatId, threadId, interim, turnId}) → deliverText
|
|
100
|
+
* @param {Function} [deps.makeDeliverText] — ({sessionKey, sessionCwd, allowedRoots, chatId, threadId, interim, turnId}) → deliverText
|
|
101
101
|
* strategy for the reply pipeline (see process-agent-reply.js). Built per call because
|
|
102
|
-
* sessionCwd, the interim flag, and the turn id are only known here.
|
|
102
|
+
* sessionCwd, the allowed roots, the interim flag, and the turn id are only known here.
|
|
103
|
+
* Injected rather
|
|
103
104
|
* than required: rich-media.js requires THIS module, so importing the rich modules from
|
|
104
105
|
* here would close a require cycle.
|
|
105
106
|
* @param {Function} [deps.projectFallbackText] — (text, {chatId, threadId}) → text;
|
|
@@ -236,6 +237,16 @@ function createChannelsToolDispatcher({
|
|
|
236
237
|
}
|
|
237
238
|
|
|
238
239
|
try {
|
|
240
|
+
// ONE roots array per reply, computed here and used by BOTH the files:
|
|
241
|
+
// validation below and whatever the delivery strategy uploads. Two
|
|
242
|
+
// computations would be two trust boundaries: a path the reply tool may
|
|
243
|
+
// upload must be exactly a path rich media may upload, for this call.
|
|
244
|
+
const allowedRoots = buildAllowedRoots({
|
|
245
|
+
sessionKey,
|
|
246
|
+
sessionCwd: call.sessionCwd,
|
|
247
|
+
extraRoots: attachmentAllowlist,
|
|
248
|
+
});
|
|
249
|
+
|
|
239
250
|
// Per-call delivery strategy: sessionCwd (and so the roots any media
|
|
240
251
|
// would be validated against) is known only here, never at construction
|
|
241
252
|
// time. Building it is optional in the strictest sense — if it fails,
|
|
@@ -246,6 +257,10 @@ function createChannelsToolDispatcher({
|
|
|
246
257
|
try {
|
|
247
258
|
deliverText = makeDeliverText({
|
|
248
259
|
sessionKey, sessionCwd: call.sessionCwd || null, chatId, threadId,
|
|
260
|
+
// The paths this call may upload. Passed rather than rebuilt: a
|
|
261
|
+
// strategy recomputing them from config would silently widen the
|
|
262
|
+
// set if config drifted after the session was spawned.
|
|
263
|
+
allowedRoots,
|
|
249
264
|
// A status update, not the turn's answer: a strategy holding a live
|
|
250
265
|
// preview must not let an interim reply consume the bubble the real
|
|
251
266
|
// answer is still being written into.
|
|
@@ -333,11 +348,6 @@ function createChannelsToolDispatcher({
|
|
|
333
348
|
failedAttachments.push({ path: extra, error: `too many files in one reply (max ${MAX_FILES_PER_REPLY}); send the rest in a follow-up` });
|
|
334
349
|
}
|
|
335
350
|
}
|
|
336
|
-
const allowedRoots = buildAllowedRoots({
|
|
337
|
-
sessionKey,
|
|
338
|
-
sessionCwd: call.sessionCwd,
|
|
339
|
-
extraRoots: attachmentAllowlist,
|
|
340
|
-
});
|
|
341
351
|
for (const filePath of toAttach) {
|
|
342
352
|
const check = validateAttachmentPath(filePath, allowedRoots);
|
|
343
353
|
if (!check.ok) {
|
|
@@ -425,11 +435,13 @@ function createChannelsToolDispatcher({
|
|
|
425
435
|
|
|
426
436
|
/**
|
|
427
437
|
* Build the per-call allowed-roots list. Includes:
|
|
428
|
-
* - DEFAULT_ATTACHMENT_BASE (/tmp/polygram-attachments — host-wide staging)
|
|
429
438
|
* - /tmp/polygram-attachments/<sessionKey>/ (per-session staging)
|
|
430
439
|
* - sessionCwd if provided (the agent's workspace)
|
|
431
440
|
* - extraRoots passed from createChannelsToolDispatcher options
|
|
432
441
|
*
|
|
442
|
+
* DEFAULT_ATTACHMENT_BASE itself is deliberately NOT a root — see the
|
|
443
|
+
* security note below.
|
|
444
|
+
*
|
|
433
445
|
* Caller is expected to ensure DEFAULT_ATTACHMENT_BASE / the per-session
|
|
434
446
|
* dir exist if Claude will write to them. We don't create them here —
|
|
435
447
|
* realpath() on a nonexistent root fails and the validator rejects, which
|
|
@@ -456,6 +468,10 @@ function buildAllowedRoots({ sessionKey, sessionCwd = null, extraRoots = [] }) {
|
|
|
456
468
|
|
|
457
469
|
module.exports = {
|
|
458
470
|
createChannelsToolDispatcher,
|
|
471
|
+
// The reply's attachment fan-out ceiling, shared with the reply tool's
|
|
472
|
+
// media wiring so a reply can't route more media through image syntax than
|
|
473
|
+
// through files:.
|
|
474
|
+
MAX_FILES_PER_REPLY,
|
|
459
475
|
// exported for unit testing
|
|
460
476
|
validateAttachmentPath,
|
|
461
477
|
buildAllowedRoots,
|
|
@@ -58,17 +58,21 @@ const TABLES_AND_HEADERS_SECTION_PLAIN = [
|
|
|
58
58
|
'- Long replies stream in chunks; prefer concise structure over walls of text.',
|
|
59
59
|
].join('\n');
|
|
60
60
|
|
|
61
|
-
// Media guidance is separated out because it is NOT true on every path
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
//
|
|
66
|
-
//
|
|
61
|
+
// Media guidance is separated out because it is NOT true on every path: a
|
|
62
|
+
// path that cannot resolve media degrades an image to its caption, and
|
|
63
|
+
// teaching syntax the delivering path discards makes the agent author
|
|
64
|
+
// constructs that silently vanish. Each caller states what its own path can
|
|
65
|
+
// do. It doubles as the exposure control — media traffic starts when the
|
|
66
|
+
// guidance does.
|
|
67
67
|
const INLINE_MEDIA_PARAGRAPHS = [
|
|
68
68
|
'**Inline media:** use the unchanged `` syntax on its own line. Local `.jpg`, `.jpeg`, `.png`, and `.webp` files become photos; `.mp4` becomes video; `.gif` becomes animation. Use an absolute path inside your workspace or the attachments staging dir. An unreachable path or unsupported type degrades to a plain "(media unavailable)" line — it will not error. Always accompany media with at least a sentence of substantive text.',
|
|
69
69
|
'',
|
|
70
70
|
'**Grouping media:** wrap consecutive supported media in `<tg-collage>…</tg-collage>` (grid) or `<tg-slideshow>…</tg-slideshow>` (swipeable) to send them as one mixed-media block.',
|
|
71
71
|
'',
|
|
72
|
+
'**At most 10 media items per reply.** Extras are dropped silently — you will not be told — so split a longer visual walkthrough across several replies.',
|
|
73
|
+
'',
|
|
74
|
+
'**Inline media or `files:`, not both.** A file you embed inline is already delivered; listing that same path in `files:` too sends it a second time as a separate message. Use inline media when the image belongs in the reply, and `files:` when you are handing over a document.',
|
|
75
|
+
'',
|
|
72
76
|
];
|
|
73
77
|
|
|
74
78
|
// Rich-mode guidance is limited to the constructs detected by
|
|
@@ -104,7 +108,7 @@ const richSection = (inlineMedia) => [
|
|
|
104
108
|
'- [ ] Size-guide page (#16)',
|
|
105
109
|
'```',
|
|
106
110
|
'',
|
|
107
|
-
'**Task lists for progress:** `- [ ] pending step` / `- [x] done step` renders as a real checkbox list — the natural way to show multi-step progress, a batch of items awaiting confirmation, or anything else with a per-item done/pending state.',
|
|
111
|
+
'**Task lists for progress:** `- [ ] pending step` / `- [x] done step` renders as a real checkbox list — the natural way to show multi-step progress, a batch of items awaiting confirmation, or anything else with a per-item done/pending state. Checkboxes carry meaning only when their states VARY or evolve: use them when some items are already `[x]` done, or when you will send an updated list with items checked off as you complete them. A list that would be all-`[ ]` forever is just a list — use plain bullets.',
|
|
108
112
|
'',
|
|
109
113
|
'**Collapsible detail:** wrap verbose logs/diffs/output you want available but not front-and-center in `<details><summary>Label</summary>...</details>`.',
|
|
110
114
|
'',
|
|
@@ -194,4 +198,7 @@ module.exports = {
|
|
|
194
198
|
TELEGRAM_TABLE_WIDTH_BUDGET,
|
|
195
199
|
buildPolygramDisplayHint,
|
|
196
200
|
appendDisplayHint,
|
|
201
|
+
// Exactly what the media gate adds, so a test can subtract it rather than
|
|
202
|
+
// pattern-match for it and miss a newly added paragraph.
|
|
203
|
+
INLINE_MEDIA_PARAGRAPHS,
|
|
197
204
|
};
|
|
@@ -273,6 +273,12 @@ function createTurnSettler({
|
|
|
273
273
|
* @param {Function} [deps.persistBubbleText] — (chatId, msgId, text) → void
|
|
274
274
|
* @param {object} [deps.logger]
|
|
275
275
|
* @param {?string} [deps.botName] — event payload tag
|
|
276
|
+
* @param {(text: string, ctx: {chatId, threadId}) => string} [deps.projectConsumedText]
|
|
277
|
+
* — applied to the text a CONSUMED reply finalizes the preview with. The
|
|
278
|
+
* bubble is rendered by the streamer, whose media resolver answers to the
|
|
279
|
+
* interactive path's rules rather than the reply tool's, so media must not
|
|
280
|
+
* ride in on this branch. Identity by default; a decline is unaffected, so
|
|
281
|
+
* whatever the next strategy receives is still the text the agent wrote.
|
|
276
282
|
*/
|
|
277
283
|
function createDeliverTextFactory({
|
|
278
284
|
registry,
|
|
@@ -280,8 +286,9 @@ function createDeliverTextFactory({
|
|
|
280
286
|
persistBubbleText = null,
|
|
281
287
|
logger = console,
|
|
282
288
|
botName = null,
|
|
289
|
+
projectConsumedText = null,
|
|
283
290
|
} = {}) {
|
|
284
|
-
return function makeDeliverText({ sessionKey, chatId, interim, turnId } = {}) {
|
|
291
|
+
return function makeDeliverText({ sessionKey, chatId, threadId, interim, turnId } = {}) {
|
|
285
292
|
const entry = registry.get(sessionKey);
|
|
286
293
|
if (!entry) return null; // no live-preview surface for this turn
|
|
287
294
|
const { streamer } = entry;
|
|
@@ -296,7 +303,26 @@ function createDeliverTextFactory({
|
|
|
296
303
|
return run;
|
|
297
304
|
};
|
|
298
305
|
|
|
299
|
-
async function consume({ text }) {
|
|
306
|
+
async function consume({ text: authored }) {
|
|
307
|
+
// What this branch can deliver, which is not the same as what was
|
|
308
|
+
// written. Consuming means the STREAMER renders the bubble, under the
|
|
309
|
+
// interactive path's media rules — wider roots and a wider fan-out than
|
|
310
|
+
// the reply tool's, reached without any of its gates. Projecting media
|
|
311
|
+
// out here is what keeps "a reply-tool reply uploads only what the reply
|
|
312
|
+
// tool would" true on both branches. Media-free text is untouched, so
|
|
313
|
+
// every other reply is byte-identical.
|
|
314
|
+
//
|
|
315
|
+
// Used for the coverage bookkeeping too: what was delivered is what the
|
|
316
|
+
// orphan check must compare against, not what was authored.
|
|
317
|
+
//
|
|
318
|
+
// Follow-up, deliberately not done here: thread the dispatcher's own
|
|
319
|
+
// media wiring (its per-call roots and ceilings) into finalize, so a
|
|
320
|
+
// consumed reply can render inline media under the same boundary the
|
|
321
|
+
// reply tool applies instead of degrading to captions.
|
|
322
|
+
const text = typeof projectConsumedText === 'function'
|
|
323
|
+
? projectConsumedText(authored, { chatId, threadId })
|
|
324
|
+
: authored;
|
|
325
|
+
|
|
300
326
|
// A reply is bound to the turn it names. A delayed reply from an earlier
|
|
301
327
|
// turn must not finalize the CURRENT turn's preview with stale text; it
|
|
302
328
|
// still gets delivered, just as its own bubble.
|
|
@@ -8,11 +8,17 @@
|
|
|
8
8
|
* would close a require cycle — and because the decision logic is worth
|
|
9
9
|
* testing without a dispatcher around it.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
11
|
+
* Media renders only when the caller injects a media wiring for THIS call —
|
|
12
|
+
* a resolver bound to the roots the dispatcher already validates `files:`
|
|
13
|
+
* against, plus the preflight the send re-checks each local source with.
|
|
14
|
+
* Then rendering runs on the RAW text and `` becomes a
|
|
15
|
+
* photo/video/animation block. Without that wiring, rendering runs on
|
|
16
|
+
* media-stripped text instead: nothing could upload, so image syntax must not
|
|
17
|
+
* reach the renderer at all — it would emit placeholder bubbles and could
|
|
18
|
+
* even be the only reason a reply went rich.
|
|
19
|
+
*
|
|
20
|
+
* Either way no branch renders an absolute local path into the chat: the
|
|
21
|
+
* fallback body every decline hands back is the stripped one.
|
|
16
22
|
*
|
|
17
23
|
* Declining is always safe: the pipeline falls back to the chunked path that
|
|
18
24
|
* has always worked. Nothing here may throw its way out.
|
|
@@ -23,9 +29,44 @@
|
|
|
23
29
|
const {
|
|
24
30
|
toTelegramRichBlocks,
|
|
25
31
|
stripMediaMarkdown,
|
|
32
|
+
carriesMediaMarkdown,
|
|
26
33
|
RICH_MAX_LEN,
|
|
27
34
|
} = require('./rich');
|
|
28
35
|
|
|
36
|
+
// Every string a block tree can put on screen: block text, media captions,
|
|
37
|
+
// details summaries, and table cells. Walked rather than JSON.stringify'd so
|
|
38
|
+
// the check sees the same values the reader will.
|
|
39
|
+
function someBlockText(blocks, predicate) {
|
|
40
|
+
for (const b of blocks || []) {
|
|
41
|
+
if (typeof b?.text === 'string' && predicate(b.text)) return true;
|
|
42
|
+
if (typeof b?.caption?.text === 'string' && predicate(b.caption.text)) return true;
|
|
43
|
+
if (typeof b?.summary === 'string' && predicate(b.summary)) return true;
|
|
44
|
+
if (Array.isArray(b?.cells)) {
|
|
45
|
+
for (const row of b.cells) {
|
|
46
|
+
for (const cell of row || []) {
|
|
47
|
+
if (typeof cell?.text === 'string' && predicate(cell.text)) return true;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (Array.isArray(b?.blocks) && someBlockText(b.blocks, predicate)) return true;
|
|
52
|
+
if (Array.isArray(b?.items)) {
|
|
53
|
+
for (const item of b.items) {
|
|
54
|
+
if (typeof item?.text === 'string' && predicate(item.text)) return true;
|
|
55
|
+
if (Array.isArray(item?.blocks) && someBlockText(item.blocks, predicate)) return true;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// A resolver that accepts nothing, index-aligned with the descriptors it was
|
|
63
|
+
// given. Rendering through it (rather than through no resolver at all) is what
|
|
64
|
+
// turns each item into an honest "(media unavailable)" line instead of a
|
|
65
|
+
// silent removal.
|
|
66
|
+
const REJECT_ALL_MEDIA = (descriptors) => (descriptors || []).map(() => ({
|
|
67
|
+
rejected: 'source-changed',
|
|
68
|
+
}));
|
|
69
|
+
|
|
29
70
|
/**
|
|
30
71
|
* @param {object} deps
|
|
31
72
|
* @param {object} deps.bot — grammy Bot instance
|
|
@@ -34,11 +75,16 @@ const {
|
|
|
34
75
|
* against live config, so a config change mid-session takes effect immediately
|
|
35
76
|
* @param {() => boolean} deps.getRichKnownUnsupported — process-wide capability latch
|
|
36
77
|
* @param {Function} [deps.toRichBlocks] — markdown → { blocks, usedRich }
|
|
78
|
+
* @param {Function} [deps.makeMediaWiring] — ({allowedRoots, chatId, threadId})
|
|
79
|
+
* → {resolveMedia, mediaContext}. Omitted (or given no roots), the reply is
|
|
80
|
+
* delivered text-only. One function returns both halves because they MUST be
|
|
81
|
+
* built from the same roots and the same stat: a resolver and a preflight
|
|
82
|
+
* that disagree reject every file with nothing in the logs to say why.
|
|
37
83
|
* @param {(s: string) => string} [deps.redactError] — strips bot tokens from logged
|
|
38
84
|
* error text; network error shapes can embed the request URL
|
|
39
85
|
* @param {number} [deps.richMaxLen]
|
|
40
86
|
* @param {object} [deps.logger]
|
|
41
|
-
* @returns {(ctx: {sessionKey, sessionCwd, chatId, threadId}) => Function} strategy factory
|
|
87
|
+
* @returns {(ctx: {sessionKey, sessionCwd, allowedRoots, chatId, threadId}) => Function} strategy factory
|
|
42
88
|
*/
|
|
43
89
|
function createRichDeliveryFactory({
|
|
44
90
|
bot,
|
|
@@ -46,6 +92,7 @@ function createRichDeliveryFactory({
|
|
|
46
92
|
isRichTextEnabled,
|
|
47
93
|
getRichKnownUnsupported = () => false,
|
|
48
94
|
toRichBlocks = toTelegramRichBlocks,
|
|
95
|
+
makeMediaWiring = null,
|
|
49
96
|
richMaxLen = RICH_MAX_LEN,
|
|
50
97
|
redactError = (s) => s,
|
|
51
98
|
logger = console,
|
|
@@ -60,7 +107,7 @@ function createRichDeliveryFactory({
|
|
|
60
107
|
// Per-call factory: the chat/topic identity is fixed for a reply, but the
|
|
61
108
|
// gate is re-resolved on every delivery so live config edits apply without
|
|
62
109
|
// a respawn.
|
|
63
|
-
return function makeDeliverText({ chatId, threadId } = {}) {
|
|
110
|
+
return function makeDeliverText({ chatId, threadId, allowedRoots = null } = {}) {
|
|
64
111
|
return async function deliverText({ text, replyToMessageId = null, meta = {} } = {}) {
|
|
65
112
|
// Flag off → this chat has not opted into rich at all. Behave exactly
|
|
66
113
|
// as before, raw markdown included: rewriting text here would change
|
|
@@ -75,47 +122,119 @@ function createRichDeliveryFactory({
|
|
|
75
122
|
// Measured on the fallback body, which is what a decline delivers.
|
|
76
123
|
if (body.length > richMaxLen) return { handled: false, text: body };
|
|
77
124
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
125
|
+
// Built per call, from the roots the dispatcher validated this reply's
|
|
126
|
+
// `files:` against. A wiring that fails to build costs media, never the
|
|
127
|
+
// reply: the render below simply falls back to the stripped body.
|
|
128
|
+
let media = null;
|
|
129
|
+
if (typeof makeMediaWiring === 'function'
|
|
130
|
+
&& Array.isArray(allowedRoots) && allowedRoots.length > 0) {
|
|
131
|
+
try {
|
|
132
|
+
const built = makeMediaWiring({ allowedRoots, chatId, threadId });
|
|
133
|
+
// BOTH halves or neither. A resolver without a preflight would send
|
|
134
|
+
// local sources and cached ids to Telegram unchecked — the TOCTOU
|
|
135
|
+
// this path exists to close — so a half-built wiring is no wiring.
|
|
136
|
+
if (typeof built?.resolveMedia === 'function'
|
|
137
|
+
&& typeof built?.mediaContext?.preflightMedia === 'function') {
|
|
138
|
+
media = built;
|
|
139
|
+
}
|
|
140
|
+
} catch (err) {
|
|
141
|
+
logger?.error?.(`[rich-dispatch] media wiring unavailable: ${redactError(err.message)}`);
|
|
142
|
+
}
|
|
86
143
|
}
|
|
87
144
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
145
|
+
// Two measurements, two jobs. The gate above sizes the plain fallback,
|
|
146
|
+
// which is the stripped body. This one bounds what the RENDERER is
|
|
147
|
+
// handed — with media that is the RAW text, and the stripped body says
|
|
148
|
+
// nothing about it: image markdown collapses to a caption, so a reply
|
|
149
|
+
// that is a megabyte of `` lines measures a few characters while
|
|
150
|
+
// costing a filesystem round trip per descriptor, on the daemon's
|
|
151
|
+
// busiest path and in one synchronous pass.
|
|
152
|
+
if (media && text.length > richMaxLen) return { handled: false, text: body };
|
|
153
|
+
|
|
154
|
+
// `partial` is deliberately never set: final mode is the only one that
|
|
155
|
+
// both resolves media and emits the complete tree.
|
|
156
|
+
const render = (resolveMedia) => {
|
|
157
|
+
try {
|
|
158
|
+
const rendered = resolveMedia
|
|
159
|
+
? toRichBlocks(text, { resolveMedia })
|
|
160
|
+
: toRichBlocks(body);
|
|
161
|
+
if (!rendered?.usedRich) return null;
|
|
162
|
+
// The gate that decides "this looks like media" is looser than the
|
|
163
|
+
// parser that turns it into media: a destination containing a space
|
|
164
|
+
// or a parenthesis is not an image to the parser, and neither is an
|
|
165
|
+
// unterminated `) {
|
|
176
|
+
const stripped = toRichBlocks(body);
|
|
177
|
+
return stripped?.usedRich ? stripped.blocks : null;
|
|
178
|
+
}
|
|
179
|
+
return rendered.blocks;
|
|
180
|
+
} catch (err) {
|
|
181
|
+
logger?.error?.(`[rich-dispatch] render failed: ${redactError(err.message)}`);
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
// Mirrors the chunked path's anchor. allow_sending_without_reply
|
|
187
|
+
// matters more here, not less: a long turn gives the user time to
|
|
188
|
+
// delete the message being answered, and without the flag Telegram
|
|
189
|
+
// rejects the whole send with MESSAGE_NOT_FOUND — which this path
|
|
190
|
+
// would misread as a generic rich failure and quietly downgrade.
|
|
191
|
+
const replyParams = replyToMessageId != null
|
|
192
|
+
? { message_id: replyToMessageId, allow_sending_without_reply: true }
|
|
193
|
+
: null;
|
|
194
|
+
|
|
195
|
+
const attempt = async (blocks) => {
|
|
196
|
+
try {
|
|
197
|
+
// Direct send is the only mechanism here: sendRichMessage honors
|
|
198
|
+
// message_thread_id, reply_parameters and multipart media uploads, so
|
|
199
|
+
// a plain-send-then-rich-edit dance would buy nothing and cost a
|
|
200
|
+
// visible flicker.
|
|
201
|
+
return await sendRich({
|
|
202
|
+
bot,
|
|
203
|
+
chatId,
|
|
204
|
+
threadId,
|
|
205
|
+
blocks,
|
|
206
|
+
// The transcript keeps what the agent actually wrote; the operator's
|
|
207
|
+
// own DB is the accepted resting place for local paths, and the
|
|
208
|
+
// background secret sweep covers the row.
|
|
209
|
+
sourceText: text,
|
|
210
|
+
replyParams,
|
|
211
|
+
mediaContext: media?.mediaContext ?? null,
|
|
212
|
+
meta,
|
|
213
|
+
});
|
|
214
|
+
} catch (err) {
|
|
215
|
+
// sendRich is contracted not to throw. Not depending on that is the
|
|
216
|
+
// difference between a flat reply and a lost one.
|
|
217
|
+
// The branch exists because the no-throw contract might be broken;
|
|
218
|
+
// it must not then assume the error is free of request URLs.
|
|
219
|
+
logger?.error?.(`[rich-dispatch] send threw unexpectedly: ${redactError(err.message)}`);
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const blocks = render(media?.resolveMedia ?? null);
|
|
225
|
+
if (!blocks) return { handled: false, text: body };
|
|
226
|
+
|
|
227
|
+
let out = await attempt(blocks);
|
|
228
|
+
|
|
229
|
+
// A file changed between resolve and send. The structure is still worth
|
|
230
|
+
// keeping — losing a whole table because one screenshot was rewritten is
|
|
231
|
+
// the worse trade — so re-render once with a resolver that rejects
|
|
232
|
+
// everything. That yields honest "(media unavailable)" lines, and a
|
|
233
|
+
// reply whose only rich trigger WAS the media demotes to plain by
|
|
234
|
+
// itself, collapsing this ladder to two steps.
|
|
235
|
+
if (out && !out.wentRich && out.fallback === 'media-source-changed' && media) {
|
|
236
|
+
const retry = render(REJECT_ALL_MEDIA);
|
|
237
|
+
if (retry) out = await attempt(retry);
|
|
119
238
|
}
|
|
120
239
|
|
|
121
240
|
if (!out?.wentRich) return { handled: false, text: body };
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
'use strict';
|
|
18
18
|
|
|
19
|
+
const path = require('node:path');
|
|
19
20
|
const { countMediaBlocks } = require('./rich');
|
|
20
21
|
|
|
21
22
|
const MEDIA_SOURCE_CHANGED = 'RICH_MEDIA_SOURCE_CHANGED';
|
|
@@ -31,7 +32,10 @@ function materializeMediaBlocks(blocks, makeInputFile, preflightMedia = null) {
|
|
|
31
32
|
&& inputMedia.media && typeof inputMedia.media === 'object'
|
|
32
33
|
&& typeof inputMedia.media.source === 'string') {
|
|
33
34
|
const checked = typeof preflightMedia === 'function'
|
|
34
|
-
|
|
35
|
+
// withBytes: the upload carries the bytes the check read through its
|
|
36
|
+
// own descriptor, so nothing re-opens the path afterwards — not at
|
|
37
|
+
// request-build time, not on a 429 retry.
|
|
38
|
+
? preflightMedia(inputMedia.media, kind, { withBytes: true })
|
|
35
39
|
: {
|
|
36
40
|
ok: true,
|
|
37
41
|
value: typeof inputMedia.media.fileId === 'string' && inputMedia.media.fileId
|
|
@@ -48,7 +52,10 @@ function materializeMediaBlocks(blocks, makeInputFile, preflightMedia = null) {
|
|
|
48
52
|
...b,
|
|
49
53
|
[kind]: {
|
|
50
54
|
...inputMedia,
|
|
51
|
-
|
|
55
|
+
// Signature unchanged — the source stays the first argument, so a
|
|
56
|
+
// caller (or a test seam) that only cares about which file is being
|
|
57
|
+
// uploaded reads exactly what it always did.
|
|
58
|
+
media: typeof media === 'string' ? media : makeInputFile(media.source, media.bytes),
|
|
52
59
|
},
|
|
53
60
|
};
|
|
54
61
|
}
|
|
@@ -67,11 +74,16 @@ function materializeMediaBlocks(blocks, makeInputFile, preflightMedia = null) {
|
|
|
67
74
|
});
|
|
68
75
|
}
|
|
69
76
|
|
|
70
|
-
function defaultMakeInputFile(source) {
|
|
71
|
-
// Lazy require keeps unit tests free of the grammy dependency
|
|
72
|
-
// InputFile MUST be path-backed (never a stream/supplier) so api.js's
|
|
73
|
-
// 429/pre-connect retries can re-read it.
|
|
77
|
+
function defaultMakeInputFile(source, bytes = null) {
|
|
78
|
+
// Lazy require keeps unit tests free of the grammy dependency.
|
|
74
79
|
const { InputFile } = require('grammy');
|
|
80
|
+
// Bytes the preflight read through its own descriptor: upload those, so a
|
|
81
|
+
// file swapped after the check cannot be substituted at request-build time
|
|
82
|
+
// or on any retry. A buffer is re-usable, which is what api.js's 429 and
|
|
83
|
+
// pre-connect retries need (a stream or a supplier would not be).
|
|
84
|
+
if (Buffer.isBuffer(bytes)) return new InputFile(bytes, path.basename(source || ''));
|
|
85
|
+
// No preflight in play (a caller that opted out): a path-backed file, which
|
|
86
|
+
// is at least re-readable across those retries.
|
|
75
87
|
return new InputFile(source);
|
|
76
88
|
}
|
|
77
89
|
|
|
@@ -88,8 +100,9 @@ function defaultMakeInputFile(source) {
|
|
|
88
100
|
* @param {() => (string|null)} [deps.getApiRoot] — for the latch-trip log line only
|
|
89
101
|
* @param {(url: string) => string} [deps.stripUrlCreds] — strips basic-auth
|
|
90
102
|
* userinfo from apiRoot before logging
|
|
91
|
-
* @param {(source: string) => *} [deps.makeInputFile] —
|
|
92
|
-
*
|
|
103
|
+
* @param {(source: string, bytes?: Buffer) => *} [deps.makeInputFile] — source
|
|
104
|
+
* (plus the preflighted bytes, when the check read them) → uploadable file
|
|
105
|
+
* for grammy (test seam)
|
|
93
106
|
* @param {object} [deps.capabilityLatch] — shared latch decision (see
|
|
94
107
|
* rich-capability-latch.js). Pass the SAME instance the send path uses so a
|
|
95
108
|
* bare 404 on either counts toward one run of strikes. Omitted, every
|
|
@@ -275,4 +288,11 @@ function createRichEditor({
|
|
|
275
288
|
};
|
|
276
289
|
}
|
|
277
290
|
|
|
278
|
-
module.exports = {
|
|
291
|
+
module.exports = {
|
|
292
|
+
createRichEditor,
|
|
293
|
+
materializeMediaBlocks,
|
|
294
|
+
defaultMakeInputFile,
|
|
295
|
+
// The send path classifies this code before anything else; sharing the
|
|
296
|
+
// constant is what keeps the two catch blocks talking about the same thing.
|
|
297
|
+
MEDIA_SOURCE_CHANGED,
|
|
298
|
+
};
|