polygram 0.41.2 → 0.41.4
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/lib/db/event-detail-schema.js +11 -0
- package/lib/error/classify.js +67 -2
- package/lib/handlers/dispatcher.js +23 -12
- package/lib/handlers/poll.js +2 -1
- package/lib/ops/clean-resume.js +16 -4
- package/lib/sdk/callbacks.js +70 -0
- package/lib/telegram/chunk.js +1 -0
- package/lib/telegram/rich-inbound.js +254 -0
- package/lib/telegram/turn-error-exit.js +68 -0
- package/package.json +2 -2
- package/polygram.js +29 -35
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://anthropic.com/claude-code/plugin.schema.json",
|
|
3
3
|
"name": "polygram",
|
|
4
|
-
"version": "0.41.
|
|
4
|
+
"version": "0.41.4",
|
|
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",
|
|
@@ -151,6 +151,8 @@ const FIELDS = {
|
|
|
151
151
|
expected: 'id',
|
|
152
152
|
topic_ids: 'ids',
|
|
153
153
|
pending_turn_ids: 'ids',
|
|
154
|
+
// The follow-up message ids a failed own-cycle query is answering.
|
|
155
|
+
anchor_msg_ids: 'ids',
|
|
154
156
|
fields: 'ids',
|
|
155
157
|
reasons: 'ids',
|
|
156
158
|
signals: 'ids',
|
|
@@ -222,6 +224,11 @@ const FIELDS = {
|
|
|
222
224
|
error_name: 'code',
|
|
223
225
|
errCode: 'code',
|
|
224
226
|
api_error_code: 'code',
|
|
227
|
+
// Orchestra flags a CLI error class outside the pinned enum (reported as
|
|
228
|
+
// 'unknown'), so a CLI bump that adds classes shows up in telemetry.
|
|
229
|
+
api_error_unlisted: 'bool',
|
|
230
|
+
// cli-open-prompt-evicted: whether the evicted prompt belonged to a turn.
|
|
231
|
+
turn_owned: 'bool',
|
|
225
232
|
queue_drain_error_code: 'code',
|
|
226
233
|
stop_error_code: 'code',
|
|
227
234
|
feedback_clear_error_code: 'code',
|
|
@@ -295,6 +302,10 @@ const FIELDS = {
|
|
|
295
302
|
shell_count: 'int',
|
|
296
303
|
open_count: 'int',
|
|
297
304
|
pending_count: 'int',
|
|
305
|
+
// A failed query's StopFailure closes its prompt and every older open one
|
|
306
|
+
// (claude runs queued prompts as one query); an evicted prompt's follow-ups.
|
|
307
|
+
closed_prompt_count: 'int',
|
|
308
|
+
follow_up_count: 'int',
|
|
298
309
|
pending_turns: 'int',
|
|
299
310
|
queue_len: 'int',
|
|
300
311
|
queue_cap: 'int',
|
package/lib/error/classify.js
CHANGED
|
@@ -399,6 +399,54 @@ const CODES = {
|
|
|
399
399
|
},
|
|
400
400
|
};
|
|
401
401
|
|
|
402
|
+
// CLAUDE_API_ERROR: on the CLI backend, claude retried a failing model request
|
|
403
|
+
// until it gave up (it reports the end through its StopFailure hook) and the
|
|
404
|
+
// turn ended without finishing. Orchestra puts claude's error class on
|
|
405
|
+
// err.apiError; the message carries no provider text. The copy is grouped by
|
|
406
|
+
// what the user can do, not by the reported class: a proxy whose credentials
|
|
407
|
+
// expired reports `server_error`, so the class is not a reliable cause.
|
|
408
|
+
// Nothing here retries or resets the session — the user decides to resend.
|
|
409
|
+
const CLAUDE_API_ERROR_COPY = Object.freeze({
|
|
410
|
+
temporary: '☁️ Claude\'s API kept failing, even after retrying, so I couldn\'t finish this. Please try again in a few minutes.',
|
|
411
|
+
// A subscription usage cap can last hours; "a few minutes" would send the
|
|
412
|
+
// user straight back into it.
|
|
413
|
+
rateLimit: '⏳ I\'ve hit Claude\'s usage limit, so I couldn\'t finish this. It can take a few hours to reset; please try again later.',
|
|
414
|
+
account: '🔑 Claude refused this request because of an account or configuration problem on my side, so I couldn\'t finish this. Please try again later.',
|
|
415
|
+
rejected: '⚠️ Claude rejected this request, so I couldn\'t finish it. If it keeps happening, send /new to start a fresh session.',
|
|
416
|
+
outputLimit: '⚠️ Claude\'s reply hit its output limit and stopped. Ask me to continue, or split the request into smaller steps.',
|
|
417
|
+
});
|
|
418
|
+
// Unlisted classes (server_error, overloaded, unknown, anything newer) read as
|
|
419
|
+
// temporary. Null prototype: a class is matched only as an own
|
|
420
|
+
// key, never through Object.prototype.
|
|
421
|
+
const CLAUDE_API_ERROR_GROUP = Object.freeze(Object.assign(Object.create(null), {
|
|
422
|
+
authentication_failed: 'account',
|
|
423
|
+
cloud_credential_error: 'account',
|
|
424
|
+
verification_required: 'account',
|
|
425
|
+
billing_error: 'account',
|
|
426
|
+
account_on_hold: 'account',
|
|
427
|
+
model_not_found: 'account',
|
|
428
|
+
invalid_request: 'rejected',
|
|
429
|
+
max_output_tokens: 'outputLimit',
|
|
430
|
+
rate_limit: 'rateLimit',
|
|
431
|
+
}));
|
|
432
|
+
|
|
433
|
+
function classifyClaudeApiError(apiError) {
|
|
434
|
+
// An org that disabled subscription access is the AUTH_DISABLED condition:
|
|
435
|
+
// the chat is told nothing. Orchestra rejects a pending turn with that code,
|
|
436
|
+
// which is where the dispatcher notifies the operator; this covers the same
|
|
437
|
+
// class arriving any other way (it only keeps the chat silent).
|
|
438
|
+
if (apiError === 'oauth_org_not_allowed') return { ...CODES.AUTH_DISABLED };
|
|
439
|
+
const group = typeof apiError === 'string' && Object.hasOwn(CLAUDE_API_ERROR_GROUP, apiError)
|
|
440
|
+
? CLAUDE_API_ERROR_GROUP[apiError]
|
|
441
|
+
: 'temporary';
|
|
442
|
+
return {
|
|
443
|
+
kind: 'claudeApiError',
|
|
444
|
+
userMessage: CLAUDE_API_ERROR_COPY[group],
|
|
445
|
+
isTransient: false,
|
|
446
|
+
autoRecover: null,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
402
450
|
/**
|
|
403
451
|
* Classify an error from any source.
|
|
404
452
|
*
|
|
@@ -432,6 +480,9 @@ function classify(err) {
|
|
|
432
480
|
) {
|
|
433
481
|
return { ...CODEX_ERROR_SHAPES.rateLimit };
|
|
434
482
|
}
|
|
483
|
+
if (code === 'CLAUDE_API_ERROR') {
|
|
484
|
+
return classifyClaudeApiError(err?.apiError);
|
|
485
|
+
}
|
|
435
486
|
if (code && CODES[code]) {
|
|
436
487
|
return { ...CODES[code] };
|
|
437
488
|
}
|
|
@@ -606,9 +657,11 @@ function detectWedgedSessionError(text) {
|
|
|
606
657
|
* cap the bubble + set the reactor when a turn ends in error. Extracted as a
|
|
607
658
|
* pure fn so the decision is unit-testable (the catch itself isn't unit-reachable).
|
|
608
659
|
*
|
|
609
|
-
* Returns { errorSuffix, reactorState }:
|
|
610
|
-
* - errorSuffix: appended to
|
|
660
|
+
* Returns { errorSuffix, reactorState, suffixMessage? }:
|
|
661
|
+
* - errorSuffix: appended to the finalized preview (null = no suffix)
|
|
611
662
|
* - reactorState: reactor.setState(...) value
|
|
663
|
+
* - suffixMessage: false = when the turn already delivered replies, do not
|
|
664
|
+
* send the suffix as a separate message (absent = send it)
|
|
612
665
|
*
|
|
613
666
|
* Turn-end timeouts (TURN_TIMEOUT = went quiet, TURN_MAX_EXCEEDED = hit hard cap)
|
|
614
667
|
* are real stops → the "stream interrupted" suffix is honest here. Note: the cli
|
|
@@ -618,6 +671,18 @@ function detectWedgedSessionError(text) {
|
|
|
618
671
|
*/
|
|
619
672
|
function classifyTurnEndError(err) {
|
|
620
673
|
const code = err?.code;
|
|
674
|
+
// The classified error reply (dispatcher) is this turn's one error message.
|
|
675
|
+
// When the turn delivered nothing, a partial preview still gets the
|
|
676
|
+
// in-bubble suffix so it does not read as a finished answer; when it did
|
|
677
|
+
// deliver replies, no separate "stream interrupted" message follows them.
|
|
678
|
+
if (code === 'CLAUDE_API_ERROR') {
|
|
679
|
+
return { errorSuffix: 'stream interrupted', reactorState: 'ERROR', suffixMessage: false };
|
|
680
|
+
}
|
|
681
|
+
// AUTH_DISABLED: the chat is told nothing (the dispatcher notifies the
|
|
682
|
+
// operator), so neither the in-bubble suffix nor a separate message.
|
|
683
|
+
if (code === 'AUTH_DISABLED') {
|
|
684
|
+
return { errorSuffix: null, reactorState: 'ERROR', suffixMessage: false };
|
|
685
|
+
}
|
|
621
686
|
// The cli backend sets err.code (TURN_TIMEOUT / TURN_MAX_EXCEEDED). The SDK +
|
|
622
687
|
// tmux backends reject with a MESSAGE and NO code (e.g. "Turn exceeded 1800s
|
|
623
688
|
// wall-clock ceiling" / "Timeout: 600s idle with no Claude activity"), so we
|
|
@@ -362,6 +362,9 @@ function createDispatcher({
|
|
|
362
362
|
error_len: err.message?.length ?? 0,
|
|
363
363
|
code: err.code || undefined,
|
|
364
364
|
cause_code: err.cause?.code || undefined,
|
|
365
|
+
// claude's error class when the turn ended in an API error (an enum
|
|
366
|
+
// Orchestra already clamps; the schema types it as a code).
|
|
367
|
+
api_error_code: err.apiError || undefined,
|
|
365
368
|
// A spawn failure's stderr is process output, not a field: its size
|
|
366
369
|
// says whether the child said anything at all, which is the signal
|
|
367
370
|
// that distinguishes "tmux refused" from "tmux said nothing".
|
|
@@ -467,18 +470,26 @@ function createDispatcher({
|
|
|
467
470
|
&& err.code !== 'AUTH_DISABLED'
|
|
468
471
|
&& !cleanReplayProcessDrift
|
|
469
472
|
) {
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
473
|
+
// A replay that hit a failing Claude API is not the message's fault —
|
|
474
|
+
// "rephrase or simplify" would mislead; say what actually happened.
|
|
475
|
+
const replayText = err.code === 'CLAUDE_API_ERROR'
|
|
476
|
+
? errorReplyText(err)
|
|
477
|
+
: '⚠️ This turn was interrupted and didn\'t complete on retry — please rephrase or simplify, or split into smaller steps.';
|
|
478
|
+
// null = a class whose chat must not be told (see classify.js).
|
|
479
|
+
if (replayText) {
|
|
480
|
+
tg(bot, 'sendMessage', {
|
|
481
|
+
chat_id: chatId,
|
|
482
|
+
text: replayText,
|
|
483
|
+
reply_parameters: { message_id: msg.message_id },
|
|
484
|
+
}, {
|
|
485
|
+
source: 'error-reply',
|
|
486
|
+
botName,
|
|
487
|
+
sessionKey,
|
|
488
|
+
sourceMsgId: msg.message_id,
|
|
489
|
+
}).catch((replyErr) => {
|
|
490
|
+
logger.error?.(`[${sessionKey}] failed to send replay-failure reply: ${replyErr.message}`);
|
|
491
|
+
});
|
|
492
|
+
}
|
|
482
493
|
}
|
|
483
494
|
// Suppress the user-facing error reply when:
|
|
484
495
|
// - boot replay (handled above),
|
package/lib/handlers/poll.js
CHANGED
|
@@ -133,7 +133,8 @@ function createPollLoop({
|
|
|
133
133
|
: null;
|
|
134
134
|
const chatLabel = chatConfig?.name || chatId;
|
|
135
135
|
const label = topicName ? `${chatLabel}/${topicName}` : chatLabel;
|
|
136
|
-
|
|
136
|
+
const preview = m.text || m.caption || (m.rich_message ? '(rich message)' : '(media)');
|
|
137
|
+
logger.log?.(`[${botName}] ← ${label}: ${preview.slice(0, 60)}`);
|
|
137
138
|
}
|
|
138
139
|
try {
|
|
139
140
|
await bot.handleUpdate(update);
|
package/lib/ops/clean-resume.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { classify } = require('../error/classify');
|
|
4
|
+
|
|
3
5
|
const CLAUDE_NAMESPACE = 'claude:channels';
|
|
4
6
|
const CODEX_NAMESPACE = 'codex:app-server';
|
|
5
7
|
const CLEAN_RESUME_POLICY_VERSION = 2;
|
|
@@ -162,9 +164,9 @@ async function executeCleanResumeClaim(claim, {
|
|
|
162
164
|
? loadSource(claim.source_message_id)
|
|
163
165
|
: null;
|
|
164
166
|
|
|
165
|
-
async function fallback(reason, { ambiguous = false } = {}) {
|
|
167
|
+
async function fallback(reason, { ambiguous = false, text: noticeText = null } = {}) {
|
|
166
168
|
markReady();
|
|
167
|
-
const text = recoveryNoticeText({ ambiguous });
|
|
169
|
+
const text = noticeText || recoveryNoticeText({ ambiguous });
|
|
168
170
|
await sendNotice({
|
|
169
171
|
claim,
|
|
170
172
|
source,
|
|
@@ -192,13 +194,14 @@ async function executeCleanResumeClaim(claim, {
|
|
|
192
194
|
return fallback(reason);
|
|
193
195
|
}
|
|
194
196
|
|
|
195
|
-
function failed(reason, { ambiguous = false } = {}) {
|
|
197
|
+
function failed(reason, { ambiguous = false, text = null, apiErrorCode = undefined } = {}) {
|
|
196
198
|
logEvent('clean-resume-failed', {
|
|
197
199
|
...eventDetail,
|
|
198
200
|
reason,
|
|
199
201
|
ambiguous: ambiguous || undefined,
|
|
202
|
+
api_error_code: apiErrorCode,
|
|
200
203
|
});
|
|
201
|
-
return fallback(reason, { ambiguous });
|
|
204
|
+
return fallback(reason, { ambiguous, text });
|
|
202
205
|
}
|
|
203
206
|
|
|
204
207
|
if (!enabled) return fallback('rollout-disabled');
|
|
@@ -312,6 +315,15 @@ async function executeCleanResumeClaim(claim, {
|
|
|
312
315
|
} catch (error) {
|
|
313
316
|
markReady();
|
|
314
317
|
const ambiguous = error?.deliveryAmbiguous === true;
|
|
318
|
+
// The resume worked and the continuation reached claude, which then gave
|
|
319
|
+
// up on a failing API: say that (the same copy a live turn gets), not
|
|
320
|
+
// that resuming was unsafe.
|
|
321
|
+
if (!ambiguous && error?.code === 'CLAUDE_API_ERROR') {
|
|
322
|
+
return failed('continuation-api-error', {
|
|
323
|
+
text: classify(error).userMessage,
|
|
324
|
+
apiErrorCode: error.apiError,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
315
327
|
return failed(
|
|
316
328
|
ambiguous ? 'continuation-delivery-ambiguous' : 'continuation-failed',
|
|
317
329
|
{ ambiguous },
|
package/lib/sdk/callbacks.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
'use strict';
|
|
22
22
|
|
|
23
23
|
const { getTopicConfig } = require('../session-key');
|
|
24
|
+
const { classify: classifyError } = require('../error/classify');
|
|
24
25
|
const { pickBackend } = require('@shumkov/orchestra');
|
|
25
26
|
const {
|
|
26
27
|
isCodexProcess,
|
|
@@ -66,6 +67,10 @@ function createSdkCallbacks({
|
|
|
66
67
|
// self-checks, injected messages picked up as their own cycle). Optional.
|
|
67
68
|
sessionFeedback = null,
|
|
68
69
|
deliveryBarrier = null,
|
|
70
|
+
// Gates for the API-error notice of a cycle with no pending turn: never
|
|
71
|
+
// speak while the daemon shuts down or right after the user's /stop.
|
|
72
|
+
getIsShuttingDown = () => false,
|
|
73
|
+
isSessionRecentlyAborted = () => false,
|
|
69
74
|
logger = console,
|
|
70
75
|
} = {}) {
|
|
71
76
|
// 0.13 P4: the rc.9 extraTurnTracker (tmux NEW-TURN typing/✍ bridge) was
|
|
@@ -407,6 +412,71 @@ function createSdkCallbacks({
|
|
|
407
412
|
catch (err) { logger.error?.(`[${botName}] onIdle failed: ${err.message}`); }
|
|
408
413
|
},
|
|
409
414
|
|
|
415
|
+
// A failed claude query ran cycles that no pending turn runs in — most
|
|
416
|
+
// often follow-ups that were autosteered into a turn that then failed,
|
|
417
|
+
// running afterwards as their own cycle (claude runs several queued ones
|
|
418
|
+
// as one query). Nobody else will answer those messages, so reply to each
|
|
419
|
+
// with the same copy a failed turn gets. A cycle that picked up no user
|
|
420
|
+
// message (a wakeup) only ends its visuals.
|
|
421
|
+
// (Failed pending turns reject instead and go through the dispatcher.)
|
|
422
|
+
onApiError: (sessionKey, payload /* , entry */) => {
|
|
423
|
+
// Visuals first and on their own: a failure here must not cost the user
|
|
424
|
+
// the notice, and a skipped notice must still stop typing.
|
|
425
|
+
try { sessionFeedback?.endCycle(sessionKey); }
|
|
426
|
+
catch (err) { logger.error?.(`[${botName}] onApiError endCycle failed: ${err.message}`); }
|
|
427
|
+
try {
|
|
428
|
+
const chatId = getChatIdFromKey(sessionKey);
|
|
429
|
+
const threadIdRaw = getThreadIdFromKey(sessionKey);
|
|
430
|
+
const threadId = threadIdRaw ? parseInt(threadIdRaw, 10) : null;
|
|
431
|
+
const anchors = Array.isArray(payload?.anchorMsgIds) ? payload.anchorMsgIds : [];
|
|
432
|
+
const { userMessage } = classifyError({ code: 'CLAUDE_API_ERROR', apiError: payload?.apiError });
|
|
433
|
+
// Why nothing may be sent, whichever message it would answer.
|
|
434
|
+
let gate = null;
|
|
435
|
+
if (!userMessage) {
|
|
436
|
+
// AUTH_DISABLED keeps the chat silent; the operator is notified when a
|
|
437
|
+
// pending turn fails with that code (dispatcher), not from here.
|
|
438
|
+
gate = payload?.apiError === 'oauth_org_not_allowed' ? 'auth-disabled' : 'suppressed';
|
|
439
|
+
}
|
|
440
|
+
else if (!bot) gate = 'no-bot';
|
|
441
|
+
else if (getIsShuttingDown()) gate = 'shutting-down';
|
|
442
|
+
else if (isSessionRecentlyAborted(sessionKey)) gate = 'aborted';
|
|
443
|
+
const logOutcome = (outcome, anchor) => logEvent('cli-cycle-api-error', {
|
|
444
|
+
chat_id: chatId,
|
|
445
|
+
session_key: sessionKey,
|
|
446
|
+
thread_id: threadIdRaw,
|
|
447
|
+
api_error_code: payload?.apiError,
|
|
448
|
+
anchor_msg_id: Number.isSafeInteger(anchor) ? anchor : undefined,
|
|
449
|
+
outcome,
|
|
450
|
+
});
|
|
451
|
+
if (anchors.length === 0) {
|
|
452
|
+
logOutcome('no-anchor');
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
for (const raw of anchors) {
|
|
456
|
+
const anchor = raw == null || raw === '' ? NaN : Number(raw);
|
|
457
|
+
const outcome = !(Number.isSafeInteger(anchor) && anchor > 0) ? 'bad-anchor' : (gate || 'replied');
|
|
458
|
+
logOutcome(outcome, anchor);
|
|
459
|
+
if (outcome !== 'replied') continue;
|
|
460
|
+
tg(bot, 'sendMessage', {
|
|
461
|
+
chat_id: chatId,
|
|
462
|
+
text: userMessage,
|
|
463
|
+
...(Number.isInteger(threadId) && { message_thread_id: threadId }),
|
|
464
|
+
// The follow-up may be minutes old (or deleted) by now.
|
|
465
|
+
reply_parameters: { message_id: anchor, allow_sending_without_reply: true },
|
|
466
|
+
}, {
|
|
467
|
+
source: 'error-reply',
|
|
468
|
+
botName,
|
|
469
|
+
sessionKey,
|
|
470
|
+
sourceMsgId: anchor,
|
|
471
|
+
}).catch((err) => {
|
|
472
|
+
logger.error?.(`[${botName}] api-error notice send failed: ${err.message}`);
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
} catch (err) {
|
|
476
|
+
logger.error?.(`[${botName}] onApiError failed: ${err.message}`);
|
|
477
|
+
}
|
|
478
|
+
},
|
|
479
|
+
|
|
410
480
|
onQuestionResumed: (sessionKey, entry) => {
|
|
411
481
|
try {
|
|
412
482
|
const ctx = entry?.pendingQueue?.[0]?.context;
|
package/lib/telegram/chunk.js
CHANGED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Inbound rich messages → plain text.
|
|
5
|
+
*
|
|
6
|
+
* Telegram delivers a rich message as `Message.rich_message`
|
|
7
|
+
* ({ blocks: RichBlock[] }) with no `text` and no `caption`. Everything
|
|
8
|
+
* after intake (the stored row, the gate, the prompt, replay, history) reads
|
|
9
|
+
* `msg.text`, so intake renders the block tree into it once.
|
|
10
|
+
*
|
|
11
|
+
* The output is plain text with just enough markdown structure (headings,
|
|
12
|
+
* list markers, quotes, code fences, table rows, link targets) for the agent
|
|
13
|
+
* to read the message the way the user saw it. Media inside blocks is not
|
|
14
|
+
* downloaded; a placeholder says it was there and was not attached.
|
|
15
|
+
*
|
|
16
|
+
* The outbound direction (markdown → blocks) lives in ./rich.js. Its
|
|
17
|
+
* flattenRichText keeps only the visible text, which is right for a styling
|
|
18
|
+
* retry but loses what the agent needs here: link targets, custom-emoji alt
|
|
19
|
+
* text and math expressions.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const { surrogateSafeCut } = require('./chunk');
|
|
23
|
+
|
|
24
|
+
// Telegram allows 16 levels of nested formatting and blocks. Blocks, inline
|
|
25
|
+
// nodes and the arrays wrapping them each count one level here, so legal
|
|
26
|
+
// input can reach about 33; past 64 the tree is malformed and that branch
|
|
27
|
+
// stops rendering instead of recursing further.
|
|
28
|
+
const MAX_DEPTH = 64;
|
|
29
|
+
|
|
30
|
+
// Quote prefixes and list indents repeat per nesting level, so a message
|
|
31
|
+
// within Telegram's own 32,768-character limit can render many times larger.
|
|
32
|
+
// Hold the rendered text to that same budget.
|
|
33
|
+
const MAX_RENDERED_CHARS = 32_768;
|
|
34
|
+
const TRUNCATED_MARKER = '\n[rich message truncated]';
|
|
35
|
+
|
|
36
|
+
// Every rendered message starts with this line. Command, abort and pairing
|
|
37
|
+
// matchers all anchor at the start of the text, so content the sender may
|
|
38
|
+
// not even have seen (a collapsed details block, say) can never be read as
|
|
39
|
+
// "/new" or "stop". It also tells the agent the text was derived from blocks.
|
|
40
|
+
const RICH_TEXT_HEADER = '[rich message]';
|
|
41
|
+
|
|
42
|
+
function str(v) {
|
|
43
|
+
return typeof v === 'string' ? v : '';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function inlineText(node, depth = 0) {
|
|
47
|
+
if (node == null || depth > MAX_DEPTH) return '';
|
|
48
|
+
if (typeof node === 'string') return node;
|
|
49
|
+
if (Array.isArray(node)) return node.map((n) => inlineText(n, depth + 1)).join('');
|
|
50
|
+
if (typeof node !== 'object') return '';
|
|
51
|
+
switch (node.type) {
|
|
52
|
+
case 'custom_emoji': return str(node.alternative_text);
|
|
53
|
+
case 'mathematical_expression': return node.expression ? `$${str(node.expression)}$` : '';
|
|
54
|
+
case 'button': return buttonText(node.button, depth + 1);
|
|
55
|
+
case 'anchor': return '';
|
|
56
|
+
case 'url': {
|
|
57
|
+
const label = inlineText(node.text, depth + 1);
|
|
58
|
+
const url = str(node.url);
|
|
59
|
+
// Keep the link target: the agent can't click the visible label.
|
|
60
|
+
if (!url || url === label) return label;
|
|
61
|
+
return label ? `[${label}](${url})` : url;
|
|
62
|
+
}
|
|
63
|
+
default: return inlineText(node.text, depth + 1);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function buttonText(button, depth = 0) {
|
|
68
|
+
const label = `[button: ${inlineText(button?.text, depth)}]`;
|
|
69
|
+
return str(button?.url) ? `${label}(${button.url})` : label;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// RichBlockCaption is { text, credit? }; a table caption is bare RichText.
|
|
73
|
+
function captionText(caption, depth) {
|
|
74
|
+
if (caption && typeof caption === 'object' && !Array.isArray(caption) && caption.type == null) {
|
|
75
|
+
const text = inlineText(caption.text, depth);
|
|
76
|
+
const credit = inlineText(caption.credit, depth);
|
|
77
|
+
return credit ? `${text} — ${credit}` : text;
|
|
78
|
+
}
|
|
79
|
+
return inlineText(caption, depth);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Every line gets a marker, blank ones included, so a multi-paragraph quote
|
|
83
|
+
// stays one quote.
|
|
84
|
+
function quote(body, credit, depth) {
|
|
85
|
+
const by = inlineText(credit, depth);
|
|
86
|
+
return [body, by && `— ${by}`].filter(Boolean).join('\n')
|
|
87
|
+
.split('\n').map((line) => (line ? `> ${line}` : '>')).join('\n');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function renderList(items, depth) {
|
|
91
|
+
if (!Array.isArray(items)) return '';
|
|
92
|
+
return items.map((item) => {
|
|
93
|
+
if (!item || typeof item !== 'object') return '';
|
|
94
|
+
const box = item.has_checkbox ? (item.is_checked ? '[x] ' : '[ ] ') : '';
|
|
95
|
+
const head = `${str(item.label) || '-'} ${box}`;
|
|
96
|
+
const body = renderBlocks(item.blocks, depth, '\n');
|
|
97
|
+
const [first = '', ...rest] = body.split('\n');
|
|
98
|
+
return [(head + first).trimEnd(), ...rest.map((line) => (line ? ` ${line}` : line))].join('\n');
|
|
99
|
+
}).filter(Boolean).join('\n');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function renderTable(block, depth) {
|
|
103
|
+
const rows = Array.isArray(block.cells) ? block.cells : [];
|
|
104
|
+
const lines = rows.map((row) => (Array.isArray(row) ? row : []).flatMap((cell) => {
|
|
105
|
+
const text = inlineText(cell?.text, depth).replace(/\n+/g, ' ');
|
|
106
|
+
// Pad a column-spanning cell so the cells after it in the row stay under
|
|
107
|
+
// their headers. Row spans are not reconstructed.
|
|
108
|
+
const span = Math.min(Math.max(Math.trunc(Number(cell?.colspan)) || 1, 1), 20);
|
|
109
|
+
return [text, ...Array(span - 1).fill('')];
|
|
110
|
+
}).join(' | '));
|
|
111
|
+
return [captionText(block.caption, depth), ...lines].filter(Boolean).join('\n');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// A fence longer than any backtick run in the code, so the code can't close it.
|
|
115
|
+
function fence(code, language) {
|
|
116
|
+
const longest = (code.match(/`+/g) || []).reduce((max, run) => Math.max(max, run.length), 0);
|
|
117
|
+
const ticks = '`'.repeat(Math.max(3, longest + 1));
|
|
118
|
+
return `${ticks}${language}\n${code}\n${ticks}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function mediaLabel(block) {
|
|
122
|
+
const media = block[block.type];
|
|
123
|
+
const named = (kind, name) => (name ? `${kind}: ${name}` : kind);
|
|
124
|
+
let label;
|
|
125
|
+
switch (block.type) {
|
|
126
|
+
case 'photo': label = 'photo'; break;
|
|
127
|
+
case 'animation': label = 'animation'; break;
|
|
128
|
+
case 'voice_note': label = 'voice'; break;
|
|
129
|
+
case 'video': label = named('video', str(media?.file_name)); break;
|
|
130
|
+
case 'audio': label = named('audio', str(media?.title) || str(media?.file_name)); break;
|
|
131
|
+
case 'document': label = named('document', str(media?.file_name)); break;
|
|
132
|
+
default: return null;
|
|
133
|
+
}
|
|
134
|
+
return `[${label} — not attached]`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function renderBlock(block, depth) {
|
|
138
|
+
if (!block || typeof block !== 'object' || depth > MAX_DEPTH) return '';
|
|
139
|
+
const media = mediaLabel(block);
|
|
140
|
+
if (media) {
|
|
141
|
+
const caption = captionText(block.caption, depth);
|
|
142
|
+
return caption ? `${media} ${caption}` : media;
|
|
143
|
+
}
|
|
144
|
+
switch (block.type) {
|
|
145
|
+
case 'paragraph':
|
|
146
|
+
case 'footer':
|
|
147
|
+
return inlineText(block.text, depth);
|
|
148
|
+
case 'heading': {
|
|
149
|
+
const text = inlineText(block.text, depth);
|
|
150
|
+
const level = Math.min(6, Math.max(1, Math.trunc(Number(block.size)) || 1));
|
|
151
|
+
return text && `${'#'.repeat(level)} ${text}`;
|
|
152
|
+
}
|
|
153
|
+
case 'pre':
|
|
154
|
+
return fence(inlineText(block.text, depth), str(block.language).replace(/[\s`]/g, ''));
|
|
155
|
+
case 'divider':
|
|
156
|
+
return '---';
|
|
157
|
+
case 'mathematical_expression':
|
|
158
|
+
return block.expression ? `$$${str(block.expression)}$$` : '';
|
|
159
|
+
case 'anchor':
|
|
160
|
+
return '';
|
|
161
|
+
case 'list':
|
|
162
|
+
return renderList(block.items, depth);
|
|
163
|
+
case 'blockquote':
|
|
164
|
+
return quote(renderBlocks(block.blocks, depth), block.credit, depth);
|
|
165
|
+
case 'expandable_blockquote':
|
|
166
|
+
case 'pullquote':
|
|
167
|
+
return quote(inlineText(block.text, depth), block.credit, depth);
|
|
168
|
+
case 'collage':
|
|
169
|
+
case 'slideshow':
|
|
170
|
+
return [renderBlocks(block.blocks, depth), captionText(block.caption, depth)].filter(Boolean).join('\n');
|
|
171
|
+
case 'table':
|
|
172
|
+
return renderTable(block, depth);
|
|
173
|
+
case 'details':
|
|
174
|
+
return [inlineText(block.summary, depth), renderBlocks(block.blocks, depth)].filter(Boolean).join('\n');
|
|
175
|
+
case 'map': {
|
|
176
|
+
const loc = block.location;
|
|
177
|
+
const where = loc && Number.isFinite(loc.latitude) && Number.isFinite(loc.longitude)
|
|
178
|
+
? `[map: ${loc.latitude},${loc.longitude}]`
|
|
179
|
+
: '[map]';
|
|
180
|
+
const caption = captionText(block.caption, depth);
|
|
181
|
+
return caption ? `${where} ${caption}` : where;
|
|
182
|
+
}
|
|
183
|
+
case 'buttons':
|
|
184
|
+
return (Array.isArray(block.buttons) ? block.buttons : [])
|
|
185
|
+
.map((button) => buttonText(button, depth))
|
|
186
|
+
.join(' ');
|
|
187
|
+
default: {
|
|
188
|
+
// A block type newer than this renderer: keep whatever readable content
|
|
189
|
+
// it carries rather than dropping the message's text on the floor.
|
|
190
|
+
const parts = [
|
|
191
|
+
inlineText(block.text, depth),
|
|
192
|
+
renderBlocks(block.blocks, depth),
|
|
193
|
+
renderList(block.items, depth),
|
|
194
|
+
captionText(block.caption, depth),
|
|
195
|
+
].filter(Boolean);
|
|
196
|
+
if (parts.length) return parts.join('\n');
|
|
197
|
+
return typeof block.type === 'string' ? `[${block.type}]` : '';
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function renderBlocks(blocks, depth, separator = '\n\n') {
|
|
203
|
+
if (!Array.isArray(blocks) || depth > MAX_DEPTH) return '';
|
|
204
|
+
return blocks.map((b) => renderBlock(b, depth + 1)).filter(Boolean).join(separator);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Render a RichMessage ({ blocks, is_rtl? }) to plain text. Never throws on
|
|
209
|
+
* malformed input; returns '' when there is nothing readable.
|
|
210
|
+
*/
|
|
211
|
+
function richMessageToText(richMessage) {
|
|
212
|
+
if (!richMessage || typeof richMessage !== 'object') return '';
|
|
213
|
+
const text = renderBlocks(richMessage.blocks, 0).trim();
|
|
214
|
+
if (text.length <= MAX_RENDERED_CHARS) return text;
|
|
215
|
+
return text.slice(0, surrogateSafeCut(text, MAX_RENDERED_CHARS)) + TRUNCATED_MARKER;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function renderInto(msg) {
|
|
219
|
+
if (!msg || typeof msg !== 'object' || msg.text || msg.caption || !msg.rich_message) return;
|
|
220
|
+
const text = richMessageToText(msg.rich_message);
|
|
221
|
+
if (text) msg.text = `${RICH_TEXT_HEADER}\n${text}`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Give a rich message (and the rich message it replies to) a `text`, so
|
|
226
|
+
* every reader after intake sees its content. Mutates and returns `msg`.
|
|
227
|
+
* A message that already has `text` or `caption` is left alone.
|
|
228
|
+
*
|
|
229
|
+
* A rich message sent by another bot stays without text, as before: AI bots
|
|
230
|
+
* reply in rich messages, and dispatching them would let two bots in a group
|
|
231
|
+
* answer each other turn after turn. A user forwarding a bot's message is
|
|
232
|
+
* the sender here, so forwards still render. So do anonymous admins and
|
|
233
|
+
* channel posts: Telegram sends those from a placeholder bot account with
|
|
234
|
+
* `sender_chat` set, but a person wrote them.
|
|
235
|
+
*/
|
|
236
|
+
function normalizeRichInbound(msg, { logger = console } = {}) {
|
|
237
|
+
const fromOtherBot = msg?.from?.is_bot === true && !msg?.sender_chat;
|
|
238
|
+
const targets = [fromOtherBot ? null : msg, msg?.reply_to_message];
|
|
239
|
+
for (const target of targets) {
|
|
240
|
+
try {
|
|
241
|
+
renderInto(target);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
logger.error?.(`rich message ${target?.message_id ?? '?'} could not be rendered: ${err?.message || err}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return msg;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
module.exports = {
|
|
250
|
+
richMessageToText,
|
|
251
|
+
normalizeRichInbound,
|
|
252
|
+
RICH_TEXT_HEADER,
|
|
253
|
+
MAX_RENDERED_CHARS,
|
|
254
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* How a streamed turn's preview is settled when the turn ends in an error
|
|
5
|
+
* (polygram.js handleMessage's catch).
|
|
6
|
+
*
|
|
7
|
+
* A turn that already delivered replies and THEN failed must not restate
|
|
8
|
+
* them: finalize(null) publishes whatever the draft holds, which on a CLI turn
|
|
9
|
+
* is usually the answer a reply already sent. So when the turn delivered
|
|
10
|
+
* anything, the exit settles through the turn settler instead and, unless told
|
|
11
|
+
* otherwise, sends the suffix as its own short message. With nothing
|
|
12
|
+
* delivered, the partial bubble is finalized in place and carries the suffix.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const { classifyTurnEndError } = require('../error/classify');
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {object} deps
|
|
19
|
+
* @param {() => boolean} deps.hasDeliveredReplies
|
|
20
|
+
* @param {() => Promise<unknown>} deps.finishStreamer - the turn settler
|
|
21
|
+
* @param {{ finalize: Function }} deps.streamer
|
|
22
|
+
* @param {(text: string) => Promise<unknown>} deps.sendSuffixMessage
|
|
23
|
+
* @param {(msgId: number, text: string) => void} deps.persistBubbleText
|
|
24
|
+
* @returns {(errorSuffix: string|null, opts?: { suffixMessage?: boolean }) => Promise<void>}
|
|
25
|
+
*/
|
|
26
|
+
function createTurnErrorExit({
|
|
27
|
+
hasDeliveredReplies,
|
|
28
|
+
finishStreamer,
|
|
29
|
+
streamer,
|
|
30
|
+
sendSuffixMessage,
|
|
31
|
+
persistBubbleText,
|
|
32
|
+
}) {
|
|
33
|
+
return async (errorSuffix, { suffixMessage = true } = {}) => {
|
|
34
|
+
if (hasDeliveredReplies()) {
|
|
35
|
+
await finishStreamer().catch(() => {});
|
|
36
|
+
// suffixMessage:false — the error reply the dispatcher sends next is
|
|
37
|
+
// already this turn's one error message.
|
|
38
|
+
if (errorSuffix && suffixMessage) {
|
|
39
|
+
await sendSuffixMessage(`⚠️ ${errorSuffix}`).catch(() => {});
|
|
40
|
+
}
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
// null, not '': finalize falls back to the drafted body. Passing ''
|
|
44
|
+
// REPLACED whatever had streamed with an empty bubble — the user watched
|
|
45
|
+
// a partial answer appear and then get wiped by the very failure that
|
|
46
|
+
// was supposed to leave it standing.
|
|
47
|
+
const fin = await streamer.finalize(null, errorSuffix ? { errorSuffix } : {})
|
|
48
|
+
.catch(() => null);
|
|
49
|
+
// The bubble now shows the drafted body; bring its transcript row along,
|
|
50
|
+
// or the row keeps the ~30-character stub the initial send wrote.
|
|
51
|
+
if (fin?.finalEditOk) persistBubbleText(fin.msgId, fin.finalText);
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The non-quiet error exit: decide the suffix from the error code
|
|
57
|
+
* (classifyTurnEndError), settle the preview, and return the reactor state
|
|
58
|
+
* the caller sets.
|
|
59
|
+
*/
|
|
60
|
+
async function settleTurnEndError(err, settleErrorExit) {
|
|
61
|
+
const { errorSuffix, reactorState, suffixMessage } = classifyTurnEndError(err);
|
|
62
|
+
// null keeps the drafted body so the suffix APPENDS to what the user was
|
|
63
|
+
// reading instead of replacing it with a bare "⚠️ …".
|
|
64
|
+
await settleErrorExit(errorSuffix, { suffixMessage });
|
|
65
|
+
return reactorState;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
module.exports = { createTurnErrorExit, settleTurnEndError };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.41.
|
|
3
|
+
"version": "0.41.4",
|
|
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": {
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"@anthropic-ai/claude-agent-sdk": "0.3.283",
|
|
72
72
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
73
|
-
"@shumkov/orchestra": "0.11.
|
|
73
|
+
"@shumkov/orchestra": "0.11.2",
|
|
74
74
|
"acorn": "8.18.0",
|
|
75
75
|
"better-sqlite3": "^12.9.0",
|
|
76
76
|
"grammy": "^1.42.0",
|
package/polygram.js
CHANGED
|
@@ -189,6 +189,7 @@ const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
|
|
|
189
189
|
const { createRichSender, sendRichWithStylingRetry } = require('./lib/telegram/rich-send');
|
|
190
190
|
const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
|
|
191
191
|
const { createRichEditStrategy } = require('./lib/telegram/rich-edit-dispatch');
|
|
192
|
+
const { normalizeRichInbound } = require('./lib/telegram/rich-inbound');
|
|
192
193
|
const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
|
|
193
194
|
const { composingMarker } = require('./lib/telegram/composing-marker');
|
|
194
195
|
const { buildPolygramDisplayHint } = require('./lib/telegram/display-hint');
|
|
@@ -207,7 +208,8 @@ const { startTyping } = require('./lib/telegram/typing');
|
|
|
207
208
|
const { createReactionManager, classifyToolName } = require('./lib/telegram/reactions');
|
|
208
209
|
const { createMediaGroupBuffer } = require('./lib/media-group-buffer');
|
|
209
210
|
const { applyReactionToMessages } = require('./lib/telegram/album-reactions');
|
|
210
|
-
const { classify: classifyError,
|
|
211
|
+
const { classify: classifyError, detectWedgedSessionError, isTransientHttpError } = require('./lib/error/classify');
|
|
212
|
+
const { createTurnErrorExit, settleTurnEndError } = require('./lib/telegram/turn-error-exit');
|
|
211
213
|
const { createAutoResumeTracker, isAutoResumable } = require('./lib/db/auto-resume');
|
|
212
214
|
const { createAuthDisabledGate } = require('./lib/ops/auth-disabled-gate');
|
|
213
215
|
const { createHeartbeat } = require('./lib/ops/heartbeat');
|
|
@@ -3119,35 +3121,20 @@ async function handleMessage(sessionKey, chatId, msg, bot, dispatchContext = nul
|
|
|
3119
3121
|
const abortedByUser = isSessionRecentlyAborted(sessionKey);
|
|
3120
3122
|
const quietFinalize = abortedByUser || isShuttingDown;
|
|
3121
3123
|
// A turn that already delivered replies and THEN failed must not restate
|
|
3122
|
-
// them
|
|
3123
|
-
// turn
|
|
3124
|
-
//
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
...(threadId && { message_thread_id: threadId }),
|
|
3137
|
-
}, { ...outMetaBase, source: 'turn-error-suffix' }).catch(() => {});
|
|
3138
|
-
}
|
|
3139
|
-
return;
|
|
3140
|
-
}
|
|
3141
|
-
// null, not '': finalize falls back to the drafted body. Passing ''
|
|
3142
|
-
// REPLACED whatever had streamed with an empty bubble — the user watched
|
|
3143
|
-
// a partial answer appear and then get wiped by the very failure that
|
|
3144
|
-
// was supposed to leave it standing.
|
|
3145
|
-
const fin = await streamer.finalize(null, errorSuffix ? { errorSuffix } : {})
|
|
3146
|
-
.catch(() => null);
|
|
3147
|
-
// The bubble now shows the drafted body; bring its transcript row along,
|
|
3148
|
-
// or the row keeps the ~30-character stub the initial send wrote.
|
|
3149
|
-
if (fin?.finalEditOk) persistBubbleText(chatId, fin.msgId, fin.finalText);
|
|
3150
|
-
};
|
|
3124
|
+
// them, so the error paths settle through the turn settler then (see
|
|
3125
|
+
// lib/telegram/turn-error-exit.js); with nothing delivered, the direct
|
|
3126
|
+
// finalize carries the error suffix onto the partial bubble.
|
|
3127
|
+
const settleErrorExit = createTurnErrorExit({
|
|
3128
|
+
hasDeliveredReplies: () => deliveredTexts.length > 0,
|
|
3129
|
+
finishStreamer,
|
|
3130
|
+
streamer,
|
|
3131
|
+
sendSuffixMessage: (text) => tg(bot, 'sendMessage', {
|
|
3132
|
+
chat_id: chatId,
|
|
3133
|
+
text,
|
|
3134
|
+
...(threadId && { message_thread_id: threadId }),
|
|
3135
|
+
}, { ...outMetaBase, source: 'turn-error-suffix' }),
|
|
3136
|
+
persistBubbleText: (msgId, text) => persistBubbleText(chatId, msgId, text),
|
|
3137
|
+
});
|
|
3151
3138
|
if (quietFinalize) {
|
|
3152
3139
|
await settleErrorExit(null);
|
|
3153
3140
|
if (abortedByUser) {
|
|
@@ -3170,11 +3157,7 @@ async function handleMessage(sessionKey, chatId, msg, bot, dispatchContext = nul
|
|
|
3170
3157
|
// `turn timeout (...)`, which does NOT match the legacy regex — branch on
|
|
3171
3158
|
// code, not text). TURN_TIMEOUT (went quiet) / TURN_MAX_EXCEEDED (hit hard
|
|
3172
3159
|
// cap) → TIMEOUT reactor; anything else → ERROR.
|
|
3173
|
-
|
|
3174
|
-
// null keeps the drafted body so the suffix APPENDS to what the user was
|
|
3175
|
-
// reading instead of replacing it with a bare "⚠️ …".
|
|
3176
|
-
await settleErrorExit(errorSuffix);
|
|
3177
|
-
reactor.setState(reactorState);
|
|
3160
|
+
reactor.setState(await settleTurnEndError(err, settleErrorExit));
|
|
3178
3161
|
}
|
|
3179
3162
|
if (deliverySettlementError) throw deliverySettlementError;
|
|
3180
3163
|
throw err;
|
|
@@ -3464,6 +3447,10 @@ function createBot(token) {
|
|
|
3464
3447
|
}
|
|
3465
3448
|
if (!chatConfig) return;
|
|
3466
3449
|
|
|
3450
|
+
// A rich message has no text of its own; give it one before anything
|
|
3451
|
+
// (the stored row, the gate, the prompt) reads it.
|
|
3452
|
+
normalizeRichInbound(ctx.message);
|
|
3453
|
+
|
|
3467
3454
|
// Record every inbound msg, even unaddressed ones — needed for reply-to
|
|
3468
3455
|
// lookups and the transcript skill.
|
|
3469
3456
|
recordInbound(ctx.message);
|
|
@@ -3519,6 +3506,9 @@ function createBot(token) {
|
|
|
3519
3506
|
}
|
|
3520
3507
|
const chatId = ctx.editedMessage.chat.id.toString();
|
|
3521
3508
|
if (!knownChat(chatId)) return;
|
|
3509
|
+
// Same rendering as a fresh message, or the upsert below would blank the
|
|
3510
|
+
// stored text of an edited rich message.
|
|
3511
|
+
normalizeRichInbound(ctx.editedMessage);
|
|
3522
3512
|
// 0.12.0 spec §3 (HARD): read the OLD text BEFORE recordInbound overwrites the row — the
|
|
3523
3513
|
// post-turn changed-guard compares it, and the re-dispatch quotes it in reply_to so claude sees
|
|
3524
3514
|
// the before/after. Reading after recordInbound would yield the new text (useless).
|
|
@@ -4080,6 +4070,10 @@ async function main() {
|
|
|
4080
4070
|
// 0.12 interactive questions: 'question-asked' (claude called the ask tool)
|
|
4081
4071
|
// → render the Telegram keyboard. Late-bound; questionHandlers is assigned below.
|
|
4082
4072
|
renderQuestion: (payload) => questionHandlers?.renderAsk(payload),
|
|
4073
|
+
// The API-error notice for a cycle with no pending turn stays quiet during
|
|
4074
|
+
// shutdown and right after the user's /stop.
|
|
4075
|
+
getIsShuttingDown: () => isShuttingDown,
|
|
4076
|
+
isSessionRecentlyAborted,
|
|
4083
4077
|
logger: console,
|
|
4084
4078
|
});
|
|
4085
4079
|
sdkCallbacks.onAbnormalTermination = (_sessionKey, evidence) => {
|