polygram 0.28.1 → 0.29.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.28.1",
4
+ "version": "0.29.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",
@@ -697,11 +697,13 @@ function validateProjectedConfig(config, materialized) {
697
697
  }
698
698
 
699
699
  function validateProjectedLayers(layers, materialized) {
700
- if (!Array.isArray(layers) || ![1, 2].includes(layers.length)) {
700
+ if (!Array.isArray(layers) || ![1, 2, 3].includes(layers.length)) {
701
701
  throw new Error('config layers are outside the owned layer set');
702
702
  }
703
703
  let userCount = 0;
704
704
  let systemCount = 0;
705
+ let projectCount = 0;
706
+ const emptyConfigSha256 = digest({});
705
707
  for (const layer of layers) {
706
708
  if (
707
709
  !layer
@@ -711,26 +713,40 @@ function validateProjectedLayers(layers, materialized) {
711
713
  !== JSON.stringify(['configSha256', 'disabled', 'type', 'version'])
712
714
  || typeof layer.version !== 'string'
713
715
  || layer.version.length === 0
714
- || layer.disabled !== false
715
716
  || !SHA256_RE.test(layer.configSha256)
716
717
  ) {
717
718
  throw new Error('config layer projection is malformed');
718
719
  }
719
720
  if (layer.type === 'user') {
720
721
  userCount += 1;
721
- if (layer.configSha256 !== digest(materialized.ownedConfig)) {
722
+ if (
723
+ layer.disabled !== false
724
+ || layer.configSha256 !== digest(materialized.ownedConfig)
725
+ ) {
722
726
  throw new Error('owned user layer hash changed');
723
727
  }
724
728
  } else if (layer.type === 'system') {
725
729
  systemCount += 1;
726
- if (layer.configSha256 !== digest({})) {
730
+ if (
731
+ layer.disabled !== false
732
+ || layer.configSha256 !== emptyConfigSha256
733
+ ) {
727
734
  throw new Error('system layer is not empty');
728
735
  }
736
+ } else if (layer.type === 'project') {
737
+ projectCount += 1;
738
+ if (
739
+ layer.disabled !== true
740
+ || layer.configSha256 !== emptyConfigSha256
741
+ || layer.version !== `sha256:${emptyConfigSha256}`
742
+ ) {
743
+ throw new Error('disabled project layer is not empty');
744
+ }
729
745
  } else {
730
746
  throw new Error('unexpected config layer is active');
731
747
  }
732
748
  }
733
- if (userCount !== 1 || systemCount > 1) {
749
+ if (userCount !== 1 || systemCount > 1 || projectCount > 1) {
734
750
  throw new Error('owned user layer is not unique');
735
751
  }
736
752
  }
@@ -131,6 +131,15 @@ function createChannelsToolDispatcher({
131
131
  // secret ([redact:<secret>]) from the stored inbound. Optional; omitted in
132
132
  // tests / legacy callers (the helper no-ops when undefined).
133
133
  redactInbound = null,
134
+ // Rich rendering for `edit_message`: { plan, edit } (see rich-edit-dispatch.js).
135
+ // Injected for the same reason the reply path's strategy is — rich-media.js
136
+ // requires this module, so requiring the rich modules here is a cycle.
137
+ // Omitted, every edit is plain, exactly as before.
138
+ richEdit = null,
139
+ // (chatId, messageId, text) → void. An edit rewrites the bubble but never
140
+ // revisited its `messages` row, so the transcript kept whatever the original
141
+ // send captured. Called on success only.
142
+ persistEditedText = null,
134
143
  logEvent = null,
135
144
  logger = console,
136
145
  maxChunkLen = 4000,
@@ -200,9 +209,60 @@ function createChannelsToolDispatcher({
200
209
  let clean = text;
201
210
  try { const p = parseResponse(text); if (p && typeof p.text === 'string') clean = p.text; } catch { /* keep raw */ }
202
211
  try { const s = sanitizeAssistantReply(clean); if (s && typeof s.text === 'string') clean = s.text; } catch { /* keep */ }
203
- if (clean.length === 0) return { ok: false, error: 'edit_message.text empty after sanitize' };
204
- if (clean.length > maxChunkLen) {
205
- return { ok: false, error: `edit text too long (${clean.length} > ${maxChunkLen}); a message edit is a single bubble — use reply for long content` };
212
+ // Whitespace-only counts as empty: it reaches tg()'s guard as a failure
213
+ // the agent can do nothing with, and the media check below reads as a
214
+ // lie about why when the text never had anything in it.
215
+ if (clean.trim().length === 0) return { ok: false, error: 'edit_message.text empty after sanitize' };
216
+
217
+ // Rich or plain is settled BEFORE the length gate, because the two modes
218
+ // carry different caps: a rich-eligible edit runs to the rich ceiling,
219
+ // everything else to the single-bubble one. Planning is pure — no
220
+ // network — so an over-cap edit can be refused with something the agent
221
+ // can act on instead of Telegram's raw "message is too long" arriving
222
+ // from the plain fallback of a rich attempt that already rewrote the
223
+ // bubble. A planner that fails costs the structure, never the edit.
224
+ // The seed is what a failed or malformed planner falls back to, so it
225
+ // gets the same chat-level hygiene the chunked reply path gets: in a
226
+ // rich-enabled chat this is the difference between a degraded edit and
227
+ // one that renders an absolute local path into the bubble. Projection
228
+ // failing must not cost the edit either, so it degrades to the raw text
229
+ // the tool has always sent.
230
+ let plan = { mode: 'plain', text: clean, maxLen: maxChunkLen };
231
+ if (typeof projectFallbackText === 'function') {
232
+ try {
233
+ const projected = projectFallbackText(clean, { chatId, threadId });
234
+ if (typeof projected === 'string') plan = { ...plan, text: projected };
235
+ } catch (err) {
236
+ logger.error?.(`[channels-tool-dispatcher] ${sessionKey} edit fallback projection failed: ${redactError(String(err?.message || err))}`);
237
+ }
238
+ }
239
+ if (richEdit && typeof richEdit.plan === 'function') {
240
+ try {
241
+ const planned = richEdit.plan({ chatId, threadId, text: clean, plainMaxLen: maxChunkLen });
242
+ if (planned && typeof planned.text === 'string' && Number.isFinite(planned.maxLen)) {
243
+ // A rich plan is only a rich plan if it carries blocks. Taking one
244
+ // on trust means discovering the omission from inside the try
245
+ // below — AFTER the edit landed — and reporting ok:false on a
246
+ // delivered edit. Demoted whole: the rich CEILING travels with the
247
+ // blocks, never with the mode alone.
248
+ plan = (planned.mode === 'rich' && !(Array.isArray(planned.blocks) && planned.blocks.length > 0))
249
+ ? { mode: 'plain', text: planned.text, maxLen: maxChunkLen }
250
+ : planned;
251
+ }
252
+ } catch (err) {
253
+ logger.error?.(`[channels-tool-dispatcher] ${sessionKey} rich edit planning failed: ${redactError(String(err?.message || err))}`);
254
+ }
255
+ }
256
+ const body = plan.text;
257
+ // A rich-enabled chat renders the media-stripped body, so an edit that
258
+ // was nothing but media has nothing left to say. Refuse it here rather
259
+ // than let an empty text reach tg()'s guard — and say why, since media
260
+ // cannot be added by an edit at all.
261
+ if (body.trim().length === 0) {
262
+ return { ok: false, error: 'edit_message.text has no text left after media was stripped — an edit renders text only; send media with reply(files:)' };
263
+ }
264
+ if (body.length > plan.maxLen) {
265
+ return { ok: false, error: `edit text too long (${body.length} > ${plan.maxLen}); a message edit is a single bubble — use reply for long content` };
206
266
  }
207
267
  // Ownership gate (review 2026-06-12): only edit a bubble THIS session
208
268
  // created (got its id from a reply/edit result). Blocks a prompt-injected
@@ -212,14 +272,46 @@ function createChannelsToolDispatcher({
212
272
  return { ok: false, error: `message_id ${messageId} was not created by this session — edit_message can only target a bubble you sent` };
213
273
  }
214
274
  try {
215
- const params = { chat_id: chatId, message_id: messageId, text: clean };
216
- if (threadId) params.message_thread_id = threadId;
217
- await send(bot, 'editMessageText', params, { source: 'channels-tool-dispatcher', sessionKey, toolName });
275
+ if (plan.mode === 'rich') {
276
+ // Rethrows transients by contract (the streamer's retry logic wants
277
+ // them); this catch is what keeps that from crossing the tool
278
+ // boundary as an unhandled rejection instead of an ack.
279
+ await richEdit.edit({
280
+ chatId, threadId, messageId, blocks: plan.blocks, sourceText: body,
281
+ });
282
+ } else {
283
+ const params = { chat_id: chatId, message_id: messageId, text: body };
284
+ if (threadId) params.message_thread_id = threadId;
285
+ await send(bot, 'editMessageText', params, { source: 'channels-tool-dispatcher', sessionKey, toolName });
286
+ }
218
287
  rememberOwned(sessionKey, messageId); // keep ownership across re-edits
288
+ // The bubble now says something the stored row does not. Persisting is
289
+ // the lesser half of this call: a throw here must not turn a delivered
290
+ // edit into a reported failure.
291
+ try { persistEditedText?.(chatId, messageId, body); }
292
+ catch (err) {
293
+ logger.error?.(`[channels-tool-dispatcher] ${sessionKey} edit transcript update failed: ${err.message}`);
294
+ }
219
295
  return { ok: true, message_id: messageId };
220
296
  } catch (err) {
221
- logger.error?.(`[channels-tool-dispatcher] ${sessionKey} edit_message failed: ${err.message}`);
222
- return { ok: false, error: err.message };
297
+ // Network error shapes can embed the request URL, which carries the
298
+ // bot token — and this string goes straight back to the agent.
299
+ const detail = redactError(String(err?.message || err));
300
+ logger.error?.(`[channels-tool-dispatcher] ${sessionKey} edit_message failed: ${detail}`);
301
+ // The one over-cap case that cannot be caught before the network: the
302
+ // SERVER refused the rich render, and rich-edit's plain fallback then
303
+ // carried a body past the single-bubble cap. Telegram's own "message
304
+ // is too long" is true but unactionable here — it reads as a bug in
305
+ // the agent's length arithmetic when the real story is that the
306
+ // structure it counted on was refused.
307
+ if (plan.mode === 'rich' && body.length > maxChunkLen) {
308
+ return {
309
+ ok: false,
310
+ error: `rich rendering was refused for this edit and the text (${body.length} chars) is past the `
311
+ + `plain single-bubble limit of ${maxChunkLen} — shorten it or send it as a reply (${detail})`,
312
+ };
313
+ }
314
+ return { ok: false, error: detail };
223
315
  }
224
316
  }
225
317
 
@@ -15,10 +15,20 @@
15
15
  * on its first 404 while the other still believed it was protected — which
16
16
  * is exactly the restart blip the rule exists to survive.
17
17
  *
18
- * The VERDICT, unlike the counter, is per verb. A server can implement
19
- * `editMessageText{rich_message}` and not the newer `sendRichMessage`,
20
- * answering the latter with a bare 404. One shared verdict would let a probe
21
- * of the new verb permanently disable rich edits that are working.
18
+ * The VERDICT, unlike the counter, follows the EVIDENCE rather than the path
19
+ * that happened to collect it, and the two kinds of evidence say different
20
+ * things:
21
+ *
22
+ * - Verb-specific evidence stays per verb. A bare 404, or a rejection
23
+ * naming a missing METHOD, is about one endpoint: a server can implement
24
+ * `editMessageText{rich_message}` and not the newer `sendRichMessage`,
25
+ * answering the latter with a 404. One shared verdict would let a probe
26
+ * of the new verb permanently disable rich edits that are working.
27
+ * - Shared-field rejections condemn both verbs, by design. `rich_message`
28
+ * is the same field on both requests, so a server that cannot read it on
29
+ * one cannot read it on the other — whichever path happened to hear it
30
+ * first. This is not a leak in the per-verb rule; it is what the rule
31
+ * says once you ask what the error was actually about.
22
32
  *
23
33
  * "Consecutive" means consecutive RICH ATTEMPTS across both paths, not
24
34
  * consecutive replies and not consecutive minutes: attempts that never
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Rich rendering for the `edit_message` tool: decide, then edit.
3
+ *
4
+ * Sibling of rich-dispatch.js, which does the same job for `reply`. It lives
5
+ * here rather than in the channels dispatcher because rich-media.js requires
6
+ * that module — importing the rich modules from there would close a require
7
+ * cycle — and because the decision is worth testing without a dispatcher
8
+ * around it.
9
+ *
10
+ * The split into plan() + edit() is the whole point. A rich-eligible edit may
11
+ * run to the rich ceiling; everything else is bound by the caller's plain one.
12
+ * The caller therefore has to know WHICH ceiling applies before anything
13
+ * reaches the network — otherwise an oversized body rides a rich attempt down
14
+ * to its plain fallback and comes back as Telegram's raw "message is too
15
+ * long", after the bubble has already been rewritten. So plan() resolves the
16
+ * flag, the latch, the body and the blocks without sending anything, and never
17
+ * throws; edit() is the only half that talks to Telegram.
18
+ *
19
+ * Media is deliberately out of scope. Rendering runs on media-stripped text —
20
+ * no resolver, no mediaContext, no preflight — so `![shot](/abs/path)`
21
+ * degrades to its caption exactly as on every other path that cannot upload,
22
+ * and no branch can render an absolute local path into the chat. Media in an
23
+ * edit would need its own resolver and TOCTOU story; it is a separate feature
24
+ * if it is ever one.
25
+ */
26
+
27
+ 'use strict';
28
+
29
+ const {
30
+ toTelegramRichBlocks,
31
+ needsRichRendering,
32
+ stripMediaMarkdown,
33
+ RICH_MAX_LEN,
34
+ } = require('./rich');
35
+
36
+ // Did the render actually produce structure, or just prose?
37
+ //
38
+ // The gate that admits text to the renderer is pattern-based and therefore
39
+ // looser than the parser: `---|` at the start of a line satisfies the
40
+ // table-row pattern, but marked needs a header row to build a table, so a
41
+ // megabyte of prose with one such line renders as paragraphs and nothing
42
+ // else. Sending that as rich would ship a document of plain prose AND hand it
43
+ // the 32k ceiling on the strength of structure it does not have.
44
+ //
45
+ // So the verdict comes from the rendered tree, not from the source: anything
46
+ // other than a paragraph is structure. A list, table, heading, blockquote,
47
+ // divider, details or code block all qualify; a tree of paragraphs does not.
48
+ // Top-level is enough — a paragraph cannot contain blocks, so structure
49
+ // nested anywhere has a non-paragraph ancestor here.
50
+ function hasStructuralBlock(blocks) {
51
+ return (blocks || []).some((b) => b && typeof b.type === 'string' && b.type !== 'paragraph');
52
+ }
53
+
54
+ /**
55
+ * @param {object} deps
56
+ * @param {Function} deps.editRich — ({chatId, threadId, messageId, blocks, sourceText})
57
+ * → Promise<{result, wentRich}>; polygram wires richEditMessageText (bot and
58
+ * phase closed over). Contracted to RETHROW transients, which is why edit()
59
+ * does not catch: the caller owns the tool result.
60
+ * @param {(chatId, threadId) => boolean} deps.isRichTextEnabled — resolved per
61
+ * call against live config, so a config change mid-session applies at once
62
+ * @param {() => boolean} [deps.getRichKnownUnsupported] — the EDIT verb's
63
+ * capability latch, the same one richEditMessageText consults
64
+ * @param {Function} [deps.toRichBlocks] — markdown → { blocks, usedRich }
65
+ * @param {() => boolean} [deps.isInlineStylingEnabled] — process-wide styling
66
+ * verdict, re-read per edit so a latch that trips applies to the next one
67
+ * @param {number} [deps.richMaxLen]
68
+ * @param {(s: string) => string} [deps.redactError]
69
+ * @param {object} [deps.logger]
70
+ * @returns {{plan: Function, edit: Function}}
71
+ */
72
+ function createRichEditStrategy({
73
+ editRich,
74
+ isRichTextEnabled,
75
+ getRichKnownUnsupported = () => false,
76
+ toRichBlocks = toTelegramRichBlocks,
77
+ isInlineStylingEnabled = () => false,
78
+ richMaxLen = RICH_MAX_LEN,
79
+ redactError = (s) => s,
80
+ logger = console,
81
+ } = {}) {
82
+ if (typeof editRich !== 'function') {
83
+ throw new TypeError('rich-edit-dispatch: editRich required');
84
+ }
85
+ if (typeof isRichTextEnabled !== 'function') {
86
+ throw new TypeError('rich-edit-dispatch: isRichTextEnabled required');
87
+ }
88
+
89
+ return {
90
+ /**
91
+ * Pure: no network, no throw. Returns the mode, the body that mode would
92
+ * deliver, and the length cap that applies to it.
93
+ *
94
+ * @param {object} args
95
+ * @param {number} args.plainMaxLen — the caller's single-bubble cap, used
96
+ * whenever this edit is not rich-shaped
97
+ * @returns {{mode: 'rich'|'plain', text: string, maxLen: number, blocks?: Array}}
98
+ */
99
+ plan({ chatId, threadId = null, text, plainMaxLen }) {
100
+ const plain = (body, maxLen = plainMaxLen) => ({ mode: 'plain', text: body, maxLen });
101
+
102
+ // Flag off → this chat never opted into rich. Behave exactly as before,
103
+ // raw markdown included: rewriting text here would change delivery for a
104
+ // chat that asked for nothing.
105
+ let richCapable = false;
106
+ try { richCapable = isRichTextEnabled(chatId, threadId) === true; }
107
+ catch (err) { logger?.error?.(`[rich-edit-dispatch] richText gate failed: ${redactError(String(err?.message || err))}`); }
108
+ if (!richCapable) return plain(text);
109
+
110
+ // From here the chat IS rich-enabled, so no branch may render a local
111
+ // path — including the branches that end up delivering plain.
112
+ //
113
+ // keepPathlessFragments: an edit arrives COMPLETE. The streaming
114
+ // projection cuts any dangling "![alt" because the rest of the path may
115
+ // still be on its way; here nothing is on its way, so that same cut just
116
+ // eats the tail of a sentence the agent finished writing. Only a
117
+ // fragment that has opened its destination and shows a separator can
118
+ // leak a path, and that one still goes.
119
+ const body = stripMediaMarkdown(text, { keepPathlessFragments: true }) ?? '';
120
+
121
+ try { if (getRichKnownUnsupported() === true) return plain(body); }
122
+ catch { return plain(body); }
123
+
124
+ // The gate toRichBlocks applies internally, asked first so the cap can
125
+ // be resolved without rendering. Rich typography is for structure —
126
+ // ordinary prose sent through it renders oversized with no knob to
127
+ // correct it — so prose stays plain and stays on the plain cap.
128
+ //
129
+ // This gate treats a divider or a blockquote as structure, so 6k of
130
+ // prose ending in one `---` renders rich and takes the 32k ceiling.
131
+ // That is deliberate: it is the same trigger set the REPLY path uses,
132
+ // and an edit that rendered differently from the reply that created the
133
+ // bubble would be the worse surprise. The rendered-output check below is
134
+ // what keeps the loose PATTERNS from admitting prose that produced no
135
+ // structure at all.
136
+ let richShaped = false;
137
+ try { richShaped = needsRichRendering(body) === true; } catch { richShaped = false; }
138
+ if (!richShaped) return plain(body);
139
+
140
+ // Rich-shaped content is measured against the rich ceiling even when it
141
+ // busts it: reporting the plain cap for a chat that renders 32k
142
+ // checklists would be a lie about what this chat accepts. Checked
143
+ // BEFORE rendering — a body that cannot be sent either way should not
144
+ // cost a parse.
145
+ if (body.length > richMaxLen) return plain(body, richMaxLen);
146
+
147
+ let blocks = null;
148
+ try {
149
+ const rendered = toRichBlocks(body, { inlineStyling: isInlineStylingEnabled() === true });
150
+ if (rendered?.usedRich && Array.isArray(rendered.blocks) && rendered.blocks.length > 0
151
+ // The source looked structural to the pattern gate; the tree is
152
+ // what says whether it IS. Paragraph-only means the gate matched
153
+ // something the parser did not build (see hasStructuralBlock), and
154
+ // this edit is prose — plain, on the plain cap.
155
+ && hasStructuralBlock(rendered.blocks)) {
156
+ blocks = rendered.blocks;
157
+ }
158
+ } catch (err) {
159
+ logger?.error?.(`[rich-edit-dispatch] render failed: ${redactError(String(err?.message || err))}`);
160
+ }
161
+ // A render that declined, failed, or produced no structure costs the
162
+ // structure, never the edit.
163
+ if (!blocks) return plain(body);
164
+
165
+ return { mode: 'rich', text: body, blocks, maxLen: richMaxLen };
166
+ },
167
+
168
+ /**
169
+ * The only half that talks to Telegram. Transients propagate by design.
170
+ */
171
+ edit({ chatId, threadId = null, messageId, blocks, sourceText }) {
172
+ return editRich({ chatId, threadId, messageId, blocks, sourceText });
173
+ },
174
+ };
175
+ }
176
+
177
+ module.exports = { createRichEditStrategy };
@@ -497,7 +497,7 @@ function parseImageAt(line, start) {
497
497
  // Walk one line's image constructs. `onImage` decides what each becomes in
498
498
  // the projected text; an unparseable construct truncates the line there,
499
499
  // since anything after it is the tail of a destination we could not read.
500
- function rewriteImageConstructs(line, onImage) {
500
+ function rewriteImageConstructs(line, onImage, onUnparsed = () => '') {
501
501
  if (line.indexOf('![') === -1) return line;
502
502
  let out = '';
503
503
  let i = 0;
@@ -506,7 +506,10 @@ function rewriteImageConstructs(line, onImage) {
506
506
  if (next === -1) { out += line.slice(i); break; }
507
507
  out += line.slice(i, next);
508
508
  const parsed = parseImageAt(line, next);
509
- if (!parsed) return out;
509
+ // Unparseable: everything from here is the tail of a destination we could
510
+ // not read, so the default drops it. A caller whose text is COMPLETE can
511
+ // decide otherwise — see stripMediaMarkdown's keepPathlessFragments.
512
+ if (!parsed) return out + onUnparsed(line.slice(next));
510
513
  out += onImage(parsed);
511
514
  i = parsed.end;
512
515
  }
@@ -1021,8 +1024,23 @@ const MEDIA_WRAP_TAG_G_RE = /<\/?tg-(?:collage|slideshow)(?:[ \t][^>]*)?>/gi;
1021
1024
  // "![alt]", "![alt](", "![alt](/partial/pa…". Single negated classes,
1022
1025
  // optional groups anchored at $ — linear.
1023
1026
  const TRAILING_IMAGE_FRAGMENT_RE = /!\[[^\]\n]*(?:\][ \t]*(?:\([^)\n]*)?)?$/;
1027
+ // The same fragment, narrowed to the ones that actually expose a path: the
1028
+ // destination must have opened AND contain a separator. For text that is
1029
+ // COMPLETE when it arrives — a tool edit, not a stream tick — nothing can
1030
+ // finish a dangling "![alt", so it is literal content the author wrote and
1031
+ // cutting it silently eats the tail of their sentence. "![a](/User…" still
1032
+ // dies, which is the only shape that leaks a path.
1033
+ const TRAILING_IMAGE_PATH_FRAGMENT_RE = /!\[[^\]\n]*\][ \t]*\([^)\n]*\/[^)\n]*$/;
1024
1034
 
1025
- function stripMediaMarkdown(markdown) {
1035
+ /**
1036
+ * @param {string} markdown
1037
+ * @param {object} [opts]
1038
+ * @param {boolean} [opts.keepPathlessFragments=false] — cut only unterminated
1039
+ * fragments that carry a path separator. For a complete text; leave it off
1040
+ * for anything still streaming, where "![alt" IS a path fragment that has
1041
+ * not arrived yet.
1042
+ */
1043
+ function stripMediaMarkdown(markdown, { keepPathlessFragments = false } = {}) {
1026
1044
  if (typeof markdown !== 'string' || markdown.length === 0) return markdown;
1027
1045
  if (markdown.indexOf('![') === -1 && markdown.indexOf('<tg-') === -1) return markdown;
1028
1046
  const lines = markdown.split('\n');
@@ -1045,12 +1063,22 @@ function stripMediaMarkdown(markdown) {
1045
1063
  let clean = rewriteImageConstructs(
1046
1064
  line,
1047
1065
  ({ alt, title }) => (alt || title || '').trim(),
1066
+ // Keep an unreadable tail only when there is no path anywhere in it. A
1067
+ // tail with a separator may be a destination this parser could not read
1068
+ // but a chat client would still show — dropping it stays the rule. One
1069
+ // test decides the whole tail, so `![a] ![b](/real/path.png)` (parse
1070
+ // fails at the first construct) cannot slip a path through as literal
1071
+ // text.
1072
+ keepPathlessFragments ? (tail) => (/[/\\]/.test(tail) ? '' : tail) : undefined,
1048
1073
  ).replace(MEDIA_WRAP_TAG_G_RE, '');
1049
1074
  // Only a fragment on the FINAL line can still be completed by
1050
1075
  // text that hasn't streamed in yet; earlier lines can't (image
1051
1076
  // syntax never spans lines), so a fragment there is plain
1052
1077
  // malformed output — cut it the same way.
1053
- clean = clean.replace(TRAILING_IMAGE_FRAGMENT_RE, '');
1078
+ clean = clean.replace(
1079
+ keepPathlessFragments ? TRAILING_IMAGE_PATH_FRAGMENT_RE : TRAILING_IMAGE_FRAGMENT_RE,
1080
+ '',
1081
+ );
1054
1082
  out.push(clean);
1055
1083
  }
1056
1084
  const projected = out.join('\n');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.28.1",
3
+ "version": "0.29.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.1",
66
+ "@shumkov/orchestra": "0.10.2",
67
67
  "better-sqlite3": "^12.9.0",
68
68
  "grammy": "^1.42.0",
69
69
  "markdown-it": "^14.1.1",
package/polygram.js CHANGED
@@ -148,6 +148,7 @@ const { createRichStylingLatch } = require('./lib/telegram/rich-styling-latch');
148
148
  const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
149
149
  const { createRichSender } = require('./lib/telegram/rich-send');
150
150
  const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
151
+ const { createRichEditStrategy } = require('./lib/telegram/rich-edit-dispatch');
151
152
  const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
152
153
  const { buildPolygramDisplayHint } = require('./lib/telegram/display-hint');
153
154
  const { redactBotToken, stripUrlCredentials } = require('./lib/error/net');
@@ -404,7 +405,11 @@ let richKnownUnsupported = false;
404
405
  // Separate verdict for the newer sendRichMessage verb. A server can implement
405
406
  // editMessageText{rich_message} and not this one, answering it with a bare
406
407
  // 404 — a single shared flag would let the reply tool's probe permanently
407
- // disable the streamer's working rich edits.
408
+ // disable the streamer's working rich edits. Separate does not mean sealed:
409
+ // verb-specific evidence (a bare 404, a missing METHOD) stays per verb, while
410
+ // a rejection of the shared `rich_message` FIELD condemns both by design —
411
+ // the same field rides both requests, so a server that cannot read it on one
412
+ // cannot read it on the other.
408
413
  let richSendKnownUnsupported = false;
409
414
  // A THIRD verdict, and deliberately not one of the two above. Those answer
410
415
  // "can this server do rich at all", and tripping either costs every heading,
@@ -3279,7 +3284,9 @@ async function main() {
3279
3284
  // ONE latch decision for both rich paths. They set the same flag, so a
3280
3285
  // counter owned by either would let that path latch on its first bare
3281
3286
  // 404 while the other still believed two were required.
3282
- // One strike counter, one verdict per verb.
3287
+ // One strike counter; verdicts follow the evidence — per verb for a bare
3288
+ // 404 or a missing method, both verbs for a rejection of the shared
3289
+ // rich_message field.
3283
3290
  const richCapabilityLatch = createRichCapabilityLatch({
3284
3291
  isExplicit: isRichCapabilityErrorExplicit,
3285
3292
  isFieldRejection: isRichMessageFieldRejection,
@@ -3720,6 +3727,28 @@ async function main() {
3720
3727
  }),
3721
3728
  ]);
3722
3729
 
3730
+ // The edit tool's counterpart to the reply chain above. An agent that posts
3731
+ // a checklist through `reply` gets a rich bubble; without this it could
3732
+ // never tick an item off, because every edit re-sent that bubble as flat
3733
+ // text. Same renderer, same per-chat gate, same capability latch — the EDIT
3734
+ // verb's latch, which is the one richEditMessageText itself consults.
3735
+ const richEditStrategy = createRichEditStrategy({
3736
+ editRich: ({ chatId, threadId, messageId, blocks, sourceText }) => richEditMessageText({
3737
+ bot, chatId, threadId, messageId, blocks, sourceText,
3738
+ // A tool edit is a finished bubble, not a streaming tick.
3739
+ phase: 'final',
3740
+ // No mediaContext on purpose: this path renders media-stripped text, so
3741
+ // there is nothing to preflight, evict or rescue. Media in an edit
3742
+ // degrades to caption text, exactly as on every other path that cannot
3743
+ // upload it.
3744
+ }),
3745
+ isRichTextEnabled: (chatId, threadId) => resolveRichTextEnabled(config, chatId, threadId),
3746
+ getRichKnownUnsupported: () => richKnownUnsupported,
3747
+ isInlineStylingEnabled: () => !richInlineStylingUnsupported,
3748
+ redactError: redactBotToken,
3749
+ logger: console,
3750
+ });
3751
+
3723
3752
  // 0.11.0: channels backend wiring. Used when a chat opts in via
3724
3753
  // `pm: 'channels'` config. Falls back to SDK gracefully if the pinned
3725
3754
  // claude binary isn't present (see factory.js — channelsClaudeBin
@@ -3751,6 +3780,11 @@ async function main() {
3751
3780
  logEvent('deliver-media-only-degraded', { chat_id: chatId, thread_id: threadId, bot: BOT_NAME });
3752
3781
  return MEDIA_ONLY_FALLBACK_TEXT;
3753
3782
  },
3783
+ richEdit: richEditStrategy,
3784
+ // An edit rewrites the bubble; nothing revisited its row, so the
3785
+ // transcript kept whatever the original send captured — a checklist would
3786
+ // be stored unticked forever. Same helper the streamer finalizes with.
3787
+ persistEditedText: persistBubbleText,
3754
3788
  logEvent,
3755
3789
  logger: console,
3756
3790
  });