polygram 0.41.3 → 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.
@@ -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.3",
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',
@@ -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 streamer.finalize('') (null = no suffix)
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
- tg(bot, 'sendMessage', {
471
- chat_id: chatId,
472
- text: '⚠️ This turn was interrupted and didn\'t complete on retry — please rephrase or simplify, or split into smaller steps.',
473
- reply_parameters: { message_id: msg.message_id },
474
- }, {
475
- source: 'error-reply',
476
- botName,
477
- sessionKey,
478
- sourceMsgId: msg.message_id,
479
- }).catch((replyErr) => {
480
- logger.error?.(`[${sessionKey}] failed to send replay-failure reply: ${replyErr.message}`);
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),
@@ -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 },
@@ -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;
@@ -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",
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.1",
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
@@ -208,7 +208,8 @@ const { startTyping } = require('./lib/telegram/typing');
208
208
  const { createReactionManager, classifyToolName } = require('./lib/telegram/reactions');
209
209
  const { createMediaGroupBuffer } = require('./lib/media-group-buffer');
210
210
  const { applyReactionToMessages } = require('./lib/telegram/album-reactions');
211
- const { classify: classifyError, classifyTurnEndError, detectWedgedSessionError, isTransientHttpError } = require('./lib/error/classify');
211
+ const { classify: classifyError, detectWedgedSessionError, isTransientHttpError } = require('./lib/error/classify');
212
+ const { createTurnErrorExit, settleTurnEndError } = require('./lib/telegram/turn-error-exit');
212
213
  const { createAutoResumeTracker, isAutoResumable } = require('./lib/db/auto-resume');
213
214
  const { createAuthDisabledGate } = require('./lib/ops/auth-disabled-gate');
214
215
  const { createHeartbeat } = require('./lib/ops/heartbeat');
@@ -3120,35 +3121,20 @@ async function handleMessage(sessionKey, chatId, msg, bot, dispatchContext = nul
3120
3121
  const abortedByUser = isSessionRecentlyAborted(sessionKey);
3121
3122
  const quietFinalize = abortedByUser || isShuttingDown;
3122
3123
  // A turn that already delivered replies and THEN failed must not restate
3123
- // them: finalize(null) publishes whatever the draft holds, which on a CLI
3124
- // turn is usually the answer a reply already sent. That is precisely the
3125
- // duplicate the shared rule exists to prevent, so when this turn delivered
3126
- // anything, the error paths settle through it instead (spec §3.3's "every
3127
- // exit" beats §3.2.3's literal wording). With nothing delivered, the old
3128
- // direct finalize is still exactly right — it is what carries the error
3129
- // suffix onto the partial bubble.
3130
- const settleErrorExit = async (errorSuffix) => {
3131
- if (deliveredTexts.length > 0) {
3132
- await finishStreamer().catch(() => {});
3133
- if (errorSuffix) {
3134
- await tg(bot, 'sendMessage', {
3135
- chat_id: chatId,
3136
- text: `⚠️ ${errorSuffix}`,
3137
- ...(threadId && { message_thread_id: threadId }),
3138
- }, { ...outMetaBase, source: 'turn-error-suffix' }).catch(() => {});
3139
- }
3140
- return;
3141
- }
3142
- // null, not '': finalize falls back to the drafted body. Passing ''
3143
- // REPLACED whatever had streamed with an empty bubble — the user watched
3144
- // a partial answer appear and then get wiped by the very failure that
3145
- // was supposed to leave it standing.
3146
- const fin = await streamer.finalize(null, errorSuffix ? { errorSuffix } : {})
3147
- .catch(() => null);
3148
- // The bubble now shows the drafted body; bring its transcript row along,
3149
- // or the row keeps the ~30-character stub the initial send wrote.
3150
- if (fin?.finalEditOk) persistBubbleText(chatId, fin.msgId, fin.finalText);
3151
- };
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
+ });
3152
3138
  if (quietFinalize) {
3153
3139
  await settleErrorExit(null);
3154
3140
  if (abortedByUser) {
@@ -3171,11 +3157,7 @@ async function handleMessage(sessionKey, chatId, msg, bot, dispatchContext = nul
3171
3157
  // `turn timeout (...)`, which does NOT match the legacy regex — branch on
3172
3158
  // code, not text). TURN_TIMEOUT (went quiet) / TURN_MAX_EXCEEDED (hit hard
3173
3159
  // cap) → TIMEOUT reactor; anything else → ERROR.
3174
- const { errorSuffix, reactorState } = classifyTurnEndError(err);
3175
- // null keeps the drafted body so the suffix APPENDS to what the user was
3176
- // reading instead of replacing it with a bare "⚠️ …".
3177
- await settleErrorExit(errorSuffix);
3178
- reactor.setState(reactorState);
3160
+ reactor.setState(await settleTurnEndError(err, settleErrorExit));
3179
3161
  }
3180
3162
  if (deliverySettlementError) throw deliverySettlementError;
3181
3163
  throw err;
@@ -4088,6 +4070,10 @@ async function main() {
4088
4070
  // 0.12 interactive questions: 'question-asked' (claude called the ask tool)
4089
4071
  // → render the Telegram keyboard. Late-bound; questionHandlers is assigned below.
4090
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,
4091
4077
  logger: console,
4092
4078
  });
4093
4079
  sdkCallbacks.onAbnormalTermination = (_sessionKey, evidence) => {