polygram 0.31.0 → 0.33.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/README.md +5 -0
- package/config.example.json +2 -0
- package/lib/db.js +233 -9
- package/lib/handlers/dispatcher.js +84 -13
- package/lib/ops/clean-resume.js +358 -0
- package/lib/ops/clean-shutdown.js +84 -0
- package/lib/ops/shutdown-disposition.js +13 -4
- package/lib/process/channels-tool-dispatcher.js +12 -3
- package/lib/sdk/callbacks.js +2 -0
- package/lib/telegram/api.js +71 -3
- package/lib/telegram/composing-marker.js +53 -0
- package/lib/telegram/delivery-barrier.js +117 -0
- package/lib/telegram/process-agent-reply.js +18 -2
- package/lib/telegram/rich-edit.js +16 -5
- package/lib/telegram/rich-media.js +18 -2
- package/lib/telegram/rich.js +36 -0
- package/lib/telegram/streamer.js +327 -26
- package/migrations/018-clean-restart-resume.sql +24 -0
- package/package.json +2 -2
- package/polygram.js +406 -43
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const DELIVERY_CLASSES = new Set(['reply-bearing', 'operational-ui']);
|
|
4
|
+
|
|
5
|
+
function deliveryBarrierError() {
|
|
6
|
+
const error = new Error('reply-bearing Telegram delivery is fenced');
|
|
7
|
+
error.code = 'DELIVERY_FENCED';
|
|
8
|
+
return error;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function createDeliveryBarrier() {
|
|
12
|
+
let fenced = false;
|
|
13
|
+
const outputSourcesBySession = new Map();
|
|
14
|
+
const uncorrelatedOutput = new Set();
|
|
15
|
+
const pending = new Set();
|
|
16
|
+
const pendingBySession = new Map();
|
|
17
|
+
const forgetWhenIdle = new Set();
|
|
18
|
+
|
|
19
|
+
function forget(sessionKey) {
|
|
20
|
+
outputSourcesBySession.delete(sessionKey);
|
|
21
|
+
uncorrelatedOutput.delete(sessionKey);
|
|
22
|
+
forgetWhenIdle.delete(sessionKey);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function inspect(sessionKey, sourceMsgId = null) {
|
|
26
|
+
const outputSources = outputSourcesBySession.get(sessionKey);
|
|
27
|
+
return {
|
|
28
|
+
outputAttempted: uncorrelatedOutput.has(sessionKey)
|
|
29
|
+
|| (
|
|
30
|
+
sourceMsgId == null
|
|
31
|
+
? (outputSources?.size ?? 0) > 0
|
|
32
|
+
: outputSources?.has(sourceMsgId) === true
|
|
33
|
+
),
|
|
34
|
+
pending: pendingBySession.get(sessionKey)?.size ?? 0,
|
|
35
|
+
fenced,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function run({
|
|
40
|
+
sessionKey = null,
|
|
41
|
+
sourceMsgId = null,
|
|
42
|
+
deliveryClass,
|
|
43
|
+
} = {}, operation) {
|
|
44
|
+
if (!DELIVERY_CLASSES.has(deliveryClass)) {
|
|
45
|
+
return Promise.reject(new TypeError('Telegram delivery class is invalid'));
|
|
46
|
+
}
|
|
47
|
+
if (typeof operation !== 'function') {
|
|
48
|
+
return Promise.reject(new TypeError('Telegram delivery operation is required'));
|
|
49
|
+
}
|
|
50
|
+
if (deliveryClass === 'operational-ui') {
|
|
51
|
+
return Promise.resolve().then(operation);
|
|
52
|
+
}
|
|
53
|
+
if (fenced) return Promise.reject(deliveryBarrierError());
|
|
54
|
+
|
|
55
|
+
if (sessionKey != null) {
|
|
56
|
+
forgetWhenIdle.delete(sessionKey);
|
|
57
|
+
if (sourceMsgId == null) uncorrelatedOutput.add(sessionKey);
|
|
58
|
+
else {
|
|
59
|
+
let outputSources = outputSourcesBySession.get(sessionKey);
|
|
60
|
+
if (!outputSources) {
|
|
61
|
+
outputSources = new Set();
|
|
62
|
+
outputSourcesBySession.set(sessionKey, outputSources);
|
|
63
|
+
}
|
|
64
|
+
outputSources.add(sourceMsgId);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const operationPromise = Promise.resolve().then(operation);
|
|
68
|
+
pending.add(operationPromise);
|
|
69
|
+
if (sessionKey != null) {
|
|
70
|
+
let sessionPending = pendingBySession.get(sessionKey);
|
|
71
|
+
if (!sessionPending) {
|
|
72
|
+
sessionPending = new Set();
|
|
73
|
+
pendingBySession.set(sessionKey, sessionPending);
|
|
74
|
+
}
|
|
75
|
+
sessionPending.add(operationPromise);
|
|
76
|
+
}
|
|
77
|
+
operationPromise.finally(() => {
|
|
78
|
+
pending.delete(operationPromise);
|
|
79
|
+
if (sessionKey == null) return;
|
|
80
|
+
const sessionPending = pendingBySession.get(sessionKey);
|
|
81
|
+
sessionPending?.delete(operationPromise);
|
|
82
|
+
if (sessionPending?.size === 0) {
|
|
83
|
+
pendingBySession.delete(sessionKey);
|
|
84
|
+
if (forgetWhenIdle.has(sessionKey)) forget(sessionKey);
|
|
85
|
+
}
|
|
86
|
+
}).catch(() => {});
|
|
87
|
+
return operationPromise;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function fenceAndDrain() {
|
|
91
|
+
fenced = true;
|
|
92
|
+
while (pending.size > 0) {
|
|
93
|
+
await Promise.allSettled([...pending]);
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
pending: 0,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function retireSession(sessionKey) {
|
|
101
|
+
if ((pendingBySession.get(sessionKey)?.size ?? 0) > 0) {
|
|
102
|
+
forgetWhenIdle.add(sessionKey);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
forget(sessionKey);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
run,
|
|
110
|
+
inspect,
|
|
111
|
+
fenceAndDrain,
|
|
112
|
+
retireSession,
|
|
113
|
+
isFenced: () => fenced,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { createDeliveryBarrier };
|
|
@@ -83,7 +83,8 @@
|
|
|
83
83
|
* @param {?string|number} [opts.sessionKey] — for event payloads
|
|
84
84
|
* @param {object} [opts.logger] — { log, error }
|
|
85
85
|
* @returns {Promise<{ deliverResult: ?object, stickersSent: number, reactionsApplied: number,
|
|
86
|
-
* reactionsDropped: number,
|
|
86
|
+
* reactionsDropped: number, auxiliaryFailures: number, deliveryAmbiguous: boolean,
|
|
87
|
+
* sanitizerReplaced: boolean, secretsRedacted: number,
|
|
87
88
|
* emptiedByStrategy?: boolean }>} — `emptiedByStrategy` marks a reply whose text
|
|
88
89
|
* projected away entirely, so nothing was delivered and the caller must decide
|
|
89
90
|
* what to tell the agent.
|
|
@@ -116,6 +117,8 @@ async function processAndDeliverAgentText({
|
|
|
116
117
|
stickersSent: 0,
|
|
117
118
|
reactionsApplied: 0,
|
|
118
119
|
reactionsDropped: 0,
|
|
120
|
+
auxiliaryFailures: 0,
|
|
121
|
+
deliveryAmbiguous: false,
|
|
119
122
|
sanitizerReplaced: false,
|
|
120
123
|
secretsRedacted: 0,
|
|
121
124
|
};
|
|
@@ -259,6 +262,8 @@ async function processAndDeliverAgentText({
|
|
|
259
262
|
});
|
|
260
263
|
summary.stickersSent += 1;
|
|
261
264
|
} catch (err) {
|
|
265
|
+
summary.auxiliaryFailures += 1;
|
|
266
|
+
summary.deliveryAmbiguous = true;
|
|
262
267
|
logger.error?.(`[${source}] sendSticker(${parsed.stickerLabel}) failed: ${err.message}`);
|
|
263
268
|
}
|
|
264
269
|
}
|
|
@@ -278,6 +283,8 @@ async function processAndDeliverAgentText({
|
|
|
278
283
|
});
|
|
279
284
|
summary.stickersSent += 1;
|
|
280
285
|
} catch (err) {
|
|
286
|
+
summary.auxiliaryFailures += 1;
|
|
287
|
+
summary.deliveryAmbiguous = true;
|
|
281
288
|
logger.error?.(`[${source}] inline sendSticker(${s.name}) failed: ${err.message}`);
|
|
282
289
|
}
|
|
283
290
|
}
|
|
@@ -312,9 +319,18 @@ async function processAndDeliverAgentText({
|
|
|
312
319
|
chat_id: chatId,
|
|
313
320
|
message_id: replyToMessageId,
|
|
314
321
|
reaction: [{ type: 'emoji', emoji }],
|
|
315
|
-
}, {
|
|
322
|
+
}, {
|
|
323
|
+
...meta,
|
|
324
|
+
sessionKey,
|
|
325
|
+
sourceMsgId: meta.sourceMsgId ?? replyToMessageId,
|
|
326
|
+
deliveryClass: 'reply-bearing',
|
|
327
|
+
source: `${source}-reaction`,
|
|
328
|
+
reaction: emoji,
|
|
329
|
+
});
|
|
316
330
|
summary.reactionsApplied += 1;
|
|
317
331
|
} catch (err) {
|
|
332
|
+
summary.auxiliaryFailures += 1;
|
|
333
|
+
summary.deliveryAmbiguous = true;
|
|
318
334
|
logger.error?.(`[${source}] setMessageReaction(${emoji}) failed: ${err.message}`);
|
|
319
335
|
}
|
|
320
336
|
if (allReactions.length > 1) {
|
|
@@ -115,7 +115,7 @@ function defaultMakeInputFile(source, bytes = null) {
|
|
|
115
115
|
* and the SAME tree, flattened, was accepted. The two differ in exactly one
|
|
116
116
|
* respect, which is what makes it evidence about styling.
|
|
117
117
|
* @param {() => void} [deps.onStylingAccepted] — a styled payload landed
|
|
118
|
-
* @returns {(args: {bot, chatId: string, threadId: (string|null), messageId: number, blocks: Array, sourceText: string, phase?: string, mediaContext?: object, hadReplyAnchor?: boolean}) => Promise<{result: *, wentRich: boolean, bubbleRemoved?: boolean}>}
|
|
118
|
+
* @returns {(args: {bot, chatId: string, threadId: (string|null), messageId: number, blocks: Array, sourceText: string, phase?: string, mediaContext?: object, hadReplyAnchor?: boolean, meta?: object}) => Promise<{result: *, wentRich: boolean, bubbleRemoved?: boolean}>}
|
|
119
119
|
*/
|
|
120
120
|
function createRichEditor({
|
|
121
121
|
tg,
|
|
@@ -169,11 +169,12 @@ function createRichEditor({
|
|
|
169
169
|
phase = 'preview',
|
|
170
170
|
mediaContext = null,
|
|
171
171
|
hadReplyAnchor = false,
|
|
172
|
+
meta = {},
|
|
172
173
|
}) {
|
|
173
174
|
if (getRichKnownUnsupported()) {
|
|
174
175
|
const res = await tg(bot, 'editMessageText', {
|
|
175
176
|
chat_id: chatId, message_id: messageId, text: sanitizeFallbackText(sourceText),
|
|
176
|
-
}, { source: 'bot-reply-stream-edit-rich-fallback', botName });
|
|
177
|
+
}, { ...meta, source: 'bot-reply-stream-edit-rich-fallback', botName });
|
|
177
178
|
return { result: res, wentRich: false };
|
|
178
179
|
}
|
|
179
180
|
|
|
@@ -190,7 +191,12 @@ function createRichEditor({
|
|
|
190
191
|
mediaContext?.preflightMedia,
|
|
191
192
|
),
|
|
192
193
|
},
|
|
193
|
-
}, {
|
|
194
|
+
}, {
|
|
195
|
+
...meta,
|
|
196
|
+
source: 'bot-reply-stream-edit-rich',
|
|
197
|
+
botName,
|
|
198
|
+
richSourceText: sourceText,
|
|
199
|
+
});
|
|
194
200
|
latch.recordHealthyOutcome();
|
|
195
201
|
if (blocksAreStyled(blocks)) {
|
|
196
202
|
try { onStylingAccepted(); } catch { /* a verdict must not cost a delivered edit */ }
|
|
@@ -280,7 +286,12 @@ function createRichEditor({
|
|
|
280
286
|
mediaContext?.preflightMedia,
|
|
281
287
|
),
|
|
282
288
|
},
|
|
283
|
-
}, {
|
|
289
|
+
}, {
|
|
290
|
+
...meta,
|
|
291
|
+
source: 'bot-reply-stream-edit-rich-unstyled',
|
|
292
|
+
botName,
|
|
293
|
+
richSourceText: sourceText,
|
|
294
|
+
});
|
|
284
295
|
if (!limitRefusal) {
|
|
285
296
|
try { onStylingRejected(); } catch { /* the edit landed either way */ }
|
|
286
297
|
}
|
|
@@ -324,7 +335,7 @@ function createRichEditor({
|
|
|
324
335
|
// single owner of discard/redelivery.
|
|
325
336
|
const fallbackRes = await tg(bot, 'editMessageText', {
|
|
326
337
|
chat_id: chatId, message_id: messageId, text: fallbackText,
|
|
327
|
-
}, { source: 'bot-reply-stream-edit-rich-fallback', botName });
|
|
338
|
+
}, { ...meta, source: 'bot-reply-stream-edit-rich-fallback', botName });
|
|
328
339
|
|
|
329
340
|
if (canRescue) {
|
|
330
341
|
await rescueBestEffort({
|
|
@@ -630,6 +630,8 @@ function createMediaDeliveryContext({
|
|
|
630
630
|
threadId = null,
|
|
631
631
|
replyToMessageId = null,
|
|
632
632
|
botName = null,
|
|
633
|
+
sessionKey = null,
|
|
634
|
+
sourceMsgId = null,
|
|
633
635
|
logEvent = null,
|
|
634
636
|
setDeliveryError = () => {},
|
|
635
637
|
logger = console,
|
|
@@ -665,7 +667,13 @@ function createMediaDeliveryContext({
|
|
|
665
667
|
await tg(bot, 'deleteMessage', {
|
|
666
668
|
chat_id: chatId,
|
|
667
669
|
message_id: messageId,
|
|
668
|
-
}, {
|
|
670
|
+
}, {
|
|
671
|
+
sessionKey,
|
|
672
|
+
sourceMsgId,
|
|
673
|
+
...meta,
|
|
674
|
+
source: 'bot-reply-rich-media-placeholder-delete',
|
|
675
|
+
botName,
|
|
676
|
+
});
|
|
669
677
|
return true;
|
|
670
678
|
} catch (err) {
|
|
671
679
|
recordFailure('deletion');
|
|
@@ -713,6 +721,8 @@ function createMediaDeliveryContext({
|
|
|
713
721
|
}
|
|
714
722
|
try {
|
|
715
723
|
const result = await tg(bot, rescue.method, params, {
|
|
724
|
+
sessionKey,
|
|
725
|
+
sourceMsgId,
|
|
716
726
|
...meta,
|
|
717
727
|
source: 'bot-reply-rich-media-rescue',
|
|
718
728
|
botName,
|
|
@@ -788,7 +798,13 @@ function createMediaDeliveryContext({
|
|
|
788
798
|
chat_id: chatId,
|
|
789
799
|
text: `⚠️ ${parts.join(' and ')} failed. The reply may be ${risks.join(' or ')} — please retry.`,
|
|
790
800
|
...(threadId != null && { message_thread_id: threadId }),
|
|
791
|
-
}, {
|
|
801
|
+
}, {
|
|
802
|
+
sessionKey,
|
|
803
|
+
sourceMsgId,
|
|
804
|
+
...meta,
|
|
805
|
+
source: 'partial-delivery-warning',
|
|
806
|
+
botName,
|
|
807
|
+
});
|
|
792
808
|
} catch (err) {
|
|
793
809
|
logger.warn?.('[rich-media] partial-delivery warning failed');
|
|
794
810
|
}
|
package/lib/telegram/rich.js
CHANGED
|
@@ -1169,6 +1169,41 @@ function toTelegramRichBlocks(markdown, opts = {}) {
|
|
|
1169
1169
|
return { blocks, usedRich: true };
|
|
1170
1170
|
}
|
|
1171
1171
|
|
|
1172
|
+
/**
|
|
1173
|
+
* partialVisibleExtent(markdown) -> number of leading SOURCE characters that a
|
|
1174
|
+
* partial render actually puts on screen.
|
|
1175
|
+
*
|
|
1176
|
+
* Partial mode holds the last top-level block back (it may be half-written),
|
|
1177
|
+
* so the reader sees the source behind blocks 0..n-2 and nothing of the rest.
|
|
1178
|
+
* Anything that needs to reason about "what has the reader already seen"
|
|
1179
|
+
* has to ask the renderer, because only the renderer knows where its own
|
|
1180
|
+
* blocks begin and end — a blank-line heuristic disagrees with it in both
|
|
1181
|
+
* directions (a fence or a loose list carries internal blank lines; adjacent
|
|
1182
|
+
* headings carry none).
|
|
1183
|
+
*
|
|
1184
|
+
* Returns the extent of the largest token prefix that renders no MORE than
|
|
1185
|
+
* the displayed blocks, so the answer is exact wherever a token maps to one
|
|
1186
|
+
* block and errs toward reporting less rather than claiming the reader saw
|
|
1187
|
+
* something they did not.
|
|
1188
|
+
*/
|
|
1189
|
+
function partialVisibleExtent(markdown) {
|
|
1190
|
+
if (typeof markdown !== 'string' || markdown.length === 0) return 0;
|
|
1191
|
+
const tokens = _lexer.lexer(markdown);
|
|
1192
|
+
const displayed = blocksFromTokens(tokens, FLAT).length - 1;
|
|
1193
|
+
// One block (or none) is emitted whole rather than held back, so all of it
|
|
1194
|
+
// reached the screen — same rule toTelegramRichBlocks applies.
|
|
1195
|
+
if (displayed < 1) return markdown.length;
|
|
1196
|
+
|
|
1197
|
+
let extent = 0;
|
|
1198
|
+
let consumed = 0;
|
|
1199
|
+
for (let n = 1; n <= tokens.length; n += 1) {
|
|
1200
|
+
consumed += (tokens[n - 1].raw || '').length;
|
|
1201
|
+
if (blocksFromTokens(tokens.slice(0, n), FLAT).length > displayed) break;
|
|
1202
|
+
extent = consumed;
|
|
1203
|
+
}
|
|
1204
|
+
return extent;
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1172
1207
|
// ─── Error classification ────────────────────────────────────────────
|
|
1173
1208
|
//
|
|
1174
1209
|
// Capability errors (endpoint missing) latch
|
|
@@ -1254,6 +1289,7 @@ const RICH_MAX_LEN = 32768;
|
|
|
1254
1289
|
module.exports = {
|
|
1255
1290
|
needsRichRendering,
|
|
1256
1291
|
toTelegramRichBlocks,
|
|
1292
|
+
partialVisibleExtent,
|
|
1257
1293
|
RICH_MAX_LEN,
|
|
1258
1294
|
resolveRichTextEnabled,
|
|
1259
1295
|
isRichCapabilityError,
|