shadok-ai 0.20.19 → 0.20.21

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/dist/telegram.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import WebSocket from "ws";
4
- import { loadChannels, upsertChannel, removeChannel, channelForTelegram, homeChannelForGeneral, loadTgGroup, saveTgGroup, loadTgOwner, saveTgOwner, loadTgOperators, saveTgOperators, isMirrored, loadTgTopics, saveTgTopics, addTgTopic, tgToolsEnabled, setTgTools, isHomeChannel, } from "./channels.js";
4
+ import { loadChannels, upsertChannel, removeChannel, channelForTelegram, homeChannelForGeneral, loadTgGroup, saveTgGroup, loadTgOwner, saveTgOwner, loadTgOperators, saveTgOperators, isMirrored, loadTgTopics, saveTgTopics, addTgTopic, tgToolsEnabled, setTgTools, isHomeChannel, loadTgDelivered, saveTgDelivered, } from "./channels.js";
5
+ import { replayPlan, replayHeader, advanceMark } from "./tg-replay.js";
5
6
  import { triggerSummary } from "./channel-triggers.js";
6
7
  import { secretNames, setSecret, deleteSecret, secretWriteVerdict, secretNameRefusal, MT_CLAUDE_OAUTH_TOKEN_NAME } from "./secrets.js";
7
8
  import { MAIN_GROUP_ID } from "./groups.js";
@@ -1346,6 +1347,16 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1346
1347
  });
1347
1348
  }
1348
1349
  };
1350
+ /**
1351
+ * Remember what this binding has delivered, so a later reattach replays the
1352
+ * gap instead of losing it (`src/tg-replay.ts`). One small synchronous write
1353
+ * per delivered message — the same cost, and the same reason, as the tail's
1354
+ * `writePos`: a resume point written only AFTER the content was consumed.
1355
+ */
1356
+ const markDelivered = (b, next) => {
1357
+ b.delivered = advanceMark(b.delivered, next);
1358
+ saveTgDelivered(b.key, b.delivered);
1359
+ };
1349
1360
  /** Open (or resume) a session for a chat/topic and wire its events to Telegram. */
1350
1361
  const openBridge = (key, chatId, threadId, opts = {}) => {
1351
1362
  const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, {
@@ -1365,6 +1376,15 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1365
1376
  pendingActions: [],
1366
1377
  worktree: opts.worktree,
1367
1378
  backfill: opts.backfill,
1379
+ // A reattach resumes a binding that already has a history in its chat, so
1380
+ // it gets a resume point. A fresh topic does not: `backfill` is its own
1381
+ // replay, and handing it a mark as well would post the gap twice.
1382
+ ...(opts.resumeId && !opts.backfill
1383
+ ? (() => {
1384
+ const mark = loadTgDelivered()[key] ?? null;
1385
+ return { delivered: mark, replayFrom: mark };
1386
+ })()
1387
+ : { delivered: null }),
1368
1388
  guest: isGuestChat(chatId, threadId),
1369
1389
  showTools: tgToolsEnabled(key),
1370
1390
  name: opts.name,
@@ -1408,20 +1428,51 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1408
1428
  }
1409
1429
  switch (m.type) {
1410
1430
  case "history": {
1411
- // Only replay for a freshly-created topic; never on a reconnect/reboot
1412
- // (arrives before `ready`, so the flag gates it exactly once).
1413
- if (!b.backfill)
1431
+ const all = Array.isArray(m.turns) ? m.turns : [];
1432
+ // A freshly-created topic replays recent history so the mirror is not
1433
+ // born empty (the flag arrives before `ready`, so it gates exactly
1434
+ // once). It also SEEDS the resume point: without that, the gap after
1435
+ // this bridge's first death would be measured from nothing and
1436
+ // replayed as "no mark" — i.e. not at all.
1437
+ if (b.backfill) {
1438
+ b.backfill = false;
1439
+ b.replayFrom = null;
1440
+ const turns = all.slice(-15);
1441
+ if (!turns.length)
1442
+ break;
1443
+ send(b, `— history resumed (last ${turns.length} exchanges) —`);
1444
+ for (const t of turns) {
1445
+ const txt = String(t?.text ?? "").trim();
1446
+ if (txt)
1447
+ send(b, t.role === "user" ? "👤 " + txt : txt);
1448
+ }
1449
+ const last = turns[turns.length - 1];
1450
+ markDelivered(b, { at: typeof last?.at === "number" ? last.at : Date.now() });
1414
1451
  break;
1415
- b.backfill = false;
1416
- const turns = (Array.isArray(m.turns) ? m.turns : []).slice(-15);
1417
- if (!turns.length)
1452
+ }
1453
+ // A RECONNECT posts the gap and only the gap: everything written
1454
+ // while no bridge was attached to carry it. The mark is consumed here
1455
+ // whatever the plan says, so a second `history` (a later resume on the
1456
+ // same bridge) can never replay the same window twice.
1457
+ const mark = b.replayFrom;
1458
+ b.replayFrom = null;
1459
+ if (!mark)
1460
+ break;
1461
+ const plan = replayPlan(all, mark);
1462
+ if (!plan.post.length)
1418
1463
  break;
1419
- send(b, `— history resumed (last ${turns.length} exchanges) —`);
1420
- for (const t of turns) {
1421
- const txt = String(t?.text ?? "").trim();
1422
- if (txt)
1423
- send(b, t.role === "user" ? "👤 " + txt : txt);
1464
+ console.log(`telegram: ${b.key} — replaying ${plan.post.length} message(s) missed while no bridge was attached` +
1465
+ (plan.dropped ? ` (+${plan.dropped} older dropped)` : ""));
1466
+ send(b, replayHeader(plan.post.length, plan.dropped));
1467
+ for (const t of plan.post) {
1468
+ const txt = t.text.trim();
1469
+ // A replayed prompt keeps its author: the history carries the
1470
+ // `⟦platform · time · who⟧` header's fields, so the same label the
1471
+ // live echo would have printed is available here (see `loadHistory`).
1472
+ send(b, t.role === "user" ? promptEchoLabel(t.origin, false, t.from) + "\n" + txt : txt);
1424
1473
  }
1474
+ const last = plan.post[plan.post.length - 1];
1475
+ markDelivered(b, { at: typeof last.at === "number" ? last.at : Date.now() });
1425
1476
  break;
1426
1477
  }
1427
1478
  case "ready":
@@ -1441,6 +1492,12 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1441
1492
  case "stream-text": {
1442
1493
  if (!m.text?.trim())
1443
1494
  break;
1495
+ // Marked here rather than after each branch: both of them deliver
1496
+ // THIS block (one posts it, the other replaces the preface that
1497
+ // already carried it), so the resume point moves either way. The
1498
+ // transcript's own `at` is used where present — it is the clock a
1499
+ // replayed turn is compared in.
1500
+ markDelivered(b, { at: typeof m.at === "number" ? m.at : Date.now() });
1444
1501
  // Is this block the authoritative twin of a preface already shown?
1445
1502
  // (the tail only delivers it once the question is answered). If so we
1446
1503
  // EDIT the existing message — clean Markdown replaces the screen's
@@ -1462,6 +1519,12 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1462
1519
  // cannot post under the user's name.
1463
1520
  if (!m.text?.trim())
1464
1521
  break;
1522
+ // The echo has no transcript time — it is broadcast at submit, before
1523
+ // Claude Code writes the prompt down — so the resume point takes our
1524
+ // own delivery instant, and the TEXT comes with it: that is what lets
1525
+ // a replay recognise this prompt instead of posting it twice (see
1526
+ // `DeliveredMark.text`).
1527
+ markDelivered(b, { at: Date.now(), text: String(m.text) });
1465
1528
  const label = promptEchoLabel(m.origin, m.auto, m.from);
1466
1529
  // A file pasted into the web composer is a MEDIA, not a path. The web
1467
1530
  // renders its marker as a thumbnail; printing the marker here left the
@@ -1644,8 +1707,14 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1644
1707
  });
1645
1708
  ws.on("close", () => {
1646
1709
  b.typing.stop();
1647
- if (bridges.get(key) === b)
1648
- bridges.delete(key);
1710
+ if (bridges.get(key) !== b)
1711
+ return;
1712
+ bridges.delete(key);
1713
+ // SAY it. A bridge dying is what opens the mirror's gap, and it used to
1714
+ // leave no trace at all — so an operator whose web messages stopped
1715
+ // reaching the topic had nothing to read, on either side. The reconcilers
1716
+ // reattach it within ~5s when its agent is still alive.
1717
+ console.log(`telegram: ${key} — bridge closed; nothing reaches this chat until it is reattached`);
1649
1718
  });
1650
1719
  ws.on("error", () => { });
1651
1720
  return b;