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