polygram 0.47.0 → 0.47.2
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/docs/MAILBOX.md +27 -6
- package/docs/RECORDED_NOTIFICATIONS_API.md +3 -1
- package/lib/db/codex-failed-generation.js +19 -17
- package/lib/error/classify.js +2 -0
- package/lib/external-jobs/runtime.js +1 -1
- package/lib/handlers/abort.js +8 -1
- package/lib/handlers/slash-commands.js +62 -38
- package/lib/mailbox/envelope.js +22 -3
- package/lib/mailbox/service.js +5 -4
- package/lib/prompt.js +43 -4
- package/package.json +2 -2
- package/polygram.js +2 -1
|
@@ -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.
|
|
4
|
+
"version": "0.47.2",
|
|
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/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
|
|
50
|
+
| `mirror` | Where each message is posted: `"target"` (or `true`) posts an HTML card into the target role's topic; `"both"` also posts a plain sender line 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. |
|
|
@@ -106,10 +106,19 @@ text lands in its own topic through the normal job report.
|
|
|
106
106
|
Each message is posted once, right after it commits, never from the
|
|
107
107
|
dispatch path. The target role's topic gets the whole redacted body:
|
|
108
108
|
|
|
109
|
+
```html
|
|
110
|
+
❓ <b>orchestrator asks marketing</b>
|
|
111
|
+
<blockquote expandable>What is the Q3 budget?</blockquote>
|
|
109
112
|
```
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
+
|
|
114
|
+
Tells use `📨 agent-org → prices`, asks `❓ cmo asks direct`, and replies
|
|
115
|
+
`↩️ direct answered cmo`, with the words in bold and no transport ids. A
|
|
116
|
+
relayed human's stored name adds `· from Ivan` to the header. The expandable
|
|
117
|
+
quotation contains the stored body literally, with HTML escaped; technical
|
|
118
|
+
instructions remain available when expanded. Link previews are disabled.
|
|
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.
|
|
113
122
|
|
|
114
123
|
With `"mirror": "both"`, the sending role's topic also gets a sender line,
|
|
115
124
|
so a role's chat shows what it sent. It carries the first 300 characters of
|
|
@@ -209,7 +218,7 @@ agent-org runner relaying a person's Notion comment, adds an `origin`:
|
|
|
209
218
|
with the same key and a different name, or with the origin added or
|
|
210
219
|
dropped, is `MAILBOX_KEY_CONFLICT`, so a message accepted at depth 1 can't
|
|
211
220
|
be upgraded to depth 0 by a retry.
|
|
212
|
-
- The mirror
|
|
221
|
+
- The target mirror header includes `· from <name>`, using the stored redacted name.
|
|
213
222
|
|
|
214
223
|
## Error codes
|
|
215
224
|
|
|
@@ -250,8 +259,20 @@ with backoff from 1 to 30 minutes while the session is paused or busy.
|
|
|
250
259
|
## Human control
|
|
251
260
|
|
|
252
261
|
- `/automation pause|resume` from the operator in a role's topic pauses or
|
|
253
|
-
resumes delivery into that role.
|
|
262
|
+
resumes delivery into that role. A stop phrase or `/stop` only interrupts
|
|
263
|
+
the current turn; it never creates or clears a pause. A pause
|
|
254
264
|
holds that topic's job reports too.
|
|
265
|
+
- After a stop, the interrupted job is not retried. Once stopping finishes
|
|
266
|
+
and the session is proven idle, the next queued job may start immediately.
|
|
267
|
+
Active stops keep the 👍 reaction; idle stops stay silent. No pause notice
|
|
268
|
+
is posted. `/automation status` reports the actual pause and job counts;
|
|
269
|
+
`enabled` does not guarantee that inactivity has been proven. If a stopped
|
|
270
|
+
process was destroyed, queued work waits for a recovered process's idle
|
|
271
|
+
proof; the unknown-job recovery poller does not recover `interrupted` jobs.
|
|
272
|
+
- Mailbox roles are identified by their resolved session, including General.
|
|
273
|
+
A non-mailbox route sharing a role session follows the same interrupt-only
|
|
274
|
+
stop policy. Dedicated infrastructure and recorded-notification destinations
|
|
275
|
+
retain durable pause-on-stop. A disabled mailbox retains that default too.
|
|
255
276
|
- `mailbox.enabled: false` (then restart) stops all delivery. Queued mailbox
|
|
256
277
|
jobs are withdrawn unsent as `failed` with error `withdrawn`, and the role's
|
|
257
278
|
other jobs keep flowing.
|
|
@@ -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
|
|
@@ -231,23 +231,25 @@ function settleCodexFailedGeneration(rawDb, input) {
|
|
|
231
231
|
) {
|
|
232
232
|
conflict('Codex provider session does not match the failed generation');
|
|
233
233
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
234
|
+
if (reason !== 'thread-attach-outcome-unknown') {
|
|
235
|
+
const deleted = rawDb.prepare(`
|
|
236
|
+
DELETE FROM agent_runtime_sessions
|
|
237
|
+
WHERE session_key = ?
|
|
238
|
+
AND namespace = ?
|
|
239
|
+
AND provider = 'codex'
|
|
240
|
+
AND provider_session_id = ?
|
|
241
|
+
AND app_server_session_id IS ?
|
|
242
|
+
AND generation_id IS ?
|
|
243
|
+
`).run(
|
|
244
|
+
sessionKey,
|
|
245
|
+
CODEX_APP_SERVER_NAMESPACE,
|
|
246
|
+
providerSessionId,
|
|
247
|
+
appServerSessionId,
|
|
248
|
+
provider.generation_id,
|
|
249
|
+
);
|
|
250
|
+
if (deleted.changes !== 1) {
|
|
251
|
+
conflict('Codex provider session changed during settlement');
|
|
252
|
+
}
|
|
251
253
|
}
|
|
252
254
|
}
|
|
253
255
|
|
package/lib/error/classify.js
CHANGED
|
@@ -265,6 +265,8 @@ const CODEX_ERROR_CODES = {
|
|
|
265
265
|
], CODEX_ERROR_SHAPES.childExit),
|
|
266
266
|
CODEX_RPC_NOT_SENT: CODEX_ERROR_SHAPES.notSent,
|
|
267
267
|
CODEX_RPC_ERROR: CODEX_ERROR_SHAPES.providerError,
|
|
268
|
+
CODEX_THREAD_UNAVAILABLE: stableCodeShape('codexThreadUnavailable',
|
|
269
|
+
'⚠️ The saved Codex conversation is unavailable in this workspace. No message was sent. Use /new to start a fresh conversation after cleanup completes.'),
|
|
268
270
|
CODEX_DAEMON_GENERATION_BUSY: CODEX_ERROR_SHAPES.busy,
|
|
269
271
|
};
|
|
270
272
|
|
|
@@ -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,
|
package/lib/handlers/abort.js
CHANGED
|
@@ -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 };
|
|
@@ -267,54 +267,78 @@ function createSlashCommands({
|
|
|
267
267
|
|
|
268
268
|
// /new + /reset + /clear — fresh session (all synonyms)
|
|
269
269
|
if (botAllowsCommands && (text === '/new' || text === '/reset' || text === '/clear')) {
|
|
270
|
-
|
|
271
|
-
|
|
270
|
+
const releaseIntent = await intentLock.acquire(sessionKey);
|
|
271
|
+
try {
|
|
272
|
+
let runtimeView = null;
|
|
273
|
+
if (typeof resolveRuntimeView === 'function') {
|
|
274
|
+
try {
|
|
275
|
+
runtimeView = await resolveRuntimeView({
|
|
276
|
+
sessionKey,
|
|
277
|
+
chatId,
|
|
278
|
+
threadId: threadIdStr,
|
|
279
|
+
});
|
|
280
|
+
} catch (error) {
|
|
281
|
+
logger.error?.(
|
|
282
|
+
`[${label}] ${text} runtime view failed: `
|
|
283
|
+
+ `${error?.code || error?.name || 'unknown'}`,
|
|
284
|
+
);
|
|
285
|
+
await sendReply(
|
|
286
|
+
'Runtime status is temporarily unavailable; the active session was not changed.',
|
|
287
|
+
);
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const codex = isCodexRuntimeView(runtimeView);
|
|
292
|
+
let drained = 0;
|
|
272
293
|
try {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
294
|
+
// A fresh session retires the process that owns any open question.
|
|
295
|
+
// Deliberately before the reset: if the reset then fails, the safe
|
|
296
|
+
// outcome is still that nothing exact was kept.
|
|
297
|
+
await retireQuestionSession?.(sessionKey);
|
|
298
|
+
const contained = codex ? pm.get(sessionKey) : null;
|
|
299
|
+
if (contained?.containmentClosePromise) {
|
|
300
|
+
await contained.containmentClosePromise;
|
|
301
|
+
const status = await pm.getModelSettingsStatus(sessionKey);
|
|
302
|
+
if (status.outcome !== 'not-loaded') {
|
|
303
|
+
throw new Error('Codex containment ownership is not released');
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const r = await pm.resetSession(sessionKey, { reason: text.slice(1) });
|
|
307
|
+
if (codex) {
|
|
308
|
+
const status = await pm.getModelSettingsStatus(sessionKey);
|
|
309
|
+
const lease = db.getCodexLease();
|
|
310
|
+
if (status.outcome !== 'not-loaded' || (lease && lease.status !== 'clear')) {
|
|
311
|
+
throw new Error('Codex reset ownership is not released');
|
|
312
|
+
}
|
|
313
|
+
db.clearProviderSession(sessionKey, 'codex:app-server');
|
|
314
|
+
if (db.getProviderSession(sessionKey, 'codex:app-server') != null) {
|
|
315
|
+
throw new Error('Codex saved conversation pointer was not cleared');
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
drained = r?.drainedPendings ?? 0;
|
|
319
|
+
} catch (err) {
|
|
320
|
+
logger.error?.(`[${label}] resetSession ${text}: ${err.message}`);
|
|
283
321
|
await sendReply(
|
|
284
|
-
|
|
322
|
+
codex
|
|
323
|
+
? '✨ Couldn’t start a fresh Codex thread because cleanup was not proven; the prior Codex thread may be unchanged.'
|
|
324
|
+
: '✨ Couldn’t start a fresh Claude session; the prior session may be unchanged.',
|
|
285
325
|
);
|
|
286
326
|
return true;
|
|
287
327
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
// Deliberately before the reset: if the reset then fails, the safe
|
|
294
|
-
// outcome is still that nothing exact was kept.
|
|
295
|
-
await retireQuestionSession?.(sessionKey);
|
|
296
|
-
const r = await pm.resetSession(sessionKey, { reason: text.slice(1) });
|
|
297
|
-
drained = r?.drainedPendings ?? 0;
|
|
298
|
-
} catch (err) {
|
|
299
|
-
logger.error?.(`[${label}] resetSession ${text}: ${err.message}`);
|
|
328
|
+
contextHintShown.delete(sessionKey);
|
|
329
|
+
logEvent('session-reset-command', {
|
|
330
|
+
chat_id: chatId, command: commandVerb(), drained_pendings: drained,
|
|
331
|
+
user_id: cmdUserId,
|
|
332
|
+
});
|
|
300
333
|
await sendReply(
|
|
301
334
|
codex
|
|
302
|
-
? '✨
|
|
303
|
-
: '✨
|
|
335
|
+
? '✨ Started a fresh Codex thread.'
|
|
336
|
+
: '✨ Started a fresh session.',
|
|
304
337
|
);
|
|
305
338
|
return true;
|
|
339
|
+
} finally {
|
|
340
|
+
releaseIntent();
|
|
306
341
|
}
|
|
307
|
-
contextHintShown.delete(sessionKey);
|
|
308
|
-
logEvent('session-reset-command', {
|
|
309
|
-
chat_id: chatId, command: commandVerb(), drained_pendings: drained,
|
|
310
|
-
user_id: cmdUserId,
|
|
311
|
-
});
|
|
312
|
-
await sendReply(
|
|
313
|
-
codex
|
|
314
|
-
? '✨ Started a fresh Codex thread.'
|
|
315
|
-
: '✨ Started a fresh session.',
|
|
316
|
-
);
|
|
317
|
-
return true;
|
|
318
342
|
}
|
|
319
343
|
|
|
320
344
|
// SDK pm applies model/effort changes live via setModel /
|
package/lib/mailbox/envelope.js
CHANGED
|
@@ -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,10 +80,28 @@ function renderNoticePayload(ask, job, reply = null) {
|
|
|
79
80
|
};
|
|
80
81
|
}
|
|
81
82
|
|
|
82
|
-
//
|
|
83
|
-
|
|
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
|
-
|
|
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
107
|
// The line for the sending role's own topic, so that topic shows what the
|
package/lib/mailbox/service.js
CHANGED
|
@@ -77,17 +77,17 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
|
|
|
77
77
|
// topic as the job report. Only a role sender has a topic of its own.
|
|
78
78
|
function mirror(row) {
|
|
79
79
|
if (!cfg.mirror || !tg) return;
|
|
80
|
-
post(cfg.roles.get(row.route_id)?.target, envelope.renderMirror(row), 'mailbox-mirror', `mirror of ${row.id}
|
|
80
|
+
post(cfg.roles.get(row.route_id)?.target, envelope.renderMirror(row), 'mailbox-mirror', `mirror of ${row.id}`, true);
|
|
81
81
|
if (cfg.mirror === 'both') {
|
|
82
82
|
const sender = rules.roleFromAddress(row.from_addr);
|
|
83
83
|
post(sender ? cfg.roles.get(sender)?.target : null, envelope.renderSenderMirror(row), 'mailbox-sender-mirror', `sender mirror of ${row.id}`);
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
|
-
function post(target, text, source, what) {
|
|
86
|
+
function post(target, text, source, what, html = false) {
|
|
87
87
|
if (!target) return;
|
|
88
88
|
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 }))
|
|
89
|
+
.then(() => tg(bot, 'sendMessage', { chat_id: target.chatId, ...(target.threadId == null ? {} : { message_thread_id: target.threadId }), text, ...(html ? { parse_mode: 'HTML' } : {}) },
|
|
90
|
+
{ source, botName, sessionKey: target.sessionKey, ...(html ? { linkPreview: false } : { plainText: true }), strictDestination: true }))
|
|
91
91
|
// Telegram's description is API text, not message content.
|
|
92
92
|
.catch((error) => logger.error?.(`[mailbox] ${what} failed: ${error?.error_code ?? error?.code ?? error?.name ?? 'Error'}${error?.description ? ` ${error.description}` : ''}`));
|
|
93
93
|
}
|
|
@@ -159,6 +159,7 @@ function createMailboxService({ config, db, botName, jobs, resolveTarget, bot =
|
|
|
159
159
|
|
|
160
160
|
const api = {
|
|
161
161
|
enabled: cfg !== null,
|
|
162
|
+
roleForSession: roleOf,
|
|
162
163
|
scope(sessionKey) {
|
|
163
164
|
if (!roleOf(sessionKey)) return null;
|
|
164
165
|
let token = tokenBySession.get(sessionKey);
|
package/lib/prompt.js
CHANGED
|
@@ -72,11 +72,50 @@ function xmlEscape(s) {
|
|
|
72
72
|
* Truncate to REPLY_TO_MAX_CHARS with a head+tail keepaway pattern.
|
|
73
73
|
*/
|
|
74
74
|
function truncateReplyText(s, max = REPLY_TO_MAX_CHARS) {
|
|
75
|
-
if (!s) return '';
|
|
75
|
+
if (!s || max <= 0) return '';
|
|
76
76
|
if (s.length <= max) return s;
|
|
77
|
+
if (max === 1) return '…';
|
|
77
78
|
const head = Math.floor(max * 0.8);
|
|
78
|
-
const tail = Math.max(
|
|
79
|
-
return `${s.slice(0, head)}…${s.slice(-tail)}`;
|
|
79
|
+
const tail = Math.max(0, max - head - 1);
|
|
80
|
+
return `${s.slice(0, head).replace(/[\uD800-\uDBFF]$/, '')}…${tail ? s.slice(-tail).replace(/^[\uDC00-\uDFFF]/, '') : ''}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Link targets are atomic context: reserve them before shortening labels or
|
|
84
|
+
// surrounding prose, so a clean task title still identifies its task.
|
|
85
|
+
function telegramReplyText(message) {
|
|
86
|
+
const text = message.text || message.caption || '';
|
|
87
|
+
const entities = message.text ? message.entities : message.caption_entities;
|
|
88
|
+
const links = (Array.isArray(entities) ? entities : []).filter((entity) => entity?.type === 'text_link'
|
|
89
|
+
&& typeof entity.url === 'string' && entity.url.length > 0
|
|
90
|
+
&& Number.isSafeInteger(entity.offset) && entity.offset >= 0
|
|
91
|
+
&& Number.isSafeInteger(entity.length) && entity.length > 0
|
|
92
|
+
&& entity.offset + entity.length <= text.length);
|
|
93
|
+
if (!links.length) return truncateReplyText(text);
|
|
94
|
+
|
|
95
|
+
const prefix = 'Links:\n';
|
|
96
|
+
const entries = [];
|
|
97
|
+
let used = prefix.length;
|
|
98
|
+
let omitted = false;
|
|
99
|
+
for (const [index, link] of links.entries()) {
|
|
100
|
+
const size = link.url.length + 2 + (entries.length ? 1 : 0);
|
|
101
|
+
const reserve = omitted || index < links.length - 1 ? 2 : 0;
|
|
102
|
+
if (used + size > REPLY_TO_MAX_CHARS - reserve) { omitted = true; continue; }
|
|
103
|
+
entries.push({ url: link.url, label: text.slice(link.offset, link.offset + link.length) });
|
|
104
|
+
used += size;
|
|
105
|
+
}
|
|
106
|
+
if (omitted) {
|
|
107
|
+
used += (entries.length ? 1 : 0) + 1;
|
|
108
|
+
}
|
|
109
|
+
let spare = REPLY_TO_MAX_CHARS - used;
|
|
110
|
+
const lines = entries.map(({ url, label }) => {
|
|
111
|
+
const kept = truncateReplyText(label, Math.min(64, spare - 1));
|
|
112
|
+
spare -= kept ? kept.length + 1 : 0;
|
|
113
|
+
return `${kept ? `${kept} ` : ''}<${url}>`;
|
|
114
|
+
});
|
|
115
|
+
if (omitted) lines.push('…');
|
|
116
|
+
const targets = prefix + lines.join('\n');
|
|
117
|
+
const surrounding = truncateReplyText(text, REPLY_TO_MAX_CHARS - targets.length - 1);
|
|
118
|
+
return [surrounding, targets].filter(Boolean).join('\n');
|
|
80
119
|
}
|
|
81
120
|
|
|
82
121
|
/**
|
|
@@ -98,7 +137,7 @@ function buildReplyToBlock(input) {
|
|
|
98
137
|
const msgId = telegram.message_id;
|
|
99
138
|
const user = telegram.from?.first_name || telegram.from?.username || 'Unknown';
|
|
100
139
|
const ts = telegram.date ? new Date(telegram.date * 1000).toISOString() : '';
|
|
101
|
-
const text =
|
|
140
|
+
const text = telegramReplyText(telegram);
|
|
102
141
|
const hasMedia = !!(telegram.document || telegram.photo || telegram.voice || telegram.audio || telegram.video);
|
|
103
142
|
const summary = hasMedia ? summarizeTelegramAttachments(telegram) : '';
|
|
104
143
|
const body = [text, summary].filter(Boolean).join('\n');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.47.
|
|
3
|
+
"version": "0.47.2",
|
|
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.3",
|
|
75
75
|
"acorn": "8.18.0",
|
|
76
76
|
"better-sqlite3": "^12.9.0",
|
|
77
77
|
"grammy": "^1.42.0",
|
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
|
},
|