polygram 0.23.3 → 0.24.1

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.23.3",
4
+ "version": "0.24.1",
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",
package/README.md CHANGED
@@ -264,6 +264,15 @@ Per-bot flags:
264
264
  `/pairings`, `/unpair`.
265
265
  - `streamMinChars` (default 30) — debounce before the first stream edit.
266
266
  - `streamThrottleMs` (default 1000, min 250) — stream edit cadence.
267
+ - `streamPreview` (default false) — live preview of the answer on the CLI
268
+ backend. Also settable per chat and per topic (topic > chat > bot >
269
+ defaults). When on, the agent gets a `stream` tool it calls with the
270
+ answer-so-far while composing; the preview bubble becomes the reply, so
271
+ a streamed turn still produces exactly one bubble. Telegram rate-limits
272
+ edits per CHAT, so with this on the effective cadence is
273
+ `streamThrottleMs × (live previews in the chat)` — several busy forum
274
+ topics cost the chat what one does. Off, the cadence is
275
+ `streamThrottleMs` unchanged.
267
276
  - `voice: { enabled, provider: "openai"|"local", ... }` — Whisper
268
277
  transcription settings.
269
278
  - `approvals: { adminChatId, timeoutMs, gatedTools, ... }` — which tool
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The per-chat override walk, in one place.
3
+ *
4
+ * Every boolean feature flag in polygram resolves the same way — topic, then
5
+ * chat, then the active bot, then defaults, first explicit boolean wins — and
6
+ * each one had grown its own copy of the walk. A copy that drifts (an `||`
7
+ * where an `??` belongs, a missing tier) silently changes who has a feature on.
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const { getTopicConfig } = require('./session-key');
13
+
14
+ /**
15
+ * @param {?object} config — the runtime config (config.bot is already the active bot)
16
+ * @param {string} key — the flag's config key, e.g. 'richText'
17
+ * @param {string|number} chatId
18
+ * @param {?string|number} [threadId]
19
+ * @returns {boolean} true only if some tier explicitly says true
20
+ */
21
+ function resolveBoolOverride(config, key, chatId, threadId = null) {
22
+ if (!config) return false;
23
+ const chat = config.chats?.[String(chatId)] || null;
24
+ const topicCfg = (chat && threadId != null) ? getTopicConfig(chat, String(threadId)) : null;
25
+ const pick = (v) => (typeof v === 'boolean' ? v : undefined);
26
+ const resolved = pick(topicCfg?.[key])
27
+ ?? pick(chat?.[key])
28
+ ?? pick(config.bot?.[key])
29
+ ?? pick(config.defaults?.[key]);
30
+ return resolved === true;
31
+ }
32
+
33
+ module.exports = { resolveBoolOverride };
package/lib/db.js CHANGED
@@ -204,6 +204,15 @@ function wrap(db) {
204
204
  WHERE id = @id
205
205
  `);
206
206
 
207
+ // A streamed reply's row is written by the INITIAL send — the first ~30
208
+ // characters of the answer. Every later edit goes straight to Telegram and
209
+ // never revisits the row, so the transcript kept a torso where the chat shows
210
+ // the whole answer. This brings the row up to the finalized body.
211
+ const updateOutboundTextStmt = db.prepare(`
212
+ UPDATE messages SET text = @text, edited_ts = @ts
213
+ WHERE chat_id = @chat_id AND msg_id = @msg_id AND direction = 'out'
214
+ `);
215
+
207
216
  const upsertSessionStmt = db.prepare(`
208
217
  INSERT INTO sessions (
209
218
  session_key, chat_id, thread_id, claude_session_id,
@@ -3613,6 +3622,16 @@ function wrap(db) {
3613
3622
  return markOutboundFailedStmt.run({ id, error: String(err).slice(0, 500) });
3614
3623
  },
3615
3624
 
3625
+ updateOutboundText({ chat_id, msg_id, text, ts }) {
3626
+ if (chat_id == null || msg_id == null || typeof text !== 'string') return { changes: 0 };
3627
+ return updateOutboundTextStmt.run({
3628
+ chat_id: String(chat_id),
3629
+ msg_id: Number(msg_id),
3630
+ text,
3631
+ ts: ts || Date.now(),
3632
+ });
3633
+ },
3634
+
3616
3635
  upsertSession(row) {
3617
3636
  return upsertLegacyAndProviderSession(row);
3618
3637
  },
package/lib/error/net.js CHANGED
@@ -160,7 +160,12 @@ function redactBotToken(s) {
160
160
  // roots may contain userinfo, which must be stripped before logging.
161
161
  function stripUrlCredentials(url) {
162
162
  if (!url) return url;
163
- return String(url).replace(/^(https?:\/\/)[^/@\s]+@/i, '$1');
163
+ // The userinfo span runs to the LAST '@' before the path, not the first.
164
+ // A password containing an unencoded '@' ("alice:p@ss@host") would
165
+ // otherwise be cut at the first one, leaving the rest of the password
166
+ // visible in whatever this was being sanitized for. The class still
167
+ // excludes '/' and whitespace, so the match cannot run past the authority.
168
+ return String(url).replace(/^(https?:\/\/)[^/\s]*@/i, '$1');
164
169
  }
165
170
 
166
171
  module.exports = {
@@ -97,6 +97,13 @@ 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
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. Injected rather
103
+ * than required: rich-media.js requires THIS module, so importing the rich modules from
104
+ * here would close a require cycle.
105
+ * @param {Function} [deps.projectFallbackText] — (text, {chatId, threadId}) → text;
106
+ * chat-level hygiene for the chunked path, applied independently of the rich strategy
100
107
  * @param {Function} [deps.logEvent] — (kind, detail) → void; piped into the helper for canned-reply-suppressed forensics
101
108
  * @param {object} [deps.logger=console]
102
109
  * @param {number} [deps.maxChunkLen=4000] — TG hard cap is 4096; leave headroom for HTML wrapping
@@ -111,6 +118,14 @@ function createChannelsToolDispatcher({
111
118
  parseResponse,
112
119
  sanitizeAssistantReply,
113
120
  processAndDeliverAgentText,
121
+ makeDeliverText = null,
122
+ // Network error shapes can embed the request URL, which carries the bot
123
+ // token. Injected so this module stays free of telegram-layer imports.
124
+ redactError = (s) => s,
125
+ // (text, {chatId, threadId}) → text. Chat-level text hygiene for whatever
126
+ // the chunked path ends up delivering. Separate from makeDeliverText on
127
+ // purpose: it must still apply when that strategy cannot be built or fails.
128
+ projectFallbackText = null,
114
129
  // 0.15: (secret, {chat_id, thread_id}) → { redacted } — wipes an agent-flagged
115
130
  // secret ([redact:<secret>]) from the stored inbound. Optional; omitted in
116
131
  // tests / legacy callers (the helper no-ops when undefined).
@@ -221,6 +236,34 @@ function createChannelsToolDispatcher({
221
236
  }
222
237
 
223
238
  try {
239
+ // Per-call delivery strategy: sessionCwd (and so the roots any media
240
+ // would be validated against) is known only here, never at construction
241
+ // time. Building it is optional in the strictest sense — if it fails,
242
+ // the reply must still go out by the path that has always worked, so a
243
+ // throw here degrades to no strategy rather than to a failed reply.
244
+ let deliverText = null;
245
+ if (typeof makeDeliverText === 'function') {
246
+ try {
247
+ deliverText = makeDeliverText({
248
+ sessionKey, sessionCwd: call.sessionCwd || null, chatId, threadId,
249
+ // A status update, not the turn's answer: a strategy holding a live
250
+ // preview must not let an interim reply consume the bubble the real
251
+ // answer is still being written into.
252
+ interim: call.interim === true,
253
+ // The turn this reply names, so a strategy holding per-turn state
254
+ // can refuse a late reply from an earlier turn.
255
+ turnId: call.turnId ?? null,
256
+ });
257
+ } catch (err) {
258
+ logger.error?.(`[channels-tool-dispatcher] delivery strategy unavailable: ${err.message}`);
259
+ logEvent?.('deliver-strategy-error', {
260
+ chat_id: chatId, thread_id: threadId, session_key: sessionKey,
261
+ phase: 'factory',
262
+ error: redactError(String(err?.message || err)).slice(0, 200),
263
+ });
264
+ }
265
+ }
266
+
224
267
  // Review F#1: helper does parse → sanitize → chunk → deliver →
225
268
  // inline-sticker → reaction in one place. summary.deliverResult is
226
269
  // null if the post-parse text was empty (solo sticker/reaction).
@@ -230,6 +273,11 @@ function createChannelsToolDispatcher({
230
273
  tg: send,
231
274
  chatId,
232
275
  threadId,
276
+ deliverText,
277
+ redactError,
278
+ sanitizeFallbackText: typeof projectFallbackText === 'function'
279
+ ? (body) => projectFallbackText(body, { chatId, threadId })
280
+ : null,
233
281
  replyToMessageId: sourceMsgId || null,
234
282
  applyReactions: sourceMsgId != null,
235
283
  source: 'channels-tool-dispatcher',
@@ -340,6 +388,25 @@ function createChannelsToolDispatcher({
340
388
  }
341
389
  }
342
390
 
391
+ // Nothing survived projection, so no bubble was sent. Attachments are
392
+ // evaluated FIRST: a reply carrying files has delivered something even
393
+ // when its text projected away, and telling an agent to "use files:"
394
+ // when it just did is both wrong and unactionable.
395
+ if (summary.emptiedByStrategy) {
396
+ const attachedCount = (Array.isArray(files) ? files.length : 0) - failedAttachments.length;
397
+ if (attachedCount > 0) {
398
+ return { ok: true, message_id: null };
399
+ }
400
+ return {
401
+ ok: false,
402
+ error: Array.isArray(files) && files.length > 0
403
+ ? `reply contained no deliverable text and every attachment failed: ${
404
+ failedAttachments.map(f => `${f.path} (${f.error})`).join('; ')}`
405
+ : 'reply contained no deliverable text — send the answer as text, '
406
+ + 'or attach the file via files:',
407
+ };
408
+ }
409
+
343
410
  // R9: surface file-attach failures so Claude knows what didn't land.
344
411
  if (failedAttachments.length > 0) {
345
412
  return {
@@ -170,9 +170,15 @@ function createBuildSdkOptions({
170
170
  // Resolve the authoring hint through the same topic→chat→bot→default
171
171
  // precedence as delivery. The hint is fixed at spawn, while delivery
172
172
  // reads the value live for each send.
173
+ // inlineMedia: replies on this path are delivered by the streamer, which
174
+ // resolves and uploads local media into the rich payload. The reply-tool
175
+ // path cannot, so it asks for the hint without those paragraphs.
173
176
  composed.systemPrompt = appendDisplayHint(
174
177
  composed.systemPrompt,
175
- buildPolygramDisplayHint(resolveRichTextEnabled(config, chatId, threadId)),
178
+ buildPolygramDisplayHint(
179
+ resolveRichTextEnabled(config, chatId, threadId),
180
+ { inlineMedia: true },
181
+ ),
176
182
  );
177
183
  return composed;
178
184
  };
@@ -176,7 +176,32 @@ function createSdkCallbacks({
176
176
  // is actively emitting events for.
177
177
  const head = entry.pendingQueue?.[0];
178
178
  const s = head?.context?.streamer;
179
- if (s) s.onChunk(normalized).catch(() => {});
179
+ if (s) {
180
+ // A finalized streamer silently swallows further chunks. That is the
181
+ // right behavior — the bubble is settled — but from the outside it
182
+ // looks like "streaming just stopped", so make it diagnosable. ONCE per
183
+ // streamer: the events table has no retention, and a chatty turn that
184
+ // keeps streaming past finalize would write a row per chunk to say the
185
+ // same thing.
186
+ if (s.state === 'finalized' && !head._streamAfterFinalizeLogged) {
187
+ head._streamAfterFinalizeLogged = true;
188
+ logEvent('stream-after-finalize', {
189
+ chat_id: entry?.chatId ?? getChatIdFromKey(sessionKey),
190
+ session_key: sessionKey,
191
+ bot: botName,
192
+ });
193
+ }
194
+ // Same canned-string safety net the delivered reply gets. A CLI-context
195
+ // leak like "No response requested." must not render live in the
196
+ // preview bubble either. (Inline [sticker:]/[react:]/[redact:] markers,
197
+ // including a still-incomplete trailing one, are already stripped by
198
+ // the streamer's own transformText.)
199
+ const clean = (typeof normalized === 'string'
200
+ && typeof sanitizeAssistantReply === 'function')
201
+ ? sanitizeAssistantReply(normalized).text
202
+ : normalized;
203
+ s.onChunk(clean).catch(() => {});
204
+ }
180
205
  // Heartbeat the reactor so long text generation doesn't trip
181
206
  // the 10s STALL → 🥱 / 30s TIMEOUT → 😨 promotion.
182
207
  const r = head?.context?.reactor;
@@ -90,11 +90,18 @@ function nextPendingId() {
90
90
  // the UNIQUE(chat_id, msg_id) constraint on the 2nd edit — the stream
91
91
  // edits one bubble N times in a single turn. The initial sendMessage
92
92
  // already persisted the row; edits just update the live bubble.
93
+ //
94
+ // sendRichMessage is untracked for a different reason: it is a *try*. Any
95
+ // failure degrades to the plain chunked path, which inserts its own rows —
96
+ // so a tracked row here would persist the failed attempt alongside the
97
+ // successful fallback and the agent's preloaded history would show the
98
+ // same answer twice. The rich sender inserts one row itself, on success only.
93
99
  const METHODS_WITHOUT_MSG = new Set([
94
100
  'setMessageReaction',
95
101
  'deleteMessage',
96
102
  'editMessageReplyMarkup',
97
103
  'editMessageText',
104
+ 'sendRichMessage',
98
105
  ]);
99
106
 
100
107
  // Derive the row's `text` column. sendSticker has no text/caption, so we
@@ -158,17 +165,34 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
158
165
  // as a user-facing "Hit a snag" — confusing because the bot didn't
159
166
  // really fail. Throw a typed error before the API call so callers
160
167
  // can detect + skip silently if appropriate.
161
- // A rich edit carries `rich_message` instead of `text`, so validate
162
- // its block collection rather than applying the plain-text guard.
168
+ // Validate any rich payload by its PRESENCE, not by the method carrying
169
+ // it. Keyed on the verb, this guard would wave through the same payload
170
+ // under any other method name — which is what a new caller looks like.
171
+ if (params.rich_message != null) {
172
+ const rich = params.rich_message;
173
+ if (!Array.isArray(rich.blocks) || rich.blocks.length === 0) {
174
+ throw new Error(`telegram ${method}: rich_message.blocks is empty`);
175
+ }
176
+ // Typed blocks are the only rich payload polygram emits. The `html` and
177
+ // `markdown` alternatives would hand Telegram a string it re-parses,
178
+ // reintroducing the markup-injection surface the block renderer exists
179
+ // to close — and nothing downstream sanitizes them.
180
+ if (rich.html != null || rich.markdown != null) {
181
+ throw new Error(
182
+ `telegram ${method}: rich_message.html/markdown is not supported — send typed blocks`,
183
+ );
184
+ }
185
+ } else if (method === 'sendRichMessage') {
186
+ throw new Error(`telegram ${method}: rich_message is missing`);
187
+ }
188
+
189
+ // A rich send/edit carries `rich_message` instead of `text`, so the
190
+ // plain-text guard applies only when there is no rich payload.
163
191
  if (method === 'sendMessage' || (method === 'editMessageText' && params.rich_message == null)) {
164
192
  const t = params.text;
165
193
  if (typeof t !== 'string' || t.length === 0) {
166
194
  throw new Error(`telegram ${method}: text is empty`);
167
195
  }
168
- } else if (method === 'editMessageText' && params.rich_message != null) {
169
- if (!Array.isArray(params.rich_message.blocks) || params.rich_message.blocks.length === 0) {
170
- throw new Error(`telegram ${method}: rich_message.blocks is empty`);
171
- }
172
196
  }
173
197
  if (method === 'sendPhoto' || method === 'sendVideo'
174
198
  || method === 'sendAudio' || method === 'sendDocument' || method === 'sendAnimation') {
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Chaining `deliverText` strategies.
3
+ *
4
+ * Two features now want the pipeline's text-delivery step — the live preview
5
+ * (a reply consumes the bubble the answer was streaming into) and rich
6
+ * rendering (a reply with structure goes out as blocks). They are independent
7
+ * decisions about the same reply, and neither may switch the other off, so the
8
+ * seam takes an ordered chain rather than one strategy.
9
+ *
10
+ * The order is meaningful, not arbitrary: the preview strategy runs first
11
+ * because only it knows whether a bubble is already on screen holding this
12
+ * answer. When it consumes, the reply is delivered and nothing downstream
13
+ * should run. When it declines, whatever it did NOT deliver flows on to the
14
+ * next strategy, and finally to the pipeline's own chunked path.
15
+ *
16
+ * A declining strategy may hand the next one a rewritten body (the rich
17
+ * strategy uses this to strip media markdown from a fallback), and the rewrite
18
+ * carries through to the chunked path.
19
+ */
20
+
21
+ 'use strict';
22
+
23
+ /**
24
+ * @param {Array<?Function>} factories — makeDeliverText factories, in the order
25
+ * they should get first refusal. Nullish entries are ignored.
26
+ * @returns {Function} a makeDeliverText factory, or one returning null when no
27
+ * member built a strategy for this call.
28
+ */
29
+ function composeDeliverTextFactories(factories) {
30
+ const built = (factories || []).filter((f) => typeof f === 'function');
31
+ if (built.length === 0) return null;
32
+
33
+ return function makeDeliverText(args) {
34
+ const strategies = built
35
+ .map((factory) => factory(args))
36
+ .filter((s) => typeof s === 'function');
37
+ if (strategies.length === 0) return null;
38
+
39
+ return async function deliverText(callArgs) {
40
+ let text = callArgs.text;
41
+ for (const strategy of strategies) {
42
+ const out = await strategy({ ...callArgs, text });
43
+ if (out?.handled) return out;
44
+ // A decline may still have projected the body for whoever delivers it.
45
+ if (typeof out?.text === 'string') text = out.text;
46
+ }
47
+ return { handled: false, text };
48
+ };
49
+ };
50
+ }
51
+
52
+ module.exports = { composeDeliverTextFactories };
@@ -58,9 +58,22 @@ 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. The
62
+ // streamer renders inline media today; the reply tool renders rich text on
63
+ // media-stripped input, so there an image reaches the user as its caption and
64
+ // nothing else. Teaching syntax the delivering path discards makes the agent
65
+ // author constructs that silently vanish, so each caller states what its own
66
+ // path can do.
67
+ const INLINE_MEDIA_PARAGRAPHS = [
68
+ '**Inline media:** use the unchanged `![caption](/abs/path/to/file.ext)` 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
+ '',
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
+ '',
72
+ ];
73
+
61
74
  // Rich-mode guidance is limited to the constructs detected by
62
75
  // needsRichRendering so ordinary prose stays on the compact plain path.
63
- const TABLES_AND_HEADERS_SECTION_RICH = [
76
+ const richSection = (inlineMedia) => [
64
77
  '### Rich formatting is available in this chat',
65
78
  '',
66
79
  'This chat has rich-text rendering enabled. Real Telegram markdown tables, headings (`#`/`##`/etc.), task lists, collapsible `<details>` blocks, blockquotes (`>`), and dividers (`---`) now render as an actual structured message, not flattened text. No character-width budget applies to tables here; write a normal markdown table.',
@@ -95,10 +108,7 @@ const TABLES_AND_HEADERS_SECTION_RICH = [
95
108
  '',
96
109
  '**Collapsible detail:** wrap verbose logs/diffs/output you want available but not front-and-center in `<details><summary>Label</summary>...</details>`.',
97
110
  '',
98
- '**Inline media:** use the unchanged `![caption](/abs/path/to/file.ext)` 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.',
99
- '',
100
- '**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.',
101
- '',
111
+ ...(inlineMedia ? INLINE_MEDIA_PARAGRAPHS : []),
102
112
  'Not every reply needs this — plain prose is still right for a normal conversational answer with no distinct items or sections. Reach for structure when the CONTENT is structured, not by default.',
103
113
  '',
104
114
  '### Other Telegram quirks',
@@ -107,8 +117,15 @@ const TABLES_AND_HEADERS_SECTION_RICH = [
107
117
  '- Long replies stream in chunks; prefer concise structure over walls of text.',
108
118
  ].join('\n');
109
119
 
110
- function buildPolygramDisplayHint(richText = false) {
111
- const tablesSection = richText ? TABLES_AND_HEADERS_SECTION_RICH : TABLES_AND_HEADERS_SECTION_PLAIN;
120
+ /**
121
+ * @param {boolean} [richText] — whether this chat renders typed rich blocks
122
+ * @param {object} [opts]
123
+ * @param {boolean} [opts.inlineMedia] — whether the path that will DELIVER
124
+ * this chat's replies renders inline media. Off by default: promising media
125
+ * a path cannot deliver is the failure mode worth defaulting away from.
126
+ */
127
+ function buildPolygramDisplayHint(richText = false, { inlineMedia = false } = {}) {
128
+ const tablesSection = richText ? richSection(inlineMedia) : TABLES_AND_HEADERS_SECTION_PLAIN;
112
129
  return [
113
130
  '## Telegram display rules',
114
131
  '',