polygram 0.47.2 → 0.48.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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +7 -1
- package/docs/MAILBOX.md +36 -27
- package/lib/db.js +1 -1
- package/lib/handlers/ipc-send.js +19 -1
- package/lib/mailbox/envelope.js +16 -8
- package/lib/mailbox/rules.js +17 -1
- package/lib/mailbox/service.js +17 -13
- package/lib/mailbox/store.js +3 -3
- package/lib/prompt.js +13 -4
- package/lib/telegram/rich-card-send.js +20 -0
- package/lib/telegram/rich-inbound.js +33 -0
- package/migrations/027-mailbox-summary.sql +2 -0
- package/package.json +2 -2
- package/polygram.js +2 -2
- package/skills/mailbox/SKILL.md +5 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://anthropic.com/claude-code/plugin.schema.json",
|
|
3
3
|
"name": "polygram",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.48.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
|
@@ -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: `"target"` (or `true`) posts
|
|
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,35 +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
|
-
|
|
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
|
-
❓
|
|
111
|
-
|
|
110
|
+
```
|
|
111
|
+
❓ Question · orchestrator → marketing
|
|
112
|
+
▸ What is the Q3 budget?
|
|
112
113
|
```
|
|
113
114
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
Parsed header and body fit 4096 UTF-16 units; longer content is cut by whole
|
|
120
|
-
code points and marked `…`. Supported servers require Bot API 7.3 or newer
|
|
121
|
-
for expandable quotations; the VPS bots use Bot API 10.2.
|
|
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.
|
|
122
120
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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.
|
|
126
129
|
|
|
127
|
-
|
|
128
|
-
|
|
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>
|
|
130
136
|
```
|
|
131
137
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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.
|
|
135
144
|
|
|
136
145
|
## System senders
|
|
137
146
|
|
|
@@ -149,14 +158,14 @@ to the IPC socket with the bot's secret, like any other IPC client.
|
|
|
149
158
|
- `key` (1 to 256 bytes) is the caller's idempotency key. It is looked up
|
|
150
159
|
first, per sender. A hit returns the stored message's receipt with its real
|
|
151
160
|
delivery state and `duplicate: true`. A hit whose `to`, redacted body or
|
|
152
|
-
`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`
|
|
153
162
|
does not conflict.
|
|
154
163
|
- There is no ten-minute duplicate window; the key replaces it.
|
|
155
164
|
- `limits.systemPerHour` applies per sender, counted only after the key
|
|
156
165
|
lookup, so a retry of an accepted message is never rate limited. System
|
|
157
166
|
sends don't use up a role pair's budget.
|
|
158
167
|
- The size cap, redaction and target mirror apply as for agent messages.
|
|
159
|
-
A system sender has no topic, so it never gets a sender
|
|
168
|
+
A system sender has no topic, so it never gets a sender card.
|
|
160
169
|
- `ref` (optional, 1 to 512 bytes) is an opaque reference such as a task id
|
|
161
170
|
or URL. It is redacted, stored, and shown to the receiver only inside the
|
|
162
171
|
untrusted payload, never in the trusted header.
|
|
@@ -233,7 +242,7 @@ contract and do not change:
|
|
|
233
242
|
| `MAILBOX_UNKNOWN_ROLE` | `to` is not a configured role. | No. |
|
|
234
243
|
| `MAILBOX_TOO_LARGE` | The body is over `maxBodyBytes`, before or after redaction. | No. |
|
|
235
244
|
| `MAILBOX_RATE_LIMITED` | `systemPerHour`, or the per-pair limit for agent sends. | Yes, later. |
|
|
236
|
-
| `MAILBOX_KEY_CONFLICT` | The key was used for a different target, body or
|
|
245
|
+
| `MAILBOX_KEY_CONFLICT` | The key was used for a different target, body, origin or summary. | No. |
|
|
237
246
|
| `MAILBOX_INVALID_ORIGIN` | `origin` is not exactly `{kind:"human", name}` with a name of 1 to 64 characters and no control characters. | No. |
|
|
238
247
|
|
|
239
248
|
A refusal from the external-jobs queue keeps its own code, for example
|
|
@@ -285,7 +294,7 @@ Messages live in `mailbox_messages`; delivery state lives in `external_jobs`
|
|
|
285
294
|
under `request_id = 'mailbox:' || id` (notices: `'mailbox-notice:' || askId`,
|
|
286
295
|
or `|| replyId` for a reply that was not delivered). System messages also
|
|
287
296
|
store their `idem_key` and `ref`, and a relayed human message its
|
|
288
|
-
`origin_name`.
|
|
297
|
+
`origin_name`; optional collapsed headings live in `summary`.
|
|
289
298
|
|
|
290
299
|
```sql
|
|
291
300
|
SELECT m.id, m.kind, m.from_addr, m.to_addr, m.depth, m.notice_sent, j.state, j.report_state, j.error
|
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 =
|
|
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
|
package/lib/handlers/ipc-send.js
CHANGED
|
@@ -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,
|
package/lib/mailbox/envelope.js
CHANGED
|
@@ -104,13 +104,21 @@ function renderMirror(row) {
|
|
|
104
104
|
return `${icon} <b>${escapeHtml(header)}</b>\n<blockquote expandable>${escapeHtml(body)}</blockquote>`;
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
|
|
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
|
+
] }];
|
|
114
122
|
}
|
|
115
123
|
|
|
116
|
-
module.exports = { renderTask, renderPayload, renderNoticeTask, renderNoticePayload, renderMirror,
|
|
124
|
+
module.exports = { renderTask, renderPayload, renderNoticeTask, renderNoticePayload, renderMirror, renderRichMirror };
|
package/lib/mailbox/rules.js
CHANGED
|
@@ -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
|
};
|
package/lib/mailbox/service.js
CHANGED
|
@@ -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,
|
|
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,
|
|
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,
|
|
87
|
+
function post(target, row, source, what) {
|
|
87
88
|
if (!target) return;
|
|
88
89
|
Promise.resolve()
|
|
89
|
-
.then(() =>
|
|
90
|
-
|
|
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
|
}
|
|
@@ -197,10 +199,11 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
|
|
|
197
199
|
send(token, input) {
|
|
198
200
|
requireEnabled();
|
|
199
201
|
const from = caller(token);
|
|
200
|
-
checkFields(input, ['to', 'kind', 'body']);
|
|
202
|
+
checkFields(input, ['to', 'kind', 'body', 'summary']);
|
|
201
203
|
rules.checkStart(cfg, { from: from.role, to: input.to, kind: input.kind });
|
|
202
204
|
const body = rules.cleanBody(input.body, cfg.limits.maxBodyBytes);
|
|
203
|
-
const
|
|
205
|
+
const summary = rules.cleanSummary(input.summary);
|
|
206
|
+
const hash = rules.summaryMessageHash(body, summary);
|
|
204
207
|
const fromAddr = rules.roleAddress(from.role);
|
|
205
208
|
const toAddr = rules.roleAddress(input.to);
|
|
206
209
|
const { result, row } = transaction(() => {
|
|
@@ -208,7 +211,7 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
|
|
|
208
211
|
if (duplicate) return { result: receipt(duplicate, { duplicate: true }) };
|
|
209
212
|
const depth = rules.nextDepth(from.depth, cfg.limits.maxDepth);
|
|
210
213
|
rules.checkRate(store.countPair(fromAddr, toAddr, now() - rules.RATE_WINDOW_MS), cfg.limits.perPairPerHour);
|
|
211
|
-
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 });
|
|
212
215
|
deliver(created);
|
|
213
216
|
return { result: receipt(created), row: created };
|
|
214
217
|
});
|
|
@@ -257,19 +260,20 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
|
|
|
257
260
|
// that message's receipt, even when a limit would now refuse a new one.
|
|
258
261
|
submit(input) {
|
|
259
262
|
requireEnabled();
|
|
260
|
-
checkFields(input, ['sender', 'to', 'body', 'key', 'ref', 'origin']);
|
|
263
|
+
checkFields(input, ['sender', 'to', 'body', 'key', 'ref', 'origin', 'summary']);
|
|
261
264
|
const fromAddr = rules.systemAddress(rules.checkSystemSender(cfg, input.sender));
|
|
262
265
|
const key = rules.checkKey(input.key);
|
|
263
266
|
const ref = rules.cleanRef(input.ref);
|
|
264
267
|
const originName = rules.cleanOriginName(input.origin);
|
|
268
|
+
const summary = rules.cleanSummary(input.summary);
|
|
265
269
|
if (typeof input.to !== 'string') throw rules.refusal(rules.REFUSAL.unknownRole, 'Unknown role');
|
|
266
270
|
const toAddr = rules.roleAddress(input.to);
|
|
267
|
-
const hash = rules.
|
|
271
|
+
const hash = rules.summaryMessageHash(input.body, summary, originName);
|
|
268
272
|
const { result, row } = transaction(() => {
|
|
269
273
|
const existing = store.findByKey(fromAddr, key);
|
|
270
274
|
if (existing) {
|
|
271
275
|
if (existing.to_addr !== toAddr || existing.body_hash !== hash) {
|
|
272
|
-
throw rules.refusal(rules.REFUSAL.keyConflict, 'Idempotency key already used for a different target, body or
|
|
276
|
+
throw rules.refusal(rules.REFUSAL.keyConflict, 'Idempotency key already used for a different target, body, origin or summary');
|
|
273
277
|
}
|
|
274
278
|
return { result: receipt(existing, { duplicate: true }) };
|
|
275
279
|
}
|
|
@@ -281,7 +285,7 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
|
|
|
281
285
|
// tell another role under the default maxDepth. A message a human
|
|
282
286
|
// wrote and the sender only relays is that human asking: depth 0.
|
|
283
287
|
const depth = originName === null ? 1 : 0;
|
|
284
|
-
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 });
|
|
285
289
|
deliver(created);
|
|
286
290
|
return { result: receipt(created), row: created };
|
|
287
291
|
});
|
package/lib/mailbox/store.js
CHANGED
|
@@ -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 (
|
|
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);
|
|
@@ -83,13 +84,21 @@ function truncateReplyText(s, max = REPLY_TO_MAX_CHARS) {
|
|
|
83
84
|
// Link targets are atomic context: reserve them before shortening labels or
|
|
84
85
|
// surrounding prose, so a clean task title still identifies its task.
|
|
85
86
|
function telegramReplyText(message) {
|
|
86
|
-
const
|
|
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;
|
|
87
90
|
const entities = message.text ? message.entities : message.caption_entities;
|
|
88
|
-
const
|
|
91
|
+
const entityLinks = (Array.isArray(entities) ? entities : []).filter((entity) => entity?.type === 'text_link'
|
|
89
92
|
&& typeof entity.url === 'string' && entity.url.length > 0
|
|
90
93
|
&& Number.isSafeInteger(entity.offset) && entity.offset >= 0
|
|
91
94
|
&& Number.isSafeInteger(entity.length) && entity.length > 0
|
|
92
|
-
&& entity.offset + entity.length <=
|
|
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
|
+
});
|
|
93
102
|
if (!links.length) return truncateReplyText(text);
|
|
94
103
|
|
|
95
104
|
const prefix = 'Links:\n';
|
|
@@ -100,7 +109,7 @@ function telegramReplyText(message) {
|
|
|
100
109
|
const size = link.url.length + 2 + (entries.length ? 1 : 0);
|
|
101
110
|
const reserve = omitted || index < links.length - 1 ? 2 : 0;
|
|
102
111
|
if (used + size > REPLY_TO_MAX_CHARS - reserve) { omitted = true; continue; }
|
|
103
|
-
entries.push(
|
|
112
|
+
entries.push(link);
|
|
104
113
|
used += size;
|
|
105
114
|
}
|
|
106
115
|
if (omitted) {
|
|
@@ -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,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.1",
|
|
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": {
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"dependencies": {
|
|
72
72
|
"@anthropic-ai/claude-agent-sdk": "0.3.322",
|
|
73
73
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
74
|
-
"@shumkov/orchestra": "0.12.
|
|
74
|
+
"@shumkov/orchestra": "0.12.4",
|
|
75
75
|
"acorn": "8.18.0",
|
|
76
76
|
"better-sqlite3": "^12.9.0",
|
|
77
77
|
"grammy": "^1.42.0",
|
package/polygram.js
CHANGED
|
@@ -4534,7 +4534,7 @@ async function main() {
|
|
|
4534
4534
|
db, dbWrite, config, botName: BOT_NAME, extractAttachments,
|
|
4535
4535
|
});
|
|
4536
4536
|
handleSendOverIpc = createHandleSendOverIpc({
|
|
4537
|
-
config, bot, tg, botName: BOT_NAME,
|
|
4537
|
+
config, bot, tg, botName: BOT_NAME, sendRich: (args) => richSendMessage(args),
|
|
4538
4538
|
});
|
|
4539
4539
|
({
|
|
4540
4540
|
dispatchHandleMessage,
|
|
@@ -4603,7 +4603,7 @@ async function main() {
|
|
|
4603
4603
|
});
|
|
4604
4604
|
mailboxService = createMailboxService({
|
|
4605
4605
|
config, db, botName: BOT_NAME, jobs: externalJobService, resolveTarget: resolveExternalTarget, bot, tg,
|
|
4606
|
-
ipcDir: ipcRuntimeDir,
|
|
4606
|
+
ipcDir: ipcRuntimeDir, sendRich: (args) => richSendMessage(args),
|
|
4607
4607
|
});
|
|
4608
4608
|
// 0.12.0 post-turn edit re-delivery: constructed AFTER dispatchHandleMessage is assigned (above).
|
|
4609
4609
|
// Claude keeps its same-message fold behavior. Codex defers edits to the
|
package/skills/mailbox/SKILL.md
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|