polygram 0.29.2 → 0.30.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
3
3
  "name": "polygram",
4
- "version": "0.29.2",
4
+ "version": "0.30.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",
@@ -229,6 +229,15 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
229
229
  // for any URL in the body (they clutter chats and add visual noise).
230
230
  // Default (no flag set) preserves Telegram's native preview behavior
231
231
  // — matches OpenClaw's account.config.linkPreview opt-out.
232
+ //
233
+ // Rich bubbles have never honored it, from two directions: sendRichMessage
234
+ // is not one of the methods above, and the rich form of editMessageText
235
+ // carries a meta built for the rich renderer that never had the flag in it.
236
+ // So a chat with the opt-out still gets preview cards under any rich reply.
237
+ // A bubble that OPENS rich only starts that gap one frame earlier than one
238
+ // that upgraded into it. Recorded, not fixed — the two paths would need the
239
+ // option threaded through the rich renderers, and no rich verb is known to
240
+ // accept it.
232
241
  if (meta.linkPreview === false
233
242
  && (method === 'sendMessage' || method === 'editMessageText')
234
243
  && params.link_preview_options == null) {
@@ -34,7 +34,7 @@ const {
34
34
  defaultMakeInputFile,
35
35
  MEDIA_SOURCE_CHANGED,
36
36
  } = require('./rich-edit');
37
- const { countMediaBlocks } = require('./rich');
37
+ const { countMediaBlocks, flattenStyledBlocks, blocksAreStyled } = require('./rich');
38
38
 
39
39
  /**
40
40
  * @param {object} deps
@@ -319,4 +319,58 @@ function errText(err) {
319
319
  return String(err.description || err.message || err);
320
320
  }
321
321
 
322
- module.exports = { createRichSender };
322
+ /**
323
+ * One rich send, with the flatten-and-retry ladder the reply-tool dispatcher
324
+ * runs around this same verb. Callers that open a streamed bubble use it so a
325
+ * styling-refusing server costs the same on an OPEN as on a reply: the
326
+ * structure survives, and the process learns from it.
327
+ *
328
+ * The retry flattens the tree that was REFUSED rather than re-rendering the
329
+ * source, so the two payloads differ in exactly one respect and a
330
+ * refused-then-accepted pair is evidence about styling and nothing else.
331
+ *
332
+ * Only a refusal that did NOT name a limit is that evidence. Flattening
333
+ * removes styling AND shrinks the payload, so a limit refusal is explained by
334
+ * the shrink; counting it would let two oversized replies disable styling for
335
+ * the whole process.
336
+ *
337
+ * @param {object} args
338
+ * @param {(args: object) => Promise<{wentRich: boolean, fallback?: string}>} args.sendRich
339
+ * @param {object} args.request — the sendRich argument object; `blocks` is the
340
+ * only field the retry changes
341
+ * @param {() => void} [args.onStylingRejected]
342
+ * @param {() => void} [args.onStylingAccepted]
343
+ * @param {object} [args.logger]
344
+ */
345
+ async function sendRichWithStylingRetry({
346
+ sendRich,
347
+ request,
348
+ onStylingRejected = () => {},
349
+ onStylingAccepted = () => {},
350
+ logger = console,
351
+ }) {
352
+ const styled = blocksAreStyled(request.blocks);
353
+ const out = await sendRich(request);
354
+ if (out?.wentRich) {
355
+ // A styled payload the server accepted — the evidence that ends any run
356
+ // of suspicion, so two unrelated content errors far apart cannot add up
357
+ // to a verdict.
358
+ if (styled) recordVerdict(onStylingAccepted, logger);
359
+ return out;
360
+ }
361
+ const contentRefused = out?.fallback === 'content-error' || out?.fallback === 'content-limit';
362
+ if (!styled || !contentRefused) return out;
363
+
364
+ const retried = await sendRich({ ...request, blocks: flattenStyledBlocks(request.blocks) });
365
+ if (retried?.wentRich && out.fallback === 'content-error') {
366
+ recordVerdict(onStylingRejected, logger);
367
+ }
368
+ return retried;
369
+ }
370
+
371
+ function recordVerdict(fn, logger) {
372
+ try { fn(); }
373
+ catch (err) { logger?.error?.(`[telegram] rich-send styling verdict failed: ${err.message}`); }
374
+ }
375
+
376
+ module.exports = { createRichSender, sendRichWithStylingRetry };
@@ -10,7 +10,8 @@
10
10
  * any -> finalize(finalText) -> finalized
11
11
  *
12
12
  * The streamer never talks to Telegram directly — callers inject
13
- * `send(text)`, `edit(msg_id, text)`, and (optional) `deleteMessage(msg_id)`.
13
+ * `send(payload)`, `edit(msg_id, payload)`, and (optional)
14
+ * `deleteMessage(msg_id)`.
14
15
  * That keeps polygram.js in charge of transcript writes, sticker/reaction
15
16
  * routing, and error handling; this module is just a cadence machine.
16
17
  *
@@ -45,8 +46,18 @@ const DEFAULT_THROTTLE_MS = 1000;
45
46
  const THROTTLE_FLOOR_MS = 250;
46
47
 
47
48
  function createStreamer({
48
- send, // async (text) -> { message_id, _hadReplyAnchor? }
49
- edit, // async (msg_id, text) -> void
49
+ // async (payload) -> { message_id, _hadReplyAnchor?, wentRich? }
50
+ //
51
+ // payload is a plain string, or — when the very first qualifying chunk
52
+ // already renders as structure — the rich shape { rich: true, blocks,
53
+ // sourceText, plainText }. (No `phase`, unlike an edit: a send is only
54
+ // ever the open.) A caller that cannot open rich delivers `plainText`
55
+ // instead and reports `wentRich: false`; the streamer then holds PLAIN
56
+ // state so the next flush edits the bubble it actually has. An absent
57
+ // `wentRich` means the payload landed as sent (backward compatible with
58
+ // plain-only callers).
59
+ send,
60
+ edit, // async (msg_id, payload) -> void
50
61
  deleteMessage = null, // async (msg_id) -> void [optional]
51
62
  minChars = DEFAULT_MIN_CHARS,
52
63
  throttleMs = DEFAULT_THROTTLE_MS,
@@ -105,7 +116,9 @@ function createStreamer({
105
116
  // messages, so rich edits and finalization must use this limit.
106
117
  richMaxLen = 32768,
107
118
  // Fires for each successful plain-to-rich transition. Caller wires this
108
- // to instrumentation for the visible bubble-shape change.
119
+ // to instrumentation for the visible bubble-shape change. A bubble that
120
+ // OPENS rich never had a plain shape to change, so it does not fire —
121
+ // the metric stays a count of visible flips.
109
122
  onRichUpgrade = () => {},
110
123
  } = {}) {
111
124
  // throttleMs may be a number OR a function evaluated per edit. Telegram's
@@ -196,10 +209,27 @@ function createStreamer({
196
209
  if (text.length < minChars) return;
197
210
  const generation = bubbleGeneration;
198
211
  state = 'live';
199
- currentText = truncateForLive(text);
212
+ // Open the bubble RICH when the first qualifying chunk already
213
+ // renders as structure. Without this the preview streams plain for
214
+ // the whole turn and converts to the rich document in one jump at
215
+ // finalize; opening rich means every later flush appends completed
216
+ // blocks to a document that was rich from its first frame.
217
+ // The rich payload measures against the rich cap, not the plain
218
+ // live-edit cap — resolveRichPayload owns that check, so an
219
+ // over-cap first chunk falls through to the truncated plain open.
220
+ const openRich = resolveRichPayload(text, { partial: true });
221
+ const plainText = truncateForLive(text);
222
+ currentText = openRich ? '' : plainText;
200
223
  let sendPromise;
201
224
  try {
202
- sendPromise = Promise.resolve(send(currentText));
225
+ sendPromise = Promise.resolve(send(openRich
226
+ ? {
227
+ rich: true, blocks: openRich.blocks, sourceText: text,
228
+ // What the plain path would have sent, so a caller that has to
229
+ // downgrade delivers a bubble under the PLAIN cap.
230
+ plainText,
231
+ }
232
+ : currentText));
203
233
  } catch (err) {
204
234
  sendPromise = Promise.reject(err);
205
235
  }
@@ -216,12 +246,27 @@ function createStreamer({
216
246
  state = 'idle';
217
247
  msgId = null;
218
248
  hadReplyAnchor = false;
249
+ currentRichJson = null;
250
+ } else if (openRich) {
251
+ // The open can resolve after delivering the same source as plain
252
+ // text (capability latch, refused payload). Seed rich state only
253
+ // for what actually landed: claiming rich over a plain bubble
254
+ // would let the next flush skip its edit as a no-op, and claiming
255
+ // plain over a rich one would overwrite the document with a plain
256
+ // edit — a visible downgrade.
257
+ if (res?.wentRich === false) {
258
+ currentText = plainText;
259
+ currentRichJson = null;
260
+ } else {
261
+ currentRichJson = JSON.stringify(openRich.blocks);
262
+ }
219
263
  }
220
264
  } catch (err) {
221
265
  if (generation !== bubbleGeneration) return;
222
266
  logger.error(`[stream] initial send failed: ${err.message}`);
223
267
  state = 'idle';
224
268
  hadReplyAnchor = false;
269
+ currentRichJson = null;
225
270
  } finally {
226
271
  if (initialSendPromise === sendPromise) initialSendPromise = null;
227
272
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.29.2",
3
+ "version": "0.30.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.4",
66
+ "@shumkov/orchestra": "0.10.5",
67
67
  "better-sqlite3": "^12.9.0",
68
68
  "grammy": "^1.42.0",
69
69
  "markdown-it": "^14.1.1",
package/polygram.js CHANGED
@@ -146,7 +146,7 @@ const { createRichStylingLatch } = require('./lib/telegram/rich-styling-latch');
146
146
  // degrades to. Silence would leave the user with nothing and the agent
147
147
  // believing it answered.
148
148
  const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
149
- const { createRichSender } = require('./lib/telegram/rich-send');
149
+ const { createRichSender, sendRichWithStylingRetry } = require('./lib/telegram/rich-send');
150
150
  const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
151
151
  const { createRichEditStrategy } = require('./lib/telegram/rich-edit-dispatch');
152
152
  const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
@@ -411,6 +411,22 @@ let richKnownUnsupported = false;
411
411
  // the same field rides both requests, so a server that cannot read it on one
412
412
  // cannot read it on the other.
413
413
  let richSendKnownUnsupported = false;
414
+ // A verdict for the STREAMED OPEN alone, held to a lower evidence bar than
415
+ // either latch above, and never fed back into them.
416
+ //
417
+ // A server that does rich edits but answers sendRichMessage with a bare 404
418
+ // never trips the send latch on this path: two ambiguous 404s in a row are
419
+ // what latch it, and the rich EDIT one flush later reports a healthy outcome
420
+ // that resets the run every time. So without this, every preview for the
421
+ // process lifetime pays a doomed round-trip and files a capability-strike the
422
+ // soak would read as a server going bad.
423
+ //
424
+ // One failure is enough here because the open is the one rich attempt with a
425
+ // guaranteed-working alternative: the bubble opens plain and the next flush
426
+ // renders it rich through the edit verb. The reply tool has no such second
427
+ // chance, which is why it keeps the two-strike rule and why this verdict must
428
+ // not touch it.
429
+ let richStreamOpenUnsupported = false;
414
430
  // A THIRD verdict, and deliberately not one of the two above. Those answer
415
431
  // "can this server do rich at all", and tripping either costs every heading,
416
432
  // table and task list. This one answers "does it accept typed RichText nodes
@@ -1411,23 +1427,64 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1411
1427
  // becomes rich during streaming.
1412
1428
  logEvent('rich-streaming-upgrade', { chat_id: chatId, thread_id: threadId, bot: BOT_NAME });
1413
1429
  },
1414
- send: async (text) => {
1430
+ send: async (payload) => {
1431
+ const openRich = payload && typeof payload === 'object' && payload.rich;
1415
1432
  const hadReplyAnchor = !firstBubbleSent;
1433
+ // allow_sending_without_reply: long-running turns give the user
1434
+ // plenty of time to delete their original message. Without this
1435
+ // flag, Telegram rejects the reply with MESSAGE_NOT_FOUND and the
1436
+ // whole streamed answer is lost.
1437
+ const replyParams = hadReplyAnchor
1438
+ ? { message_id: msg.message_id, allow_sending_without_reply: true }
1439
+ : null;
1440
+ // One bubble per call whichever verb carries it, so the anchor is
1441
+ // spent here rather than once per transport — a rich open that has
1442
+ // to downgrade still quotes the user exactly once.
1443
+ firstBubbleSent = true;
1444
+ if (openRich && !richStreamOpenUnsupported) {
1445
+ // sendRichMessage is the only verb that opens a bubble rich; a
1446
+ // plain send followed by a rich edit would flicker. It never
1447
+ // throws and reports whether rich actually landed, so a refusal
1448
+ // just opens plain here and the next flush retries via the edit
1449
+ // path (which is where the plain→rich upgrade metric belongs).
1450
+ const out = await sendRichWithStylingRetry({
1451
+ sendRich: richSendMessage,
1452
+ request: {
1453
+ bot, chatId, threadId,
1454
+ blocks: payload.blocks,
1455
+ sourceText: payload.sourceText,
1456
+ replyParams,
1457
+ mediaContext,
1458
+ // The soak needs to tell a streamed open from a reply-tool send:
1459
+ // they use one verb, one latch and one renderer, but only one of
1460
+ // them has a working second attempt when it fails.
1461
+ meta: { ...outMetaBase, source: 'bot-reply-stream-open-rich' },
1462
+ },
1463
+ onStylingRejected: () => richStylingLatch?.recordStylingRejection(),
1464
+ onStylingAccepted: () => richStylingLatch?.recordHealthyOutcome(),
1465
+ logger: { error: (m) => console.error(`[${label}] ${m}`) },
1466
+ });
1467
+ if (out?.wentRich) {
1468
+ return { ...out.result, _hadReplyAnchor: hadReplyAnchor, wentRich: true };
1469
+ }
1470
+ if (out?.fallback === 'capability') {
1471
+ // Stop probing. See richStreamOpenUnsupported — the streamer's
1472
+ // rich path continues through the edit verb from the next flush.
1473
+ richStreamOpenUnsupported = true;
1474
+ logEvent('rich-stream-open-unsupported', {
1475
+ chat_id: chatId, thread_id: threadId, bot: BOT_NAME,
1476
+ });
1477
+ }
1478
+ }
1416
1479
  const params = {
1417
- chat_id: chatId, text: sanitizeLiveText(text),
1480
+ chat_id: chatId,
1481
+ text: sanitizeLiveText(openRich ? payload.plainText : payload),
1418
1482
  ...(threadId && { message_thread_id: threadId }),
1419
1483
  };
1420
- if (!firstBubbleSent) {
1421
- // allow_sending_without_reply: long-running turns give the user
1422
- // plenty of time to delete their original message. Without this
1423
- // flag, Telegram rejects the reply with MESSAGE_NOT_FOUND and the
1424
- // whole streamed answer is lost.
1425
- params.reply_parameters = { message_id: msg.message_id, allow_sending_without_reply: true };
1426
- firstBubbleSent = true;
1427
- }
1484
+ if (replyParams) params.reply_parameters = replyParams;
1428
1485
  const res = await tg(bot, 'sendMessage', params, outMetaBase);
1429
1486
  return res && typeof res === 'object'
1430
- ? { ...res, _hadReplyAnchor: hadReplyAnchor }
1487
+ ? { ...res, _hadReplyAnchor: hadReplyAnchor, wentRich: false }
1431
1488
  : res;
1432
1489
  },
1433
1490
  edit: async (messageId, payload) => {