shadok-ai 0.19.19 → 0.19.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.
@@ -96,9 +96,15 @@ export declare function nextToolsState(arg: string, current: boolean): boolean;
96
96
  * refused before anything else: there is nothing to store as owner, and nothing
97
97
  * stable to key a guest's own agent on either.
98
98
  *
99
+ * `dmOnly` removes the owner from the question altogether (`TgMode`): nobody
100
+ * pairs, so a stored owner from before the switch is IGNORED rather than
101
+ * privileged — a mode's guarantee must not depend on the instance's history.
102
+ * With no door to put them through it still answers `deny`, fail-closed, even
103
+ * though the config cannot be saved in that state.
104
+ *
99
105
  * Pure — unit tested.
100
106
  */
101
- export declare function dmGate(owner: number | null, from: number | undefined, guestsOn?: boolean): "pair" | "allow" | "guest" | "deny";
107
+ export declare function dmGate(owner: number | null, from: number | undefined, guestsOn?: boolean, dmOnlyMode?: boolean): "pair" | "allow" | "guest" | "deny";
102
108
  /**
103
109
  * The code a message presents to pair the bot, or null. `/setup <code>` is the
104
110
  * typed form; `/start <code>` is what Telegram sends by itself when the bot is
package/dist/telegram.js CHANGED
@@ -16,7 +16,7 @@ import { tmuxHasSession } from "./tmux.js";
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { loadCrons, upsertCron, removeCron, resolveCronId, nextRunFor, onceAt, cronTimeZone, normalizeSchedule, parseDays, scheduleLabel, } from "./crons.js";
18
18
  import { SHADOK_DIR, guestSetupForCwd, loadConfig, telegramConfig } from "./config.js";
19
- import { guestCallbackAllowed, guestCommandCarriesSecret, guestCommandRefusal, guestNotice, ownerAdoptionCandidate, } from "./tg-guests.js";
19
+ import { dmOnly, groupChatRefusal, guestCallbackAllowed, guestCommandCarriesSecret, guestCommandRefusal, guestNotice, guestOpeningPrompt, guestsOpen, ownerAdoptionCandidate, } from "./tg-guests.js";
20
20
  import { readAndClearUpdateResult } from "./update-flag.js";
21
21
  import { UPDATE_EXIT_CODE } from "./supervisor.js";
22
22
  import { pairingRefusal, redeemPairingCode } from "./tg-pairing.js";
@@ -204,11 +204,23 @@ export function nextToolsState(arg, current) {
204
204
  * refused before anything else: there is nothing to store as owner, and nothing
205
205
  * stable to key a guest's own agent on either.
206
206
  *
207
+ * `dmOnly` removes the owner from the question altogether (`TgMode`): nobody
208
+ * pairs, so a stored owner from before the switch is IGNORED rather than
209
+ * privileged — a mode's guarantee must not depend on the instance's history.
210
+ * With no door to put them through it still answers `deny`, fail-closed, even
211
+ * though the config cannot be saved in that state.
212
+ *
207
213
  * Pure — unit tested.
208
214
  */
209
- export function dmGate(owner, from, guestsOn = false) {
215
+ export function dmGate(owner, from, guestsOn = false,
216
+ // Named like the bridge's own flag rather than the `dmOnly()` predicate it
217
+ // comes from: this file imports that function, and shadowing it here would
218
+ // make the next reader look twice.
219
+ dmOnlyMode = false) {
210
220
  if (typeof from !== "number")
211
221
  return "deny";
222
+ if (dmOnlyMode)
223
+ return guestsOn ? "guest" : "deny";
212
224
  if (owner === null)
213
225
  return "pair";
214
226
  if (owner === from)
@@ -1036,20 +1048,26 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1036
1048
  const token = cfg.token;
1037
1049
  const api = `https://api.telegram.org/bot${token}`;
1038
1050
  const allowed = cfg.allowedChats;
1039
- // Open DMs (src/tg-guests.ts). Read at start like the rest of the config: the
1040
- // panel restarts the bridge when it changes, so this cannot go stale. Only
1041
- // the SWITCH is read here — which group and which profile a guest's agent
1042
- // gets is resolved server-side at spawn, never carried from here.
1043
- const guestsOn = guestSetupForCwd(loadConfig(), process.cwd()).on;
1051
+ // Where this bot works (`TgMode`, src/tg-guests.ts). Read at start like the
1052
+ // rest of the config: the panel restarts the bridge when it changes, so this
1053
+ // cannot go stale. Only the MODE is read here — which group and which profile
1054
+ // a guest's agent gets is resolved server-side at spawn, never carried from
1055
+ // here.
1056
+ const tgSetup = guestSetupForCwd(loadConfig(), process.cwd());
1057
+ const guestsOn = guestsOpen(tgSetup);
1058
+ // DM-only: no board group, no `/setup`, and no owner at all (see `TgMode`).
1059
+ const dmOnlyMode = dmOnly(tgSetup);
1044
1060
  /**
1045
1061
  * Is this chat a GUEST's DM? One definition, derived rather than stored, so a
1046
1062
  * bridge opened by a spawn, a resume or a boot reattach all agree — and so
1047
1063
  * nothing has to carry a flag through those three paths.
1048
1064
  *
1049
1065
  * A DM's chat id IS the sender's user id and is always positive; a group's is
1050
- * negative. So "a private chat that is not the owner's" is the whole rule.
1066
+ * negative. So "a private chat that is not the owner's" is the whole rule —
1067
+ * and in DM-only mode there is no owner to except, the operator's own DM
1068
+ * included.
1051
1069
  */
1052
- const isGuestChat = (chatId, threadId) => guestsOn && threadId == null && chatId > 0 && chatId !== loadTgOwner();
1070
+ const isGuestChat = (chatId, threadId) => guestsOn && threadId == null && chatId > 0 && (dmOnlyMode || chatId !== loadTgOwner());
1053
1071
  // Mutable bridge state, closed over by the returned handle (see stop()/status()).
1054
1072
  let stopped = false;
1055
1073
  let polling = false;
@@ -1556,6 +1574,23 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1556
1574
  b.awaitingFreetext = undefined;
1557
1575
  sendOps(b, "— session ended —", "exited");
1558
1576
  break;
1577
+ case "stopped":
1578
+ // The agent was DELETED — the cockpit's ✕, "End session", /end, or a
1579
+ // closed topic. Its channel row is gone with it, so this bridge now
1580
+ // points at nothing: keeping it would send every later message into a
1581
+ // dead session, and the person on the other side would get "something
1582
+ // went wrong" for ever with no way out. Closing it drops it from
1583
+ // `bridges` (see `ws.on("close")`), so the NEXT message opens a fresh
1584
+ // agent — `bridgeFor` finds no channel to resume, which is exactly
1585
+ // what a deleted agent should mean.
1586
+ b.typing.stop();
1587
+ b.awaitingFreetext = undefined;
1588
+ console.log(`telegram: ${b.key} — its agent was ended, the next message starts a new one`);
1589
+ try {
1590
+ ws.close();
1591
+ }
1592
+ catch { /* already closing */ }
1593
+ break;
1559
1594
  }
1560
1595
  });
1561
1596
  ws.on("close", () => {
@@ -1568,8 +1603,22 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1568
1603
  };
1569
1604
  const bridgeFor = (key, chatId, threadId, name) => {
1570
1605
  const existing = bridges.get(key);
1571
- if (existing && existing.ws.readyState <= WebSocket.OPEN)
1572
- return existing;
1606
+ // A live socket is not proof that the agent behind it still exists: a
1607
+ // deleted channel leaves a bridge pointing at a dead session (the `stopped`
1608
+ // frame closes it, but a removal that never broadcast one — a reconcile, a
1609
+ // crashed server — would not). The registry is the authority on where a
1610
+ // session lives (invariant 1), so it is asked here too, and a bridge it no
1611
+ // longer knows is dropped rather than reused.
1612
+ if (existing && existing.ws.readyState <= WebSocket.OPEN) {
1613
+ if (!existing.sessionId || loadChannels().some((c) => c.sessionId === existing.sessionId))
1614
+ return existing;
1615
+ console.log(`telegram: ${key} — its agent is gone from the registry, starting a new one`);
1616
+ bridges.delete(key);
1617
+ try {
1618
+ existing.ws.close();
1619
+ }
1620
+ catch { /* already closing */ }
1621
+ }
1573
1622
  const saved = channelForTelegram(chatId, threadId);
1574
1623
  // The board's General (no threadId, a group) is the environment's home base.
1575
1624
  // The web home channel has `home: true` but NO Telegram binding until now, so
@@ -1684,7 +1733,7 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1684
1733
  */
1685
1734
  const guardDm = async (msg) => {
1686
1735
  const from = msg.from?.id;
1687
- const verdict = dmGate(loadTgOwner(), from, guestsOn);
1736
+ const verdict = dmGate(loadTgOwner(), from, guestsOn, dmOnlyMode);
1688
1737
  if (verdict === "allow")
1689
1738
  return "allow";
1690
1739
  if (verdict === "guest")
@@ -1820,7 +1869,22 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1820
1869
  const threadId = msg.message_thread_id;
1821
1870
  const isGroup = chat.type === "group" || chat.type === "supergroup";
1822
1871
  // Commands only exist in text messages — a caption is never a command.
1823
- const cmd = typeof msg.text === "string" ? parseCommand(msg.text) : null;
1872
+ // Not `const`: a guest's `/start` is taken out of the dispatcher's hands
1873
+ // below, and becomes the opening prompt of their own agent instead.
1874
+ let cmd = typeof msg.text === "string" ? parseCommand(msg.text) : null;
1875
+ // Is this message Telegram's own `/start`, from someone who has not written
1876
+ // anything yet (`guestOpeningPrompt`)?
1877
+ let guestOpening = false;
1878
+ // DM-only mode: a group chat reaches nothing at all, and that refusal sits
1879
+ // ABOVE the board logic on purpose — a group bound before the switch must
1880
+ // stop working too, or the mode's guarantee would depend on when the
1881
+ // instance was set up. It is also what prevents `/setup` here: binding a
1882
+ // board, and becoming an operator of one, both live below this line.
1883
+ const groupClosed = groupChatRefusal(tgSetup);
1884
+ if (isGroup && groupClosed) {
1885
+ await reply(chat.id, threadId, groupClosed);
1886
+ return;
1887
+ }
1824
1888
  // One board per instance: a group must be the bound group.
1825
1889
  if (isGroup) {
1826
1890
  const bound = loadTgGroup();
@@ -1906,6 +1970,14 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
1906
1970
  await reply(chat.id, undefined, refusal);
1907
1971
  return;
1908
1972
  }
1973
+ // `/start` is the only command that survives that refusal, and it must
1974
+ // never reach the dispatcher below: `case "start"` prints the COCKPIT's
1975
+ // help page — /spawn, /secret, /login — which is exactly the operator's
1976
+ // vocabulary landing in a stranger's chat (invariant 65). It becomes the
1977
+ // opening prompt of their own agent instead, so the welcome is written by
1978
+ // the profile rather than by this file.
1979
+ guestOpening = true;
1980
+ cmd = null;
1909
1981
  }
1910
1982
  if (cmd && commandRequiresOperator(cmd.cmd, cmd.arg, (n) => !!getProfile(n))) {
1911
1983
  if (!isOperator(msg.from?.id, loadTgOperators(), loadTgOwner(), !!msg.from?.is_bot)) {
@@ -2342,6 +2414,13 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
2342
2414
  b.pendingActions.push(wsMsg);
2343
2415
  return;
2344
2416
  }
2417
+ // Telegram's own `/start`, before this person has written a word: the agent
2418
+ // is asked to greet them, and the raw "/start" is never forwarded — a
2419
+ // leading slash is a command to the TUI, not a sentence.
2420
+ if (guestOpening) {
2421
+ promptTo(b, guestOpeningPrompt(msg.from?.language_code), senderName(msg.from));
2422
+ return;
2423
+ }
2345
2424
  // A reply carries the message it answers: without it the agent reads
2346
2425
  // "fix that" with no trace of what "that" is.
2347
2426
  const quoted = replyContext(msg);
@@ -2357,7 +2436,7 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
2357
2436
  // on that assumption. Never a pairing here: DMs are paired by a typed code,
2358
2437
  // not by clicking.
2359
2438
  if (msg.chat?.type === "private" &&
2360
- !guestCallbackAllowed(dmGate(loadTgOwner(), cq.from?.id, guestsOn), msg.chat?.id, cq.from?.id)) {
2439
+ !guestCallbackAllowed(dmGate(loadTgOwner(), cq.from?.id, guestsOn, dmOnlyMode), msg.chat?.id, cq.from?.id)) {
2361
2440
  await tg("answerCallbackQuery", { callback_query_id: cq.id, text: "⛔ This bot is private." });
2362
2441
  return;
2363
2442
  }
@@ -2365,7 +2444,9 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
2365
2444
  // board. Without it a click in any group reached `bridgeFor` and opened a
2366
2445
  // bridge there. Answering dialogs stays open to every board member — it
2367
2446
  // is driving the conversation, like sending a message.
2368
- if (!msg.chat || !callbackChatAllowed(msg.chat, allowed, loadTgGroup())) {
2447
+ // In DM-only mode there is no board, so a group has nothing to click in:
2448
+ // the gate is asked about a null board rather than a stale binding.
2449
+ if (!msg.chat || !callbackChatAllowed(msg.chat, allowed, dmOnlyMode ? null : loadTgGroup())) {
2369
2450
  await tg("answerCallbackQuery", { callback_query_id: cq.id, text: "⛔ this bot is restricted." });
2370
2451
  return;
2371
2452
  }
@@ -2713,7 +2794,9 @@ export function startTelegram(port, authCookie, multiTenant = false, opts = {})
2713
2794
  * enough to name it.
2714
2795
  */
2715
2796
  const adoptOwnerFromBindings = async () => {
2716
- if (loadTgOwner() !== null)
2797
+ // DM-only: the bot has no owner by design (`TgMode`), so there is nothing
2798
+ // to adopt — and writing one would leave a file that contradicts the mode.
2799
+ if (dmOnlyMode || loadTgOwner() !== null)
2717
2800
  return;
2718
2801
  // A GUEST's DM has exactly the shape this looks for, so it is excluded by
2719
2802
  // its channel's group (`ownerAdoptionCandidate`): adopting one would hand