polygram 0.10.0-rc.21 → 0.10.0-rc.22

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.10.0-rc.21",
4
+ "version": "0.10.0-rc.22",
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",
@@ -41,13 +41,37 @@ function createHandleAbort({
41
41
 
42
42
  const threadId = msg.message_thread_id?.toString();
43
43
  const sessionKey = getSessionKey(chatId, threadId, chatConfig);
44
- const hadActive = pm.has(sessionKey) && !!pm.get(sessionKey)?.inFlight;
44
+ const proc = pm.has(sessionKey) ? pm.get(sessionKey) : null;
45
+ const hadActive = !!proc?.inFlight;
45
46
 
46
47
  // Mark BEFORE killing: the 'close' event fires almost immediately
47
48
  // after interrupt, and the surrounding handleMessage's catch
48
49
  // needs to see the flag to skip the generic error-reply.
49
50
  if (hadActive) markSessionAborted(sessionKey);
50
51
 
52
+ // Bug 1 (incident 2026-05-18): "Stop" was turn-scoped — it only
53
+ // looked at an in-flight TURN. But the agent can leave a DETACHED
54
+ // background shell running (a `run_in_background:true` Bash) that
55
+ // outlives the turn; the tmux TUI shows an `N shell` indicator.
56
+ // When there is no live turn, check for such a shell and stop it
57
+ // so "Stop" acts truthfully instead of replying "Nothing to stop"
58
+ // while work is still churning. tmux-only — the SDK Process has no
59
+ // hasBackgroundShell()/killBackgroundShells(); the typeof guards
60
+ // make this a no-op there.
61
+ let killedBackgroundShell = false;
62
+ if (!hadActive && proc
63
+ && typeof proc.hasBackgroundShell === 'function'
64
+ && typeof proc.killBackgroundShells === 'function') {
65
+ try {
66
+ if (await proc.hasBackgroundShell()) {
67
+ markSessionAborted(sessionKey);
68
+ killedBackgroundShell = await proc.killBackgroundShells();
69
+ }
70
+ } catch (err) {
71
+ logger.error?.(`[${botName}] background-shell stop failed: ${err.message}`);
72
+ }
73
+ }
74
+
51
75
  // SDK abort: interrupt() + drainQueue(). interrupt() cancels
52
76
  // the in-flight turn at SDK level WITHOUT tearing down the
53
77
  // Query (cheap to reuse for the user's next message);
@@ -62,6 +86,7 @@ function createHandleAbort({
62
86
  logEvent('abort-requested', {
63
87
  chat_id: chatId, user_id: msg.from?.id || null,
64
88
  had_active: hadActive,
89
+ killed_background_shell: killedBackgroundShell,
65
90
  trigger: cleanText.slice(0, 40),
66
91
  });
67
92
 
@@ -69,10 +94,23 @@ function createHandleAbort({
69
94
  // detection is crude but reliable for ru/en.
70
95
  const lang = /[а-яё]/i.test(cleanText) ? 'ru' : 'en';
71
96
  const strs = {
72
- en: { stopped: 'Stopped.', nothing: 'Nothing to stop.' },
73
- ru: { stopped: 'Остановлено.', nothing: 'Нечего останавливать.' },
97
+ en: {
98
+ stopped: 'Stopped.',
99
+ bgStopped: 'Stopped the background task.',
100
+ nothing: 'Nothing to stop.',
101
+ },
102
+ ru: {
103
+ stopped: 'Остановлено.',
104
+ bgStopped: 'Фоновая задача остановлена.',
105
+ nothing: 'Нечего останавливать.',
106
+ },
74
107
  }[lang];
75
- const reply = hadActive ? strs.stopped : strs.nothing;
108
+ // Truthful ack: a stopped in-flight turn → "Stopped"; a stopped
109
+ // background shell → "Stopped the background task"; neither →
110
+ // "Nothing to stop".
111
+ const reply = hadActive ? strs.stopped
112
+ : killedBackgroundShell ? strs.bgStopped
113
+ : strs.nothing;
76
114
  try {
77
115
  await tg(bot, 'sendMessage', {
78
116
  chat_id: chatId, text: reply,
@@ -88,6 +88,16 @@ const DEFAULT_CONTEXT_WINDOW = 200_000;
88
88
  const READY_HINTS_RE = /\?\s+for shortcuts|accept edits on|bypass permissions on/;
89
89
  const STREAMING_HINT_RE = /esc to interrupt/;
90
90
 
91
+ // Bug 1 (incident 2026-05-18): when the agent leaves a detached
92
+ // background shell running (a `run_in_background:true` Bash), the
93
+ // claude TUI shows a background-shell count in the pane. Verified
94
+ // against claude 2.1.142 — two forms:
95
+ // - the bottom hint line: "… · 1 shell · ↓ to manage"
96
+ // - the status line: "✻ Baked for 5s · 1 shell still running"
97
+ // Both carry "<N> shell(s)". polygram's turn-scoped Stop is blind to
98
+ // these; this regex lets the abort handler see them.
99
+ const BG_SHELL_RE = /\b\d+\s+shells?\b/;
100
+
91
101
  // L1 fix (spike leftover): the claude TUI shows its welcome banner
92
102
  // WITH a ready hint at the bottom during startup — before the user's
93
103
  // prompt has been processed:
@@ -135,7 +145,17 @@ const TUI_BANNER_RE = /▐▛███▜▌|▝▜█████▛▘/;
135
145
  // The optional `❯` cursor in [^\S\n]*(?:❯[^\S\n]+)?1\. is still
136
146
  // bounded to the line containing `1.`, so the security property
137
147
  // holds — only a real menu line satisfies it.
138
- const APPROVAL_PROMPT_RE = /Do you want to (?:proceed|do this|continue)\??[\s\S]{0,400}?(?:^|\n)[^\S\n]*(?:❯[^\S\n]+)?1\.\s+/im;
148
+ //
149
+ // 2026-05-18 incident fix: the verb after "Do you want to" varies by
150
+ // tool — Bash → "do this", Write → "create CLAUDE.md", Edit → "make
151
+ // this edit", etc. A `proceed|do this|continue` whitelist missed
152
+ // "create" and hung the Music topic for 7+ min with no approval card.
153
+ // Match the STRUCTURE, not a verb whitelist: a "Do you want to …?"
154
+ // question (verb is a bounded wildcard, single-line — no newline so
155
+ // it can't swallow past the question) followed within the bounded
156
+ // window by the numbered menu. The verb was never the security
157
+ // control — the required `1.` menu line is, and it is unchanged.
158
+ const APPROVAL_PROMPT_RE = /Do you want to [^\n?]{1,80}\??[\s\S]{0,400}?(?:^|\n)[^\S\n]*(?:❯[^\S\n]+)?1\.\s+/im;
139
159
  // Pull the tool name + raw arg snippet from the line preceding the
140
160
  // approval prompt. Capture-pane preserves the ⏺ marker.
141
161
  const TOOL_INVOCATION_RE = /⏺\s+([A-Za-z_]\w*)\s*\((.*?)\)\s*$/m;
@@ -532,6 +552,12 @@ class TmuxProcess extends Process {
532
552
  // Internal turn-done signal — settled by _flushActiveGroup when
533
553
  // this turn's group is flushed on a terminal `result`.
534
554
  turn.resultPromise = new Promise((resolve) => { turn.settleResult = resolve; });
555
+ // Bug 3: interrupt signal. `interrupt()` settles `signalInterrupt`
556
+ // to end this turn's race promptly — without it, an interrupted
557
+ // turn whose tool was killed by C-c writes no JSONL `result` and
558
+ // shows no capture-pane completion the race recognises, so
559
+ // `_runTurn` would hang until the absolute `turnTimeoutMs`.
560
+ turn.interruptP = new Promise((resolve) => { turn.signalInterrupt = resolve; });
535
561
 
536
562
  try {
537
563
  // rc.13.1: pasteAndEnter holds a per-session async lock around
@@ -596,6 +622,7 @@ class TmuxProcess extends Process {
596
622
  turn.resultPromise.then((ev) => ({ kind: 'jsonl', ev })),
597
623
  captureRaceP,
598
624
  turnDeadlineP,
625
+ turn.interruptP.then(() => ({ kind: 'interrupt' })),
599
626
  ]);
600
627
 
601
628
  // If capture-pane won but the turn used a tool, the agent is
@@ -603,10 +630,14 @@ class TmuxProcess extends Process {
603
630
  // tool calls. Wait for the real terminal result from JSONL, but
604
631
  // keep the absolute deadline armed so a JSONL `result` that
605
632
  // never arrives still fails the turn rather than hanging it.
633
+ // The interrupt signal still wins here too — Bug 3: an
634
+ // interrupted tool turn writes no terminal JSONL `result`, so
635
+ // without this racer it would hang to `turnTimeoutMs`.
606
636
  if (winner.kind === 'capture' && turn.toolUsedThisTurn) {
607
637
  winner = await Promise.race([
608
638
  turn.resultPromise.then((ev) => ({ kind: 'jsonl', ev })),
609
639
  turnDeadlineP,
640
+ turn.interruptP.then(() => ({ kind: 'interrupt' })),
610
641
  ]);
611
642
  }
612
643
  } finally {
@@ -620,7 +651,18 @@ class TmuxProcess extends Process {
620
651
  let text;
621
652
  let resultSubtype = 'success';
622
653
  let stopReason = null;
623
- if (winner.kind === 'jsonl') {
654
+ if (winner.kind === 'interrupt') {
655
+ // Bug 3: `interrupt()` ended the turn. C-c was sent to the
656
+ // TUI; the turn stops here instead of hanging until the
657
+ // absolute `turnTimeoutMs`. Deliver whatever partial text the
658
+ // agent streamed before the interrupt (may be empty) with an
659
+ // explicit `interrupted` subtype so polygram's caller can tell
660
+ // a stopped turn apart from a clean completion.
661
+ turn.interrupted = true;
662
+ text = turn.text || '';
663
+ resultSubtype = 'interrupted';
664
+ stopReason = 'interrupted';
665
+ } else if (winner.kind === 'jsonl') {
624
666
  text = turn.text || winner.ev.text || '';
625
667
  resultSubtype = winner.ev.subtype || 'success';
626
668
  stopReason = winner.ev.stopReason || null;
@@ -796,6 +838,10 @@ class TmuxProcess extends Process {
796
838
  startedAt: 0,
797
839
  resolve: null, reject: null, callerPromise: null,
798
840
  settleResult: null, resultPromise: null,
841
+ // Bug 3: settled by `interrupt()` to make a live turn's
842
+ // `_runTurn` race end promptly instead of hanging until
843
+ // `turnTimeoutMs`. Armed at the top of `_runTurn`.
844
+ signalInterrupt: null, interruptP: null, interrupted: false,
799
845
  };
800
846
  }
801
847
 
@@ -1508,10 +1554,78 @@ class TmuxProcess extends Process {
1508
1554
  this.logger.error?.(`[${this.label}] interrupt: ${err.message}`);
1509
1555
  return false;
1510
1556
  }
1557
+ // Bug 3: C-c stops the agent's work in the TUI, but an interrupted
1558
+ // turn (especially a tool turn) writes no terminal JSONL `result`
1559
+ // and shows no capture-pane completion `_runTurn`'s race
1560
+ // recognises — so `_runTurn` would hang until the absolute
1561
+ // `turnTimeoutMs`. Settle the running turn's interrupt signal so
1562
+ // its race ends NOW. The running primary turn is `pendingQueue[0]`
1563
+ // in state 'pasted'/'streaming'.
1564
+ const running = this.pendingQueue.find(
1565
+ (t) => t.state === 'pasted' || t.state === 'streaming',
1566
+ );
1567
+ if (running && typeof running.signalInterrupt === 'function') {
1568
+ running.signalInterrupt();
1569
+ }
1511
1570
  this.emit('interrupt-applied', { backend: 'tmux' });
1512
1571
  return true;
1513
1572
  }
1514
1573
 
1574
+ /**
1575
+ * Bug 1: report whether the TUI currently shows a running
1576
+ * background shell (a detached `run_in_background:true` Bash). This
1577
+ * is work that outlives the turn — polygram's turn-scoped Stop is
1578
+ * blind to it. Reads the pane bottom for the `N shell` indicator.
1579
+ * @returns {Promise<boolean>}
1580
+ */
1581
+ async hasBackgroundShell() {
1582
+ if (this.closed) return false;
1583
+ try {
1584
+ const buf = await this.runner.captureWide(this.tmuxName, { lines: 80 });
1585
+ // The indicator lives in the bottom few lines of the pane.
1586
+ return BG_SHELL_RE.test(String(buf || '').slice(-2000));
1587
+ } catch (err) {
1588
+ this.logger.error?.(`[${this.label}] hasBackgroundShell: ${err.message}`);
1589
+ return false;
1590
+ }
1591
+ }
1592
+
1593
+ /**
1594
+ * Bug 1: stop every running background shell via the TUI's
1595
+ * background-task panel. Sequence verified against claude 2.1.142:
1596
+ * `/bashes` + Enter opens the "Shell details" panel (legend
1597
+ * "Esc/Enter/Space to close · x to stop"); `x` stops the shell;
1598
+ * Esc closes the panel. Repeats while a shell remains, bounded so a
1599
+ * stuck panel can't loop forever.
1600
+ *
1601
+ * @returns {Promise<boolean>} true if no background shell remains
1602
+ * after the attempt (all stopped, or none was running).
1603
+ */
1604
+ async killBackgroundShells() {
1605
+ if (this.closed) return false;
1606
+ const maxRounds = 8; // bound — one round per shell, plus slack
1607
+ for (let round = 0; round < maxRounds; round += 1) {
1608
+ if (!(await this.hasBackgroundShell())) return true;
1609
+ try {
1610
+ // Open the background-task panel.
1611
+ await this.runner.pasteText(this.tmuxName, '/bashes');
1612
+ await this.runner.sendControl(this.tmuxName, 'Enter');
1613
+ await this._sleep(this.pollMs * 4 + 200);
1614
+ // Stop the shell shown in the Shell-details panel.
1615
+ await this.runner.sendControl(this.tmuxName, 'x');
1616
+ await this._sleep(this.pollMs * 4 + 200);
1617
+ // Close the panel.
1618
+ await this.runner.sendControl(this.tmuxName, 'Escape');
1619
+ await this._sleep(this.pollMs * 2 + 100);
1620
+ } catch (err) {
1621
+ this.logger.error?.(`[${this.label}] killBackgroundShells: ${err.message}`);
1622
+ return false;
1623
+ }
1624
+ }
1625
+ // Bounded out — report the residual state honestly.
1626
+ return !(await this.hasBackgroundShell());
1627
+ }
1628
+
1515
1629
  async setModel(model) {
1516
1630
  if (this.closed || !model) return false;
1517
1631
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.10.0-rc.21",
3
+ "version": "0.10.0-rc.22",
4
4
  "description": "Telegram daemon for Claude Code that preserves the OpenClaw per-chat session model. Migration path for OpenClaw users moving to Claude Code.",
5
5
  "main": "lib/ipc/client.js",
6
6
  "bin": {
package/polygram.js CHANGED
@@ -1379,6 +1379,16 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1379
1379
  await sendInlineStickers();
1380
1380
  await sendInlineReactions();
1381
1381
  await cleanupArchivedBubbles();
1382
+ // Bug 2 (incident 2026-05-18): this streamed-success branch
1383
+ // returns BEFORE the rc.10 deferred-clear block at the
1384
+ // bottom of the handler — so a turn that streamed its reply
1385
+ // never cleared the reactor. If the turn went quiet
1386
+ // mid-stream long enough to trip STALL (🥱), the emoji
1387
+ // stuck. reactor.stop() in the finally only kills timers,
1388
+ // not the visible reaction. Clear here, mirroring the
1389
+ // rc.10 block — AFTER delivery so there's no visual gap.
1390
+ reactor.clear().catch(() => {});
1391
+ clearAutosteeredReactions(sessionKey).catch(() => {});
1382
1392
  console.log(`[${label}] ${elapsed}s | ${result.text.length} chars | streamed | ${chatConfig.model}/${chatConfig.effort} | $${result.cost?.toFixed(4) || '?'}`);
1383
1393
  markReplied();
1384
1394
  return;
@@ -1426,6 +1436,18 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1426
1436
  await sendInlineStickers();
1427
1437
  await sendInlineReactions();
1428
1438
  await cleanupArchivedBubbles();
1439
+ // Bug 2 (incident 2026-05-18): same gap as the finalEditOk
1440
+ // branch above — this streamed-redeliver path returns before
1441
+ // the rc.10 deferred-clear block, so the reactor would stay
1442
+ // stuck. Clear it (and autosteered ✍) here, after delivery —
1443
+ // but ONLY on a clean delivery. When r.failed.length>0 the
1444
+ // ERROR state (😨) was set above as the "look here" signal
1445
+ // for the partial-delivery failure; clearing it would wipe
1446
+ // that signal, so leave the reactor as-is in that case.
1447
+ if (r.failed.length === 0) {
1448
+ reactor.clear().catch(() => {});
1449
+ }
1450
+ clearAutosteeredReactions(sessionKey).catch(() => {});
1429
1451
  console.log(`[${label}] ${elapsed}s | ${result.text.length} chars | streamed-redeliver(${reason}, ${chunks.length} chunks${r.failed.length ? `, ${r.failed.length} failed` : ''}) | ${chatConfig.model}/${chatConfig.effort} | $${result.cost?.toFixed(4) || '?'}`);
1430
1452
  markReplied();
1431
1453
  return;