polygram 0.47.1 → 0.48.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.47.1",
4
+ "version": "0.48.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",
package/README.md CHANGED
@@ -326,11 +326,17 @@ await tell('admin-bot', 'sendMessage', {
326
326
  }, { source: 'cron:inventory-report' });
327
327
  ```
328
328
 
329
- Allowed methods: `sendMessage`, `sendPhoto`, `sendDocument`, `sendSticker`,
329
+ Allowed methods: `sendMessage`, `sendRichMessage`, `sendPhoto`, `sendDocument`, `sendSticker`,
330
330
  `sendChatAction`, `editMessageText`, `setMessageReaction`. The socket
331
331
  server rejects others. Cross-bot sends are rejected (chat must belong
332
332
  to the bot on the other end of the socket).
333
333
 
334
+ Rich cards use the authenticated `send` request with typed `rich_message.blocks`
335
+ and optional top-level `fallback: {text, parse_mode: "HTML"}`. The response is
336
+ `{ok: true, result: Message, rich: true|false}`; rich failure without a fallback
337
+ is an error. Both transports keep the same chat/topic. See the
338
+ [rich cards interface and examples](docs/RICH_MAILBOX_CARDS_SPEC.md).
339
+
334
340
  If the bot process is down, the call throws. This is intentional — cron
335
341
  failures should surface.
336
342
 
package/docs/MAILBOX.md CHANGED
@@ -47,7 +47,7 @@ rules.
47
47
  | `enabled` | Must be `true`. Without a `mailbox` key nothing changes. |
48
48
  | `roles.<name>` | Role name = route id, `^[a-z][a-z0-9_-]*$`. `about` (≤ 300 characters) is shown to the roles allowed to message it. |
49
49
  | `allow.<name>` | Roles this role may start an `ask` or `tell` to; `"*"` means every role. A role without an entry can only reply. Replies are never checked against it. |
50
- | `mirror` | Where each message is posted as plain text: `"target"` (or `true`) posts it into the target role's topic; `"both"` also posts a sender line into the sending role's topic; `false` posts nothing. Default `true`. See [Telegram mirror](#telegram-mirror). |
50
+ | `mirror` | Where each message is posted: `"target"` (or `true`) posts a collapsed rich card into the target role's topic; `"both"` also posts the same card into the sending role's topic; `false` posts nothing. Default `true`. See [Telegram mirror](#telegram-mirror). |
51
51
  | `systemSenders` | Names of processes outside any session that may send through `mailbox_submit` as `system:<name>` (see [System senders](#system-senders)). Distinct names, `^[a-z][a-z0-9_-]*$`; `polygram` is reserved. Default none. |
52
52
  | `limits.maxDepth` | Longest chain. A human message starts at depth 0, as does a system tell that relays a human's words (see [Relayed human messages](#relayed-human-messages)); any other system tell is depth 1, and each new message is one deeper. Default 2. |
53
53
  | `limits.perPairPerHour` | Asks and tells per (from, to) pair in the last hour. Default 10. |
@@ -103,26 +103,44 @@ text lands in its own topic through the normal job report.
103
103
 
104
104
  ## Telegram mirror
105
105
 
106
- Each message is posted once, right after it commits, never from the
107
- dispatch path. The target role's topic gets the whole redacted body:
106
+ Each message is posted once, right after it commits, never from the dispatch
107
+ path. The target role's topic gets one rich blockquote with a header and a closed
108
+ `details` block:
108
109
 
109
110
  ```
110
- 📨 role:orchestrator → role:marketing (ask m_…)
111
- <body>
111
+ ❓ Question · orchestrator → marketing
112
+ ▸ What is the Q3 budget?
112
113
  ```
113
114
 
114
- With `"mirror": "both"`, the sending role's topic also gets a sender line,
115
- so a role's chat shows what it sent. It carries the first 300 characters of
116
- the redacted body, with `…` when the body is longer:
117
-
118
- ```
119
- 📤 role:orchestrator → role:marketing (ask m_…)
120
- <first 300 characters of the body>
115
+ The event word is bold: `📨 Message`, `❓ Question`, or `↩️ Answer`. Addresses
116
+ have no `role:`/`system:` prefixes or transport ids. A relayed human's stored name
117
+ adds `· from Ivan`. Expanding details reveals the complete stored, redacted body
118
+ literally, including any technical instructions. With `"mirror": "both"`, the
119
+ sender topic gets the same card; a system sender has no sender topic.
120
+
121
+ `mailbox_send` and `mailbox_submit` accept optional `summary`: one nonblank line
122
+ of at most 120 Unicode code points, without controls or line separators. It is
123
+ redacted, stored in `mailbox_messages.summary`, and used only for the collapsed
124
+ line, never the receiving role's prompt. Without it, the first nonempty body
125
+ line is shortened to 80 code points. Replies derive their summary from the body.
126
+ A role send's duplicate identity includes its supplied summary; a system retry
127
+ with a different summary under the same key conflicts. Absent summaries retain
128
+ legacy hashes. Identical retries return the original receipt without posting.
129
+
130
+ Rich sends use the shared capability latch. Unsupported or rejected rich cards
131
+ fall back once to the previous HTML target card, in the exact same topic:
132
+
133
+ ```html
134
+ ❓ <b>orchestrator asks marketing</b>
135
+ <blockquote expandable>What is the Q3 budget?</blockquote>
121
136
  ```
122
137
 
123
- Only a `role:` sender has a topic, so a system sender's message gets the
124
- target line only. A failed post is logged and never blocks delivery or the
125
- other post. Duplicates and refused messages are not posted.
138
+ The HTML fallback escapes all text, disables link previews, and fits 4096 parsed
139
+ UTF-16 units, cutting whole code points with `…` when necessary. It is also the
140
+ sender topic's fallback. Rich details were verified on the VPS Bot API 10.2;
141
+ HTML expandable blockquotes require Bot API 7.3+. A failed post is logged and
142
+ never blocks delivery or the other post. Duplicates and refusals are not posted.
143
+ Agent-org tells remain mirrored when mirroring is enabled.
126
144
 
127
145
  ## System senders
128
146
 
@@ -140,14 +158,14 @@ to the IPC socket with the bot's secret, like any other IPC client.
140
158
  - `key` (1 to 256 bytes) is the caller's idempotency key. It is looked up
141
159
  first, per sender. A hit returns the stored message's receipt with its real
142
160
  delivery state and `duplicate: true`. A hit whose `to`, redacted body or
143
- `origin` differs is refused with `MAILBOX_KEY_CONFLICT`; a different `ref`
161
+ `origin` or `summary` differs is refused with `MAILBOX_KEY_CONFLICT`; a different `ref`
144
162
  does not conflict.
145
163
  - There is no ten-minute duplicate window; the key replaces it.
146
164
  - `limits.systemPerHour` applies per sender, counted only after the key
147
165
  lookup, so a retry of an accepted message is never rate limited. System
148
166
  sends don't use up a role pair's budget.
149
167
  - The size cap, redaction and target mirror apply as for agent messages.
150
- A system sender has no topic, so it never gets a sender line.
168
+ A system sender has no topic, so it never gets a sender card.
151
169
  - `ref` (optional, 1 to 512 bytes) is an opaque reference such as a task id
152
170
  or URL. It is redacted, stored, and shown to the receiver only inside the
153
171
  untrusted payload, never in the trusted header.
@@ -209,7 +227,7 @@ agent-org runner relaying a person's Notion comment, adds an `origin`:
209
227
  with the same key and a different name, or with the origin added or
210
228
  dropped, is `MAILBOX_KEY_CONFLICT`, so a message accepted at depth 1 can't
211
229
  be upgraded to depth 0 by a retry.
212
- - The mirror line is the same as for any system message.
230
+ - The target mirror header includes `· from <name>`, using the stored redacted name.
213
231
 
214
232
  ## Error codes
215
233
 
@@ -224,7 +242,7 @@ contract and do not change:
224
242
  | `MAILBOX_UNKNOWN_ROLE` | `to` is not a configured role. | No. |
225
243
  | `MAILBOX_TOO_LARGE` | The body is over `maxBodyBytes`, before or after redaction. | No. |
226
244
  | `MAILBOX_RATE_LIMITED` | `systemPerHour`, or the per-pair limit for agent sends. | Yes, later. |
227
- | `MAILBOX_KEY_CONFLICT` | The key was used for a different target, body or origin. | No. |
245
+ | `MAILBOX_KEY_CONFLICT` | The key was used for a different target, body, origin or summary. | No. |
228
246
  | `MAILBOX_INVALID_ORIGIN` | `origin` is not exactly `{kind:"human", name}` with a name of 1 to 64 characters and no control characters. | No. |
229
247
 
230
248
  A refusal from the external-jobs queue keeps its own code, for example
@@ -250,8 +268,20 @@ with backoff from 1 to 30 minutes while the session is paused or busy.
250
268
  ## Human control
251
269
 
252
270
  - `/automation pause|resume` from the operator in a role's topic pauses or
253
- resumes delivery into that role. The operator's `/stop` also pauses. A pause
271
+ resumes delivery into that role. A stop phrase or `/stop` only interrupts
272
+ the current turn; it never creates or clears a pause. A pause
254
273
  holds that topic's job reports too.
274
+ - After a stop, the interrupted job is not retried. Once stopping finishes
275
+ and the session is proven idle, the next queued job may start immediately.
276
+ Active stops keep the 👍 reaction; idle stops stay silent. No pause notice
277
+ is posted. `/automation status` reports the actual pause and job counts;
278
+ `enabled` does not guarantee that inactivity has been proven. If a stopped
279
+ process was destroyed, queued work waits for a recovered process's idle
280
+ proof; the unknown-job recovery poller does not recover `interrupted` jobs.
281
+ - Mailbox roles are identified by their resolved session, including General.
282
+ A non-mailbox route sharing a role session follows the same interrupt-only
283
+ stop policy. Dedicated infrastructure and recorded-notification destinations
284
+ retain durable pause-on-stop. A disabled mailbox retains that default too.
255
285
  - `mailbox.enabled: false` (then restart) stops all delivery. Queued mailbox
256
286
  jobs are withdrawn unsent as `failed` with error `withdrawn`, and the role's
257
287
  other jobs keep flowing.
@@ -264,7 +294,7 @@ Messages live in `mailbox_messages`; delivery state lives in `external_jobs`
264
294
  under `request_id = 'mailbox:' || id` (notices: `'mailbox-notice:' || askId`,
265
295
  or `|| replyId` for a reply that was not delivered). System messages also
266
296
  store their `idem_key` and `ref`, and a relayed human message its
267
- `origin_name`.
297
+ `origin_name`; optional collapsed headings live in `summary`.
268
298
 
269
299
  ```sql
270
300
  SELECT m.id, m.kind, m.from_addr, m.to_addr, m.depth, m.notice_sent, j.state, j.report_state, j.error
@@ -71,7 +71,9 @@ admission deferrals (busy session, recovery, authentication or spawn) retain the
71
71
  same queued identity and use the existing 60-second polling without another LLM
72
72
  execution. This change adds no exhaustion policy to that existing queue. Existing
73
73
  recovery, pause and definitely-unsent report retry rules remain authoritative. `/automation status` includes unread, active processing,
74
- last execution/report and due-check counts. Human stop durably pauses automation.
74
+ last execution/report and due-check counts. Human stop durably pauses automation
75
+ in non-mailbox destinations. If a consumer aliases an enabled mailbox role
76
+ session, that session's stop only interrupts; use `/automation pause` to pause it.
75
77
 
76
78
  Every human turn, including a resumed or paused session, receives bounded unread
77
79
  source context. A reply to a processed notification also receives that exact
package/lib/db.js CHANGED
@@ -94,7 +94,7 @@ const durableJson = (value) => {
94
94
  //
95
95
  // 0.15: bumped 13 → 14. Adds migration 014-secret-redactions.sql
96
96
  // (secret_redactions audit table + messages.secret_scanned_at).
97
- const SCHEMA_VERSION = 26;
97
+ const SCHEMA_VERSION = 27;
98
98
 
99
99
  // Sentinel `error` value for outbound rows whose API call may or may not
100
100
  // have reached Telegram. markStalePending writes it; hasOutboundReplyTo
@@ -127,7 +127,7 @@ function createExternalJobRuntime({
127
127
  const inactive = await checkInactive(job);
128
128
  if (result?.sendError) return { outcome: 'unknown', turnId, inactive, error: result.sendError.message || 'Turn receipt is unavailable' };
129
129
  return {
130
- outcome: result?.aborted ? 'interrupted' : result?.error ? 'failed' : result ? 'succeeded' : 'unknown',
130
+ outcome: result?.aborted || result?.metrics?.resultSubtype === 'interrupted' ? 'interrupted' : result?.error ? 'failed' : result ? 'succeeded' : 'unknown',
131
131
  turnId, inactive,
132
132
  text: typeof result?.text === 'string' ? result.text : '',
133
133
  channelsAcknowledged: result?.alreadyDelivered === true,
@@ -74,6 +74,7 @@ function createHandleAbort({
74
74
  // the question store.
75
75
  retireQuestionSession = null,
76
76
  pauseAutomation = null,
77
+ holdAutomationAdmission = null,
77
78
  getSessionKey,
78
79
  botName,
79
80
  // Cancel-cheap (spec Finding 5): delay before the second background-shell
@@ -87,6 +88,12 @@ function createHandleAbort({
87
88
 
88
89
  const threadId = msg.message_thread_id?.toString();
89
90
  const sessionKey = getSessionKey(chatId, threadId, chatConfig);
91
+ const release = await holdAutomationAdmission?.(sessionKey);
92
+ try { return await stopSession(msg, chatId, threadId, sessionKey, cleanText); }
93
+ finally { release?.(); }
94
+ };
95
+
96
+ async function stopSession(msg, chatId, threadId, sessionKey, cleanText) {
90
97
  let automationPauseFailed = false;
91
98
  try { await pauseAutomation?.({ msg, chatId, threadId, sessionKey }); }
92
99
  catch {
@@ -381,7 +388,7 @@ function createHandleAbort({
381
388
  }
382
389
  await reportPauseFailure();
383
390
  return true;
384
- };
391
+ }
385
392
  }
386
393
 
387
394
  module.exports = { createHandleAbort };
@@ -18,12 +18,14 @@
18
18
  'use strict';
19
19
 
20
20
  const { validateIpcFileParam } = require('../ipc/file-validator');
21
+ const { sendRichCard } = require('../telegram/rich-card-send');
21
22
 
22
23
  // Allowed Telegram Bot API methods. Broader than sendMessage to
23
24
  // cover receipts, error reports, quick replies. Deliberately
24
25
  // excludes destructive ops.
25
26
  const IPC_SEND_ALLOWED_METHODS = new Set([
26
27
  'sendMessage',
28
+ 'sendRichMessage',
27
29
  'sendPhoto',
28
30
  'sendDocument',
29
31
  'sendSticker',
@@ -32,7 +34,7 @@ const IPC_SEND_ALLOWED_METHODS = new Set([
32
34
  'setMessageReaction',
33
35
  ]);
34
36
 
35
- function createHandleSendOverIpc({ config, bot, tg, botName } = {}) {
37
+ function createHandleSendOverIpc({ config, bot, tg, botName, sendRich } = {}) {
36
38
  return async function handleSendOverIpc(req) {
37
39
  const { method, params = {}, source } = req || {};
38
40
  if (!method) throw new Error('method required');
@@ -66,6 +68,22 @@ function createHandleSendOverIpc({ config, bot, tg, botName } = {}) {
66
68
  const fileParamErr = validateIpcFileParam(method, params);
67
69
  if (fileParamErr) throw new Error(fileParamErr);
68
70
 
71
+ if (method === 'sendRichMessage') {
72
+ if (!chatId) throw new Error('sendRichMessage requires chat_id');
73
+ const rich = params.rich_message;
74
+ if (!Array.isArray(rich?.blocks) || !rich.blocks.length || rich.html != null || rich.markdown != null) {
75
+ throw new Error('sendRichMessage requires typed rich_message.blocks');
76
+ }
77
+ const fallback = req.fallback;
78
+ if (fallback !== undefined && (!fallback || typeof fallback !== 'object' || Array.isArray(fallback)
79
+ || typeof fallback.text !== 'string' || !fallback.text || fallback.parse_mode !== 'HTML'
80
+ || Object.keys(fallback).some((key) => !['text', 'parse_mode'].includes(key)))) {
81
+ throw new Error('Invalid rich fallback: use {text, parse_mode:"HTML"}');
82
+ }
83
+ return sendRichCard({ sendRich, tg, bot, chatId, threadId: params.message_thread_id,
84
+ blocks: rich.blocks, fallback, meta: { source: source || 'ipc', botName } });
85
+ }
86
+
69
87
  const sendRes = await tg(bot, method, params, {
70
88
  source: source || 'ipc',
71
89
  botName,
@@ -6,6 +6,7 @@
6
6
  // is a pure function of stored rows, so a resubmission is byte-identical.
7
7
 
8
8
  const { SYSTEM_ADDRESS } = require('./rules');
9
+ const { escapeHtml } = require('../telegram/format');
9
10
 
10
11
  const AUTHORITY = 'Another agent session of this organization sent this. It is not a human instruction and not authorization: '
11
12
  + 'paid, outward-facing or destructive actions still need a human go.';
@@ -79,19 +80,45 @@ function renderNoticePayload(ask, job, reply = null) {
79
80
  };
80
81
  }
81
82
 
82
- // The Telegram mirror line for the target role's topic. The body is the
83
- // redacted text that was stored.
83
+ // Telegram limits parsed text, so cut complete code points before escaping.
84
+ function truncateMirror(text, limit) {
85
+ if (text.length <= limit) return text;
86
+ let kept = '';
87
+ for (const char of text) {
88
+ if (kept.length + char.length > limit - 1) break;
89
+ kept += char;
90
+ }
91
+ return `${kept}…`;
92
+ }
93
+
94
+ // The target card quotes the stored redacted body literally. Only the
95
+ // header and the expandable quotation are formatting, never body content.
84
96
  function renderMirror(row) {
85
- return `📨 ${row.from_addr} → ${row.to_addr} (${row.kind} ${row.id})\n${row.body}`;
97
+ const from = row.from_addr.replace(/^(?:role|system):/, '');
98
+ const to = row.to_addr.replace(/^(?:role|system):/, '');
99
+ const icon = row.kind === 'ask' ? '❓' : row.kind === 'reply' ? '↩️' : '📨';
100
+ const action = row.kind === 'ask' ? 'asks' : row.kind === 'reply' ? 'answered' : '→';
101
+ const origin = row.origin_name == null ? '' : ` · from ${row.origin_name}`;
102
+ const header = truncateMirror(`${from} ${action} ${to}${origin}`, 512 - icon.length - 1);
103
+ const body = truncateMirror(row.body, 4096 - icon.length - header.length - 2);
104
+ return `${icon} <b>${escapeHtml(header)}</b>\n<blockquote expandable>${escapeHtml(body)}</blockquote>`;
86
105
  }
87
106
 
88
- // The line for the sending role's own topic, so that topic shows what the
89
- // role sent. The body is cut by code points so no character is split.
90
- const SENDER_MIRROR_CHARS = 300;
91
- function renderSenderMirror(row) {
92
- const chars = Array.from(row.body);
93
- const body = chars.length > SENDER_MIRROR_CHARS ? `${chars.slice(0, SENDER_MIRROR_CHARS).join('')}…` : row.body;
94
- return `📤 ${row.from_addr} → ${row.to_addr} (${row.kind} ${row.id})\n${body}`;
107
+ // Typed rich text keeps the stored body literal; only details controls its
108
+ // collapsed appearance. Sender and target topics get the same card.
109
+ function renderRichMirror(row) {
110
+ const from = row.from_addr.replace(/^(?:role|system):/, '');
111
+ const to = row.to_addr.replace(/^(?:role|system):/, '');
112
+ const [icon, event] = row.kind === 'ask' ? ['❓', 'Question'] : row.kind === 'reply' ? ['↩️', 'Answer'] : ['📨', 'Message'];
113
+ const origin = row.origin_name == null ? '' : ` · from ${row.origin_name}`;
114
+ const context = truncateMirror(` · ${from} → ${to}${origin}`, 512 - icon.length - event.length - 1);
115
+ const firstLine = row.body.split(/[\r\n\u2028\u2029]/u).find((line) => line.trim())?.trim() || 'Message';
116
+ const chars = Array.from(firstLine);
117
+ const summary = row.summary ?? (chars.length > 80 ? `${chars.slice(0, 79).join('')}…` : firstLine);
118
+ return [{ type: 'blockquote', blocks: [
119
+ { type: 'paragraph', text: [`${icon} `, { type: 'bold', text: event }, context] },
120
+ { type: 'details', summary, is_open: false, blocks: [{ type: 'paragraph', text: row.body }] },
121
+ ] }];
95
122
  }
96
123
 
97
- module.exports = { renderTask, renderPayload, renderNoticeTask, renderNoticePayload, renderMirror, renderSenderMirror };
124
+ module.exports = { renderTask, renderPayload, renderNoticeTask, renderNoticePayload, renderMirror, renderRichMirror };
@@ -20,6 +20,7 @@ const MAX_ABOUT = 300;
20
20
  const MAX_KEY_BYTES = 256;
21
21
  const MAX_REF_BYTES = 512;
22
22
  const MAX_ORIGIN_NAME = 64;
23
+ const MAX_SUMMARY = 120;
23
24
  const RATE_WINDOW_MS = 60 * 60 * 1000;
24
25
  const DUPLICATE_WINDOW_MS = 10 * 60 * 1000;
25
26
  const SYSTEM_ADDRESS = 'system:polygram';
@@ -170,6 +171,21 @@ const systemMessageHash = (body, originName) => (originName === null
170
171
  ? redactedBodyHash(body)
171
172
  : bodyHash(`origin\0${JSON.stringify({ body: redact(requireBody(body)), originName })}`));
172
173
 
174
+ function cleanSummary(summary) {
175
+ if (summary === undefined) return null;
176
+ const valid = (value) => typeof value === 'string' && value.trim()
177
+ && Array.from(value).length <= MAX_SUMMARY && !/[\p{Cc}\u2028\u2029]/u.test(value);
178
+ if (!valid(summary)) throw new Error(`Invalid summary: use one line of 1 to ${MAX_SUMMARY} characters without controls`);
179
+ const clean = redact(summary);
180
+ if (!valid(clean)) throw new Error(`Invalid redacted summary: exceeds ${MAX_SUMMARY} characters or is not one line`);
181
+ return clean;
182
+ }
183
+
184
+ // Preserve legacy hashes when the optional display metadata is absent.
185
+ const summaryMessageHash = (body, summary, originName = null) => (summary === null
186
+ ? systemMessageHash(body, originName)
187
+ : bodyHash(`summary\0${JSON.stringify({ body: redact(requireBody(body)), originName, summary })}`));
188
+
173
189
  function requireBody(body) {
174
190
  if (typeof body !== 'string' || !body.trim()) throw new Error('Message body required');
175
191
  return body;
@@ -199,6 +215,6 @@ function checkReply({ ask, caller, replied }) {
199
215
 
200
216
  module.exports = {
201
217
  readMailboxConfig, checkStart, nextDepth, checkRate, cleanBody, bodyHash, checkReply,
202
- checkSystemSender, checkSystemRate, checkKey, cleanRef, cleanOriginName, systemMessageHash, requireBody, redactedBodyHash,
218
+ checkSystemSender, checkSystemRate, checkKey, cleanRef, cleanOriginName, systemMessageHash, cleanSummary, summaryMessageHash, requireBody, redactedBodyHash,
203
219
  roleAddress, systemAddress, roleFromAddress, SYSTEM_ADDRESS, DEFAULT_LIMITS, RATE_WINDOW_MS, DUPLICATE_WINDOW_MS, REFUSAL, refusal,
204
220
  };
@@ -5,6 +5,7 @@ const { randomBytes, randomUUID } = require('node:crypto');
5
5
  const rules = require('./rules');
6
6
  const envelope = require('./envelope');
7
7
  const { createMailboxStore } = require('./store');
8
+ const { sendRichCard } = require('../telegram/rich-card-send');
8
9
 
9
10
  const SCRIPT = path.resolve(__dirname, '../../skills/mailbox/scripts/msg.js');
10
11
  const MAILBOX_REQUEST = 'mailbox:';
@@ -30,7 +31,7 @@ function checkFields(input, allowed) {
30
31
  // it because a CLI session inherits its environment from whoever started the
31
32
  // tmux server, which is often not the daemon; msg.js then finds the socket
32
33
  // and the 0600 secret file there.
33
- function createMailboxService({ config, db, botName, jobs, resolveTarget, bot = null, tg = null, ipcDir = null, now = Date.now, logger = console }) {
34
+ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot = null, tg = null, sendRich, ipcDir = null, now = Date.now, logger = console }) {
34
35
  const cfg = rules.readMailboxConfig(config.bot, resolveTarget);
35
36
  const raw = db?.raw;
36
37
  const store = cfg ? createMailboxStore(raw, { botName, now }) : null;
@@ -77,17 +78,18 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
77
78
  // topic as the job report. Only a role sender has a topic of its own.
78
79
  function mirror(row) {
79
80
  if (!cfg.mirror || !tg) return;
80
- post(cfg.roles.get(row.route_id)?.target, envelope.renderMirror(row), 'mailbox-mirror', `mirror of ${row.id}`);
81
+ post(cfg.roles.get(row.route_id)?.target, row, 'mailbox-mirror', `mirror of ${row.id}`);
81
82
  if (cfg.mirror === 'both') {
82
83
  const sender = rules.roleFromAddress(row.from_addr);
83
- post(sender ? cfg.roles.get(sender)?.target : null, envelope.renderSenderMirror(row), 'mailbox-sender-mirror', `sender mirror of ${row.id}`);
84
+ post(sender ? cfg.roles.get(sender)?.target : null, row, 'mailbox-sender-mirror', `sender mirror of ${row.id}`);
84
85
  }
85
86
  }
86
- function post(target, text, source, what) {
87
+ function post(target, row, source, what) {
87
88
  if (!target) return;
88
89
  Promise.resolve()
89
- .then(() => tg(bot, 'sendMessage', { chat_id: target.chatId, ...(target.threadId == null ? {} : { message_thread_id: target.threadId }), text },
90
- { source, botName, sessionKey: target.sessionKey, plainText: true, strictDestination: true }))
90
+ .then(() => sendRichCard({ sendRich, tg, bot, chatId: target.chatId, threadId: target.threadId,
91
+ blocks: envelope.renderRichMirror(row), fallback: { text: envelope.renderMirror(row), parse_mode: 'HTML' },
92
+ meta: { source, botName, sessionKey: target.sessionKey } }))
91
93
  // Telegram's description is API text, not message content.
92
94
  .catch((error) => logger.error?.(`[mailbox] ${what} failed: ${error?.error_code ?? error?.code ?? error?.name ?? 'Error'}${error?.description ? ` ${error.description}` : ''}`));
93
95
  }
@@ -159,6 +161,7 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
159
161
 
160
162
  const api = {
161
163
  enabled: cfg !== null,
164
+ roleForSession: roleOf,
162
165
  scope(sessionKey) {
163
166
  if (!roleOf(sessionKey)) return null;
164
167
  let token = tokenBySession.get(sessionKey);
@@ -196,10 +199,11 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
196
199
  send(token, input) {
197
200
  requireEnabled();
198
201
  const from = caller(token);
199
- checkFields(input, ['to', 'kind', 'body']);
202
+ checkFields(input, ['to', 'kind', 'body', 'summary']);
200
203
  rules.checkStart(cfg, { from: from.role, to: input.to, kind: input.kind });
201
204
  const body = rules.cleanBody(input.body, cfg.limits.maxBodyBytes);
202
- const hash = rules.bodyHash(body);
205
+ const summary = rules.cleanSummary(input.summary);
206
+ const hash = rules.summaryMessageHash(body, summary);
203
207
  const fromAddr = rules.roleAddress(from.role);
204
208
  const toAddr = rules.roleAddress(input.to);
205
209
  const { result, row } = transaction(() => {
@@ -207,7 +211,7 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
207
211
  if (duplicate) return { result: receipt(duplicate, { duplicate: true }) };
208
212
  const depth = rules.nextDepth(from.depth, cfg.limits.maxDepth);
209
213
  rules.checkRate(store.countPair(fromAddr, toAddr, now() - rules.RATE_WINDOW_MS), cfg.limits.perPairPerHour);
210
- const created = record({ kind: input.kind, from: fromAddr, to: toAddr, routeId: input.to, body, inReplyTo: null, depth, bodyHash: hash });
214
+ const created = record({ kind: input.kind, from: fromAddr, to: toAddr, routeId: input.to, body, inReplyTo: null, depth, bodyHash: hash, summary });
211
215
  deliver(created);
212
216
  return { result: receipt(created), row: created };
213
217
  });
@@ -256,19 +260,20 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
256
260
  // that message's receipt, even when a limit would now refuse a new one.
257
261
  submit(input) {
258
262
  requireEnabled();
259
- checkFields(input, ['sender', 'to', 'body', 'key', 'ref', 'origin']);
263
+ checkFields(input, ['sender', 'to', 'body', 'key', 'ref', 'origin', 'summary']);
260
264
  const fromAddr = rules.systemAddress(rules.checkSystemSender(cfg, input.sender));
261
265
  const key = rules.checkKey(input.key);
262
266
  const ref = rules.cleanRef(input.ref);
263
267
  const originName = rules.cleanOriginName(input.origin);
268
+ const summary = rules.cleanSummary(input.summary);
264
269
  if (typeof input.to !== 'string') throw rules.refusal(rules.REFUSAL.unknownRole, 'Unknown role');
265
270
  const toAddr = rules.roleAddress(input.to);
266
- const hash = rules.systemMessageHash(input.body, originName);
271
+ const hash = rules.summaryMessageHash(input.body, summary, originName);
267
272
  const { result, row } = transaction(() => {
268
273
  const existing = store.findByKey(fromAddr, key);
269
274
  if (existing) {
270
275
  if (existing.to_addr !== toAddr || existing.body_hash !== hash) {
271
- throw rules.refusal(rules.REFUSAL.keyConflict, 'Idempotency key already used for a different target, body or origin');
276
+ throw rules.refusal(rules.REFUSAL.keyConflict, 'Idempotency key already used for a different target, body, origin or summary');
272
277
  }
273
278
  return { result: receipt(existing, { duplicate: true }) };
274
279
  }
@@ -280,7 +285,7 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
280
285
  // tell another role under the default maxDepth. A message a human
281
286
  // wrote and the sender only relays is that human asking: depth 0.
282
287
  const depth = originName === null ? 1 : 0;
283
- const created = record({ kind: 'tell', from: fromAddr, to: toAddr, routeId: input.to, body, inReplyTo: null, depth, bodyHash: hash, idemKey: key, ref, originName });
288
+ const created = record({ kind: 'tell', from: fromAddr, to: toAddr, routeId: input.to, body, inReplyTo: null, depth, bodyHash: hash, idemKey: key, ref, originName, summary });
284
289
  deliver(created);
285
290
  return { result: receipt(created), row: created };
286
291
  });
@@ -5,9 +5,9 @@ function createMailboxStore(db, { botName, now = Date.now }) {
5
5
  const byId = db.prepare('SELECT * FROM mailbox_messages WHERE id=? AND bot_name=?');
6
6
  return {
7
7
  insert(m) {
8
- db.prepare(`INSERT INTO mailbox_messages(id,bot_name,kind,from_addr,to_addr,route_id,body,in_reply_to,depth,body_hash,created_at,idem_key,ref,origin_name)
9
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(m.id, botName, m.kind, m.from, m.to, m.routeId, m.body, m.inReplyTo ?? null, m.depth, m.bodyHash, now(),
10
- m.idemKey ?? null, m.ref ?? null, m.originName ?? null);
8
+ db.prepare(`INSERT INTO mailbox_messages(id,bot_name,kind,from_addr,to_addr,route_id,body,in_reply_to,depth,body_hash,created_at,idem_key,ref,origin_name,summary)
9
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(m.id, botName, m.kind, m.from, m.to, m.routeId, m.body, m.inReplyTo ?? null, m.depth, m.bodyHash, now(),
10
+ m.idemKey ?? null, m.ref ?? null, m.originName ?? null, m.summary ?? null);
11
11
  return byId.get(m.id, botName);
12
12
  },
13
13
  get(id) { return byId.get(id, botName) ?? null; },
package/lib/prompt.js CHANGED
@@ -9,6 +9,7 @@ const {
9
9
  requireCodexEnabled,
10
10
  resolveRuntimeDescriptor,
11
11
  } = require('./runtime-config');
12
+ const { richMessageReplyContext } = require('./telegram/rich-inbound');
12
13
 
13
14
  function resolvePromptBackend({ config, chatId, threadId = null }) {
14
15
  const normalizedChatId = String(chatId);
@@ -72,11 +73,58 @@ function xmlEscape(s) {
72
73
  * Truncate to REPLY_TO_MAX_CHARS with a head+tail keepaway pattern.
73
74
  */
74
75
  function truncateReplyText(s, max = REPLY_TO_MAX_CHARS) {
75
- if (!s) return '';
76
+ if (!s || max <= 0) return '';
76
77
  if (s.length <= max) return s;
78
+ if (max === 1) return '…';
77
79
  const head = Math.floor(max * 0.8);
78
- const tail = Math.max(1, max - head - 1);
79
- return `${s.slice(0, head)}…${s.slice(-tail)}`;
80
+ const tail = Math.max(0, max - head - 1);
81
+ return `${s.slice(0, head).replace(/[\uD800-\uDBFF]$/, '')}…${tail ? s.slice(-tail).replace(/^[\uDC00-\uDFFF]/, '') : ''}`;
82
+ }
83
+
84
+ // Link targets are atomic context: reserve them before shortening labels or
85
+ // surrounding prose, so a clean task title still identifies its task.
86
+ function telegramReplyText(message) {
87
+ const originalText = message.text || message.caption || '';
88
+ const rich = message.rich_message ? richMessageReplyContext(message.rich_message) : null;
89
+ const text = rich ? rich.text : originalText;
90
+ const entities = message.text ? message.entities : message.caption_entities;
91
+ const entityLinks = (Array.isArray(entities) ? entities : []).filter((entity) => entity?.type === 'text_link'
92
+ && typeof entity.url === 'string' && entity.url.length > 0
93
+ && Number.isSafeInteger(entity.offset) && entity.offset >= 0
94
+ && Number.isSafeInteger(entity.length) && entity.length > 0
95
+ && entity.offset + entity.length <= originalText.length)
96
+ .map((entity) => ({ url: entity.url, label: originalText.slice(entity.offset, entity.offset + entity.length) }));
97
+ const seen = new Set();
98
+ const links = [...entityLinks, ...(rich?.links || [])].filter(({ url }) => {
99
+ if (seen.has(url)) return false;
100
+ seen.add(url); return true;
101
+ });
102
+ if (!links.length) return truncateReplyText(text);
103
+
104
+ const prefix = 'Links:\n';
105
+ const entries = [];
106
+ let used = prefix.length;
107
+ let omitted = false;
108
+ for (const [index, link] of links.entries()) {
109
+ const size = link.url.length + 2 + (entries.length ? 1 : 0);
110
+ const reserve = omitted || index < links.length - 1 ? 2 : 0;
111
+ if (used + size > REPLY_TO_MAX_CHARS - reserve) { omitted = true; continue; }
112
+ entries.push(link);
113
+ used += size;
114
+ }
115
+ if (omitted) {
116
+ used += (entries.length ? 1 : 0) + 1;
117
+ }
118
+ let spare = REPLY_TO_MAX_CHARS - used;
119
+ const lines = entries.map(({ url, label }) => {
120
+ const kept = truncateReplyText(label, Math.min(64, spare - 1));
121
+ spare -= kept ? kept.length + 1 : 0;
122
+ return `${kept ? `${kept} ` : ''}<${url}>`;
123
+ });
124
+ if (omitted) lines.push('…');
125
+ const targets = prefix + lines.join('\n');
126
+ const surrounding = truncateReplyText(text, REPLY_TO_MAX_CHARS - targets.length - 1);
127
+ return [surrounding, targets].filter(Boolean).join('\n');
80
128
  }
81
129
 
82
130
  /**
@@ -98,7 +146,7 @@ function buildReplyToBlock(input) {
98
146
  const msgId = telegram.message_id;
99
147
  const user = telegram.from?.first_name || telegram.from?.username || 'Unknown';
100
148
  const ts = telegram.date ? new Date(telegram.date * 1000).toISOString() : '';
101
- const text = truncateReplyText(telegram.text || telegram.caption || '');
149
+ const text = telegramReplyText(telegram);
102
150
  const hasMedia = !!(telegram.document || telegram.photo || telegram.voice || telegram.audio || telegram.video);
103
151
  const summary = hasMedia ? summarizeTelegramAttachments(telegram) : '';
104
152
  const body = [text, summary].filter(Boolean).join('\n');
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ const { richMessageToText } = require('./rich-inbound');
4
+
5
+ // One rich attempt through the shared sender, then one destination-preserving
6
+ // HTML fallback. The sender owns capability decisions and transcript recording.
7
+ async function sendRichCard({ sendRich, tg, bot, chatId, threadId = null, blocks, fallback, meta = {} }) {
8
+ const strictMeta = { ...meta, strictDestination: true, linkPreview: false };
9
+ const sent = sendRich ? await sendRich({ bot, chatId, threadId, blocks,
10
+ sourceText: richMessageToText({ blocks }), meta: strictMeta }) : { wentRich: false };
11
+ if (sent.wentRich) return { result: sent.result, rich: true };
12
+ if (!fallback) throw new Error(`Rich send failed (${sent.fallback || 'unsupported'})`);
13
+ const result = await tg(bot, 'sendMessage', {
14
+ chat_id: chatId, ...(threadId == null ? {} : { message_thread_id: threadId }),
15
+ text: fallback.text, parse_mode: 'HTML',
16
+ }, strictMeta);
17
+ return { result, rich: false };
18
+ }
19
+
20
+ module.exports = { sendRichCard };
@@ -215,6 +215,38 @@ function richMessageToText(richMessage) {
215
215
  return text.slice(0, surrogateSafeCut(text, MAX_RENDERED_CHARS)) + TRUNCATED_MARKER;
216
216
  }
217
217
 
218
+ // Reply context reserves whole targets separately from surrounding prose.
219
+ // Render a label-only copy so head/tail truncation cannot leave URL fragments,
220
+ // including when intake has already rendered Markdown links into msg.text.
221
+ function richMessageReplyContext(richMessage) {
222
+ const links = [];
223
+ let visited = 0;
224
+ function labels(node, depth = 0) {
225
+ if (depth > MAX_DEPTH || ++visited > MAX_RENDERED_CHARS) return null;
226
+ if (!node || typeof node !== 'object') return node;
227
+ const link = node.type === 'url' && typeof node.url === 'string' && node.url
228
+ ? { url: node.url, label: '' } : null;
229
+ if (link) links.push(link);
230
+ if (Array.isArray(node)) {
231
+ const copy = [];
232
+ for (const value of node) {
233
+ if (visited >= MAX_RENDERED_CHARS) break;
234
+ copy.push(labels(value, depth + 1));
235
+ }
236
+ return copy;
237
+ }
238
+ const copy = {};
239
+ for (const key of Object.keys(node)) {
240
+ if (visited >= MAX_RENDERED_CHARS) break;
241
+ if (node.type === 'url' && key === 'url') continue;
242
+ copy[key] = labels(node[key], depth + 1);
243
+ }
244
+ if (link) link.label = inlineText(copy.text);
245
+ return copy;
246
+ }
247
+ return { text: richMessageToText(labels(richMessage)), links };
248
+ }
249
+
218
250
  function renderInto(msg) {
219
251
  if (!msg || typeof msg !== 'object' || msg.text || msg.caption || !msg.rich_message) return;
220
252
  const text = richMessageToText(msg.rich_message);
@@ -248,6 +280,7 @@ function normalizeRichInbound(msg, { logger = console } = {}) {
248
280
 
249
281
  module.exports = {
250
282
  richMessageToText,
283
+ richMessageReplyContext,
251
284
  normalizeRichInbound,
252
285
  RICH_TEXT_HEADER,
253
286
  MAX_RENDERED_CHARS,
@@ -0,0 +1,2 @@
1
+ -- Display metadata for the collapsed line of a mailbox mirror card.
2
+ ALTER TABLE mailbox_messages ADD COLUMN summary TEXT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.47.1",
3
+ "version": "0.48.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": {
package/polygram.js CHANGED
@@ -4516,8 +4516,9 @@ async function main() {
4516
4516
  pm, bot, tg, logEvent, isAbortRequest,
4517
4517
  markSessionAborted, clearAutosteeredReactions, getSessionKey,
4518
4518
  retireQuestionSession: (sessionKey) => questionHandlers?.retireSession(sessionKey),
4519
+ holdAutomationAdmission: (sessionKey) => mailboxService?.roleForSession(sessionKey) ? intentLock.acquire(sessionKey) : null,
4519
4520
  pauseAutomation: ({ msg, chatId, threadId, sessionKey }) => {
4520
- if (externalJobService && isAutomationDestination({ config, getSessionKey }, chatId, threadId) && isAutomationOperator(config, msg)) {
4521
+ if (!mailboxService?.roleForSession(sessionKey) && externalJobService && isAutomationDestination({ config, getSessionKey }, chatId, threadId) && isAutomationOperator(config, msg)) {
4521
4522
  return pauseAutomationSession({ service: externalJobService, intentLock, sessionKey, paused: true });
4522
4523
  }
4523
4524
  },
@@ -4533,7 +4534,7 @@ async function main() {
4533
4534
  db, dbWrite, config, botName: BOT_NAME, extractAttachments,
4534
4535
  });
4535
4536
  handleSendOverIpc = createHandleSendOverIpc({
4536
- config, bot, tg, botName: BOT_NAME,
4537
+ config, bot, tg, botName: BOT_NAME, sendRich: (args) => richSendMessage(args),
4537
4538
  });
4538
4539
  ({
4539
4540
  dispatchHandleMessage,
@@ -4602,7 +4603,7 @@ async function main() {
4602
4603
  });
4603
4604
  mailboxService = createMailboxService({
4604
4605
  config, db, botName: BOT_NAME, jobs: externalJobService, resolveTarget: resolveExternalTarget, bot, tg,
4605
- ipcDir: ipcRuntimeDir,
4606
+ ipcDir: ipcRuntimeDir, sendRich: (args) => richSendMessage(args),
4606
4607
  });
4607
4608
  // 0.12.0 post-turn edit re-delivery: constructed AFTER dispatchHandleMessage is assigned (above).
4608
4609
  // Claude keeps its same-message fold behavior. Codex defers edits to the
@@ -9,10 +9,13 @@ identity in the body. Tokens expire when the daemon restarts, so always use the
9
9
  current turn's command.
10
10
 
11
11
  `send` takes one JSON object: `{"to":"<role>","kind":"ask"|"tell","body":"..."}`.
12
- An `ask` expects exactly one reply; a `tell` expects none. `reply` takes
12
+ `send` also accepts optional `summary`: a short, nonblank one-line heading (up to
13
+ 120 characters, no controls) for the collapsed mirror card. It is not sent to
14
+ the receiving role. An `ask` expects exactly one reply; a `tell` expects none.
15
+ `reply` takes
13
16
  `{"id":"<message id of the ask>","body":"..."}`. Both return `{"id","state"}`
14
17
  right away; `state` is `queued`, or `paused` while the target role is paused.
15
- A repeated identical send (same target, kind and body) within ten minutes
18
+ A repeated identical send (same target, kind, body and summary) within ten minutes
16
19
  returns the existing message with `duplicate: true` and its current delivery
17
20
  state, which may already be `running`, `succeeded`, `failed`, `interrupted` or
18
21
  `unknown`. After you get a notice about an ask, sending the same ask again