polygram 0.31.0 → 0.32.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/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/migrations/018-clean-restart-resume.sql +24 -0
- package/package.json +2 -2
- package/polygram.js +380 -41
|
@@ -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
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
-- One-shot ownership for a CLI turn interrupted by a deliberate restart.
|
|
2
|
+
--
|
|
3
|
+
-- generation_id is a non-identity reference token. It lets a restart intent
|
|
4
|
+
-- prove that the authoritative provider-session row was not replaced between
|
|
5
|
+
-- shutdown and boot without copying provider session identity into the intent.
|
|
6
|
+
|
|
7
|
+
ALTER TABLE agent_runtime_sessions ADD COLUMN generation_id TEXT;
|
|
8
|
+
|
|
9
|
+
UPDATE agent_runtime_sessions
|
|
10
|
+
SET generation_id = lower(hex(randomblob(16)))
|
|
11
|
+
WHERE generation_id IS NULL;
|
|
12
|
+
|
|
13
|
+
CREATE UNIQUE INDEX idx_agent_runtime_sessions_generation_id
|
|
14
|
+
ON agent_runtime_sessions(generation_id);
|
|
15
|
+
|
|
16
|
+
CREATE TABLE clean_restart_resume_intents (
|
|
17
|
+
bot_name TEXT NOT NULL,
|
|
18
|
+
session_key TEXT NOT NULL,
|
|
19
|
+
session_generation_id TEXT NOT NULL,
|
|
20
|
+
source_message_id INTEGER NOT NULL,
|
|
21
|
+
shutdown_at INTEGER NOT NULL,
|
|
22
|
+
policy_version INTEGER NOT NULL,
|
|
23
|
+
PRIMARY KEY(bot_name, session_key)
|
|
24
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.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": {
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@anthropic-ai/claude-agent-sdk": "0.2.123",
|
|
65
65
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
66
|
-
"@shumkov/orchestra": "0.10.
|
|
66
|
+
"@shumkov/orchestra": "0.10.6",
|
|
67
67
|
"better-sqlite3": "^12.9.0",
|
|
68
68
|
"grammy": "^1.42.0",
|
|
69
69
|
"markdown-it": "^14.1.1",
|