@ours.network/tg-connector 2.0.4-nightly.2 → 2.1.0

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/connector.js CHANGED
@@ -25970,9 +25970,9 @@ async function applyProvision(stateDir, operations) {
25970
25970
 
25971
25971
  // src/connector.ts
25972
25972
  import { createServer as createHttpServer } from "node:http";
25973
- import { randomBytes } from "node:crypto";
25974
- import { join as join4 } from "node:path";
25975
- import * as fs3 from "node:fs";
25973
+ import { randomBytes as randomBytes2 } from "node:crypto";
25974
+ import { join as join5 } from "node:path";
25975
+ import * as fs4 from "node:fs";
25976
25976
 
25977
25977
  // src/config.ts
25978
25978
  import * as fs from "node:fs";
@@ -27287,11 +27287,16 @@ async function fetchWithRetry(fetchImpl, input, init, opts, log2) {
27287
27287
  if (attempt >= opts.retries || !isRetriableFetchError(err)) throw err;
27288
27288
  const delay = opts.retryBaseMs * 2 ** attempt + Math.floor(Math.random() * opts.retryBaseMs);
27289
27289
  attempt += 1;
27290
- log2?.(`${sanitizeUrl(input)} failed (${err.message}); retry ${attempt}/${opts.retries} in ${delay}ms`);
27290
+ log2?.(`${sanitizeUrl(input)} failed (${telegramErrorText(err.message)}); retry ${attempt}/${opts.retries} in ${delay}ms`);
27291
27291
  await sleep(delay);
27292
27292
  }
27293
27293
  }
27294
27294
  }
27295
+ function telegramErrorText(s) {
27296
+ const redacted = String(s).replace(/bot\d+:[A-Za-z0-9_-]+/g, "bot***").replace(/\b\d{5,}:[A-Za-z0-9_-]{20,}/g, "***").replace(/\s+/g, " ");
27297
+ const safe = /^[A-Za-z0-9 _:.,()/*'-]*/.exec(redacted)[0].trimEnd();
27298
+ return (safe.length < redacted.length ? `${safe} [\u2026]` : safe).slice(0, 160);
27299
+ }
27295
27300
  function userLabel(u3) {
27296
27301
  if (!u3) return void 0;
27297
27302
  const name = [u3.first_name, u3.last_name].filter(Boolean).join(" ").trim();
@@ -27358,6 +27363,7 @@ var TelegramClient = class {
27358
27363
  offset = 0;
27359
27364
  aborter = null;
27360
27365
  stopped = false;
27366
+ wakeOnStop = null;
27361
27367
  net;
27362
27368
  dispatcher;
27363
27369
  fetchImpl;
@@ -27425,6 +27431,67 @@ var TelegramClient = class {
27425
27431
  const parsed = await resp.json().catch(() => null);
27426
27432
  return parsed?.result?.message_id ?? 0;
27427
27433
  }
27434
+ // Send a static widget with queries allowed (Bot API 10.4 sendWidget). The
27435
+ // request is made exactly once — no transport retry — and the reply is
27436
+ // classified so the caller can tell "not sent" from "maybe sent".
27437
+ async sendWidget(p2) {
27438
+ let resp;
27439
+ try {
27440
+ resp = await this.tgFetch(this.url("sendWidget"), {
27441
+ method: "POST",
27442
+ headers: { "Content-Type": "application/json" },
27443
+ body: JSON.stringify({ ...p2, allow_queries: true })
27444
+ }, false);
27445
+ } catch (err) {
27446
+ return { status: "unknown", description: telegramErrorText(`transport error: ${err?.message ?? String(err)}`) };
27447
+ }
27448
+ const body = await resp.json().catch(() => null);
27449
+ if (resp.ok && body?.ok === true && Number.isSafeInteger(body.result?.message_id) && body.result.message_id > 0) {
27450
+ return { status: "sent", messageId: body.result.message_id };
27451
+ }
27452
+ if (resp.status >= 400 && resp.status < 500 && body && body.ok === false) {
27453
+ return {
27454
+ status: "rejected",
27455
+ code: body.error_code ?? resp.status,
27456
+ description: telegramErrorText(body.description ?? `HTTP ${resp.status}`),
27457
+ ...body.parameters?.retry_after !== void 0 ? { retryAfter: body.parameters.retry_after } : {}
27458
+ };
27459
+ }
27460
+ return { status: "unknown", description: telegramErrorText(`HTTP ${resp.status}${body?.description ? `: ${body.description}` : ""}`) };
27461
+ }
27462
+ // Answer a widget query (Bot API 10.4 answerWidgetQuery). Must happen within
27463
+ // 15 s of the tap; throws on any refusal (e.g. "query is too old").
27464
+ async answerWidgetQuery(queryId, data) {
27465
+ const r = await this.callWidgetMethod("answerWidgetQuery", { widget_query_id: queryId, ...data !== void 0 ? { data } : {} });
27466
+ if (r.status !== "ok") throw new Error(`answerWidgetQuery ${r.status}: ${r.description}`);
27467
+ }
27468
+ // Replace a widget's chat and/or public state (Bot API 10.4
27469
+ // editMessageWidgetData). Setting state is idempotent, so transport errors
27470
+ // are retried; what is still ambiguous afterwards is reported as `unknown`.
27471
+ async editMessageWidgetData(chatId, messageId, state) {
27472
+ const r = await this.callWidgetMethod("editMessageWidgetData", { chat_id: chatId, message_id: messageId, ...state });
27473
+ if (r.status === "ok") return { status: "updated", changed: true };
27474
+ if (r.status === "rejected" && /message is not modified/i.test(r.description)) return { status: "updated", changed: false };
27475
+ return r;
27476
+ }
27477
+ async callWidgetMethod(method, payload) {
27478
+ let resp;
27479
+ try {
27480
+ resp = await this.tgFetch(this.url(method), {
27481
+ method: "POST",
27482
+ headers: { "Content-Type": "application/json" },
27483
+ body: JSON.stringify(payload)
27484
+ });
27485
+ } catch (err) {
27486
+ return { status: "unknown", description: telegramErrorText(`transport error: ${err?.message ?? String(err)}`) };
27487
+ }
27488
+ const body = await resp.json().catch(() => null);
27489
+ if (resp.ok && body?.ok === true && body.result === true) return { status: "ok" };
27490
+ if (resp.status >= 400 && resp.status < 500 && body && body.ok === false) {
27491
+ return { status: "rejected", code: body.error_code ?? resp.status, description: telegramErrorText(body.description ?? `HTTP ${resp.status}`) };
27492
+ }
27493
+ return { status: "unknown", description: telegramErrorText(`HTTP ${resp.status}${body?.description ? `: ${body.description}` : ""}`) };
27494
+ }
27428
27495
  async setMyCommands(commands) {
27429
27496
  const resp = await this.tgFetch(this.url("setMyCommands"), {
27430
27497
  method: "POST",
@@ -27506,22 +27573,50 @@ var TelegramClient = class {
27506
27573
  }
27507
27574
  return Buffer.from(await resp.arrayBuffer());
27508
27575
  }
27509
- // Long-poll loop. Calls `onMessage` for every inbound text message until
27510
- // stop() is called. Network errors are logged and retried with a short
27511
- // backoff so a transient outage never kills the bridge.
27512
- async poll(onMessage) {
27576
+ // Long-poll loop. Calls `onMessage` for every inbound text message (and
27577
+ // `onWidgetQuery`, when given, for every widget_query) until stop() is
27578
+ // called. Network errors are logged and retried with a short backoff so a
27579
+ // transient outage never kills the bridge.
27580
+ //
27581
+ // With a widget handler, messages are handled one at a time, in order, on a
27582
+ // queue the poll does not wait for, so a slow message (a download,
27583
+ // speech-to-text) does not hold back the widget queries fetched meanwhile,
27584
+ // which must be answered within Telegram's 15 s; queries run concurrently.
27585
+ // This is prompt, not guaranteed: see the 100-update window below.
27586
+ //
27587
+ // Telegram treats every update below the getUpdates `offset` as confirmed
27588
+ // and never sends it again, so the offset sent is never past the oldest
27589
+ // message that has not finished: an unfinished message is redelivered after
27590
+ // a stop or a crash, exactly as before. Updates that come back again in the
27591
+ // meantime are recognized by update_id and skipped; while a message is
27592
+ // still running, the poll paces itself (about once a second) instead of
27593
+ // spinning on those repeats. getUpdates returns at most 100 updates, so
27594
+ // while a message runs only the 99 after it are seen; a query further back
27595
+ // waits and may miss its deadline (it is then dropped, never forwarded).
27596
+ // stop() lets the running handlers finish and starts no queued message
27597
+ // (those stay unconfirmed).
27598
+ async poll(onMessage, onWidgetQuery) {
27513
27599
  this.stopped = false;
27600
+ let messages = Promise.resolve();
27601
+ const unfinished = /* @__PURE__ */ new Set();
27602
+ const dispatched = /* @__PURE__ */ new Set();
27603
+ const queries = /* @__PURE__ */ new Set();
27604
+ const stopping = new Promise((resolve2) => {
27605
+ this.wakeOnStop = resolve2;
27606
+ });
27514
27607
  while (!this.stopped) {
27515
27608
  this.aborter = new AbortController();
27516
27609
  const timer = setTimeout(() => this.aborter?.abort(), (this.pollTimeoutSec + 10) * 1e3);
27610
+ const confirm = unfinished.size ? Math.min(...unfinished) : this.offset;
27611
+ for (const id of dispatched) if (id < confirm) dispatched.delete(id);
27517
27612
  try {
27518
27613
  const resp = await this.tgFetch(this.url("getUpdates"), {
27519
27614
  method: "POST",
27520
27615
  headers: { "Content-Type": "application/json" },
27521
27616
  body: JSON.stringify({
27522
- offset: this.offset,
27617
+ offset: confirm,
27523
27618
  timeout: this.pollTimeoutSec,
27524
- allowed_updates: ["message"]
27619
+ allowed_updates: onWidgetQuery ? ["message", "widget_query"] : ["message"]
27525
27620
  }),
27526
27621
  signal: this.aborter.signal
27527
27622
  }, false);
@@ -27537,35 +27632,72 @@ var TelegramClient = class {
27537
27632
  await sleep(3e3);
27538
27633
  continue;
27539
27634
  }
27635
+ let fresh = 0;
27540
27636
  for (const u3 of body.result) {
27541
27637
  if (this.stopped) break;
27542
27638
  this.offset = Math.max(this.offset, u3.update_id + 1);
27639
+ if (dispatched.has(u3.update_id)) continue;
27640
+ dispatched.add(u3.update_id);
27641
+ fresh += 1;
27642
+ if (u3.widget_query && onWidgetQuery) {
27643
+ const q = parseWidgetQuery(u3.update_id, u3.widget_query);
27644
+ if (!q) continue;
27645
+ let run;
27646
+ run = (async () => {
27647
+ await null;
27648
+ try {
27649
+ await onWidgetQuery(q);
27650
+ } catch (err) {
27651
+ this.log(`onWidgetQuery handler failed: ${String(err)}`);
27652
+ } finally {
27653
+ queries.delete(run);
27654
+ }
27655
+ })();
27656
+ queries.add(run);
27657
+ continue;
27658
+ }
27543
27659
  const m2 = u3.message;
27544
27660
  if (!m2) continue;
27545
27661
  const attachment = pickAttachment(m2);
27546
27662
  if (typeof m2.text !== "string" && typeof m2.caption !== "string" && !attachment) continue;
27547
- try {
27548
- await onMessage({
27549
- update_id: u3.update_id,
27550
- message_id: m2.message_id ?? 0,
27551
- chat_id: m2.chat.id,
27552
- chat_type: m2.chat.type,
27553
- chat_username: m2.chat.username,
27554
- thread_id: m2.is_topic_message ? m2.message_thread_id : void 0,
27555
- is_topic: m2.is_topic_message === true,
27556
- chat_title: m2.chat.title,
27557
- from: senderLabel(m2),
27558
- from_id: m2.from?.id,
27559
- from_username: m2.from?.username,
27560
- text: messageMarkdown(m2),
27561
- date: m2.date,
27562
- reply_to: parseReply(m2),
27563
- forwarded_from: parseForwardOrigin(m2),
27564
- attachment
27565
- });
27566
- } catch (err) {
27567
- this.log(`onMessage handler failed: ${String(err)}`);
27568
- }
27663
+ const message = {
27664
+ update_id: u3.update_id,
27665
+ message_id: m2.message_id ?? 0,
27666
+ chat_id: m2.chat.id,
27667
+ chat_type: m2.chat.type,
27668
+ chat_username: m2.chat.username,
27669
+ thread_id: m2.is_topic_message ? m2.message_thread_id : void 0,
27670
+ is_topic: m2.is_topic_message === true,
27671
+ chat_title: m2.chat.title,
27672
+ from: senderLabel(m2),
27673
+ from_id: m2.from?.id,
27674
+ from_username: m2.from?.username,
27675
+ text: messageMarkdown(m2),
27676
+ date: m2.date,
27677
+ reply_to: parseReply(m2),
27678
+ forwarded_from: parseForwardOrigin(m2),
27679
+ attachment
27680
+ };
27681
+ unfinished.add(u3.update_id);
27682
+ messages = messages.then(async () => {
27683
+ if (this.stopped) return;
27684
+ try {
27685
+ await onMessage(message);
27686
+ } catch (err) {
27687
+ this.log(`onMessage handler failed: ${String(err)}`);
27688
+ }
27689
+ unfinished.delete(message.update_id);
27690
+ });
27691
+ }
27692
+ if (!onWidgetQuery) await messages;
27693
+ while (!this.stopped && (unfinished.size > MAX_QUEUED_MESSAGES || queries.size > MAX_INFLIGHT_QUERIES)) {
27694
+ const pending = [stopping];
27695
+ if (unfinished.size > MAX_QUEUED_MESSAGES) pending.push(messages);
27696
+ if (queries.size > MAX_INFLIGHT_QUERIES) pending.push(...queries);
27697
+ await Promise.race(pending);
27698
+ }
27699
+ if (!this.stopped && fresh === 0 && unfinished.size > 0) {
27700
+ await Promise.race([messages, stopping, sleep(REPEAT_PACE_MS)]);
27569
27701
  }
27570
27702
  } catch (err) {
27571
27703
  clearTimeout(timer);
@@ -27579,12 +27711,33 @@ var TelegramClient = class {
27579
27711
  this.aborter = null;
27580
27712
  }
27581
27713
  }
27714
+ this.wakeOnStop = null;
27715
+ await messages;
27716
+ await Promise.all(queries);
27717
+ if (unfinished.size) this.offset = Math.min(...unfinished);
27582
27718
  }
27583
27719
  stop() {
27584
27720
  this.stopped = true;
27585
27721
  this.aborter?.abort();
27722
+ this.wakeOnStop?.();
27586
27723
  }
27587
27724
  };
27725
+ function parseWidgetQuery(updateId, q) {
27726
+ if (typeof q.id !== "string" || !q.id || typeof q.from?.id !== "number" || typeof q.data !== "string") return null;
27727
+ return {
27728
+ update_id: updateId,
27729
+ id: q.id,
27730
+ from_id: q.from.id,
27731
+ from: userLabel(q.from) ?? "telegram",
27732
+ chat_id: typeof q.chat?.id === "number" ? q.chat.id : void 0,
27733
+ chat_type: q.chat?.type,
27734
+ message_id: typeof q.message_id === "number" ? q.message_id : void 0,
27735
+ inline: typeof q.inline_message_id === "string",
27736
+ shared: typeof q.widget_id === "string",
27737
+ queryType: String(q.type?.type ?? ""),
27738
+ data: q.data
27739
+ };
27740
+ }
27588
27741
  function chunkText(text2, size) {
27589
27742
  if (text2.length <= size) return [text2];
27590
27743
  const out = [];
@@ -27615,8 +27768,461 @@ function splitForMarkdownV2(text2, limit = TELEGRAM_TEXT_LIMIT) {
27615
27768
  if (rest) out.push(rest);
27616
27769
  return out;
27617
27770
  }
27771
+ var MAX_QUEUED_MESSAGES = 200;
27772
+ var MAX_INFLIGHT_QUERIES = 64;
27773
+ var REPEAT_PACE_MS = 1e3;
27618
27774
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27619
27775
 
27776
+ // src/widgets.ts
27777
+ import { deflateSync, constants as zlibConstants } from "node:zlib";
27778
+ import { createHash, randomBytes } from "node:crypto";
27779
+ import * as fs2 from "node:fs";
27780
+ import { join as join3 } from "node:path";
27781
+ var WIDGET_HTML_MAX_BYTES = 32768;
27782
+ var WIDGET_HTML_MAX_COMPRESSED = 4096;
27783
+ var WIDGET_STATE_MAX_BYTES = 1024;
27784
+ var WIDGET_QUERY_DATA_MAX_BYTES = 64;
27785
+ var WIDGET_CAPTION_MAX = 1024;
27786
+ var SEND_COMMAND = "telegram_widget_send";
27787
+ var UPDATE_COMMAND = "telegram_widget_update";
27788
+ var QUERY_EVENT = "telegram_widget_query";
27789
+ var ACCEPTED_ANSWER = '{"ok":true}';
27790
+ var REFUSED_ANSWER = '{"ok":false}';
27791
+ var QUERY_NOTE = "untrusted widget data; the widget may send requests without a tap, so this is not proof of a deliberate human approval";
27792
+ var MAX_WIDGETS = 2e3;
27793
+ var MAX_QUERY_IDS = 1e3;
27794
+ var REQUEST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
27795
+ var REF_RE = /^w_[A-Za-z0-9_-]{12}$/;
27796
+ var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
27797
+ var utf8Bytes = (s) => Buffer.byteLength(s, "utf8");
27798
+ function textProblem(s) {
27799
+ if (s.includes("\0")) return "contains the NUL character";
27800
+ if (LONE_SURROGATE_RE.test(s)) return "is not valid Unicode (lone surrogate)";
27801
+ return null;
27802
+ }
27803
+ function compressedSize(html) {
27804
+ return deflateSync(Buffer.from(html, "utf8"), { level: zlibConstants.Z_BEST_COMPRESSION }).length;
27805
+ }
27806
+ function htmlProblem(html) {
27807
+ if (html.length === 0) return "html is empty";
27808
+ const bad = textProblem(html);
27809
+ if (bad) return `html ${bad}`;
27810
+ const raw = utf8Bytes(html);
27811
+ if (raw > WIDGET_HTML_MAX_BYTES) return `html is ${raw} UTF-8 bytes; the limit is ${WIDGET_HTML_MAX_BYTES}`;
27812
+ const packed = compressedSize(html);
27813
+ if (packed > WIDGET_HTML_MAX_COMPRESSED) {
27814
+ return `html compresses to ${packed} bytes (zlib level 9); the limit is ${WIDGET_HTML_MAX_COMPRESSED}`;
27815
+ }
27816
+ return null;
27817
+ }
27818
+ function stateProblem(name, v2) {
27819
+ const bad = textProblem(v2);
27820
+ if (bad) return `${name} ${bad}`;
27821
+ const n = utf8Bytes(v2);
27822
+ return n > WIDGET_STATE_MAX_BYTES ? `${name} is ${n} UTF-8 bytes; the limit is ${WIDGET_STATE_MAX_BYTES}` : null;
27823
+ }
27824
+ function widgetEligible(chatId, threadId) {
27825
+ return /^[1-9][0-9]{0,15}$/.test(chatId) && !threadId;
27826
+ }
27827
+ function validRecord(v2) {
27828
+ if (!v2 || typeof v2 !== "object") return null;
27829
+ const r = v2;
27830
+ if (typeof r.ref !== "string" || !REF_RE.test(r.ref)) return null;
27831
+ if (typeof r.requestId !== "string" || !REQUEST_ID_RE.test(r.requestId)) return null;
27832
+ if (typeof r.payloadHash !== "string") return null;
27833
+ if (typeof r.owner !== "string" || !r.owner || typeof r.chatId !== "string" || !r.chatId) return null;
27834
+ const status = r.status;
27835
+ if (status !== "sending" && status !== "sent" && status !== "rejected" && status !== "unknown") return null;
27836
+ const messageId = typeof r.messageId === "number" && Number.isSafeInteger(r.messageId) ? r.messageId : 0;
27837
+ if (status === "sent" && messageId <= 0) return null;
27838
+ return {
27839
+ ref: r.ref,
27840
+ requestId: r.requestId,
27841
+ payloadHash: r.payloadHash,
27842
+ owner: r.owner,
27843
+ chatId: r.chatId,
27844
+ messageId,
27845
+ status,
27846
+ ...typeof r.detail === "string" ? { detail: r.detail } : {},
27847
+ createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date(0)).toISOString()
27848
+ };
27849
+ }
27850
+ var WidgetStore = class {
27851
+ constructor(dir, log2 = () => {
27852
+ }) {
27853
+ this.dir = dir;
27854
+ this.log = log2;
27855
+ this.path = join3(dir, "widgets.json");
27856
+ try {
27857
+ if (fs2.existsSync(this.path)) this.load(fs2.readFileSync(this.path, "utf8"));
27858
+ } catch (err) {
27859
+ this.broken = `${this.path} is unreadable or corrupt (${String(err?.message ?? err).slice(0, 120)})`;
27860
+ this.widgets = [];
27861
+ this.log(`widgets disabled for this route: ${this.broken}`);
27862
+ }
27863
+ }
27864
+ widgets = [];
27865
+ queries = [];
27866
+ queryIds = /* @__PURE__ */ new Set();
27867
+ path;
27868
+ // Set when widgets.json exists but cannot be trusted. Starting over would
27869
+ // forget unknown sends and request_ids, so the route's widgets stay off
27870
+ // until an operator repairs or removes the file.
27871
+ broken = null;
27872
+ load(raw) {
27873
+ const parsed = JSON.parse(raw);
27874
+ if (!parsed || typeof parsed !== "object" || parsed.v !== 1 || !Array.isArray(parsed.widgets) || !Array.isArray(parsed.queries)) {
27875
+ throw new Error("not a v1 widget ledger");
27876
+ }
27877
+ let interrupted = 0;
27878
+ for (const v2 of parsed.widgets) {
27879
+ const rec = validRecord(v2);
27880
+ if (!rec) throw new Error("invalid widget record");
27881
+ if (rec.status === "sending") {
27882
+ rec.status = "unknown";
27883
+ rec.detail = "connector stopped before the send outcome was known";
27884
+ interrupted += 1;
27885
+ }
27886
+ this.widgets.push(rec);
27887
+ }
27888
+ for (const q of parsed.queries) {
27889
+ if (typeof q === "string" && q && !this.queryIds.has(q)) {
27890
+ this.queries.push(q);
27891
+ this.queryIds.add(q);
27892
+ }
27893
+ }
27894
+ if (interrupted) {
27895
+ this.log(`${interrupted} widget send(s) interrupted by a restart are marked unknown`);
27896
+ this.persist();
27897
+ }
27898
+ }
27899
+ persist() {
27900
+ fs2.mkdirSync(this.dir, { recursive: true });
27901
+ const tmp = `${this.path}.tmp`;
27902
+ const data = { v: 1, widgets: this.widgets, queries: this.queries };
27903
+ fs2.writeFileSync(tmp, JSON.stringify(data), { mode: 384 });
27904
+ fs2.renameSync(tmp, this.path);
27905
+ }
27906
+ byRequest(owner, requestId) {
27907
+ return this.widgets.find((w3) => w3.owner === owner && w3.requestId === requestId);
27908
+ }
27909
+ byRef(ref) {
27910
+ return this.widgets.find((w3) => w3.ref === ref);
27911
+ }
27912
+ byMessage(chatId, messageId) {
27913
+ return this.widgets.find((w3) => w3.status === "sent" && w3.chatId === chatId && w3.messageId === messageId);
27914
+ }
27915
+ full() {
27916
+ return this.widgets.length >= MAX_WIDGETS;
27917
+ }
27918
+ // Persist a new `sending` record. Throws if it cannot be written.
27919
+ begin(owner, requestId, payloadHash, chatId) {
27920
+ if (this.broken) throw new Error(this.broken);
27921
+ if (this.full()) throw new Error("widget ledger is full");
27922
+ const rec = {
27923
+ ref: `w_${randomBytes(9).toString("base64url")}`,
27924
+ requestId,
27925
+ payloadHash,
27926
+ owner,
27927
+ chatId,
27928
+ messageId: 0,
27929
+ status: "sending",
27930
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
27931
+ };
27932
+ this.widgets.push(rec);
27933
+ try {
27934
+ this.persist();
27935
+ } catch (err) {
27936
+ this.widgets = this.widgets.filter((w3) => w3 !== rec);
27937
+ throw err;
27938
+ }
27939
+ return rec;
27940
+ }
27941
+ // Apply the send outcome. Returns false if it could not be saved: the file
27942
+ // then still says `sending`, which a restart turns into `unknown`.
27943
+ settle(rec, outcome) {
27944
+ if (outcome.status === "sent") {
27945
+ rec.status = "sent";
27946
+ rec.messageId = outcome.messageId;
27947
+ } else {
27948
+ rec.status = outcome.status;
27949
+ rec.detail = outcome.description;
27950
+ }
27951
+ try {
27952
+ this.persist();
27953
+ return true;
27954
+ } catch (err) {
27955
+ this.log(`widget record write failed: ${String(err)}`);
27956
+ return false;
27957
+ }
27958
+ }
27959
+ // Durably record a query id before it is acted on, so each query is
27960
+ // answered and forwarded at most once, across restarts too. `unsaved` means
27961
+ // the id could not be written: the caller must not act on the query.
27962
+ claimQuery(id) {
27963
+ if (this.queryIds.has(id)) return "duplicate";
27964
+ const before = this.queries.slice();
27965
+ this.queries.push(id);
27966
+ this.queryIds.add(id);
27967
+ const evicted = this.queries.length > MAX_QUERY_IDS ? this.queries.splice(0, this.queries.length - MAX_QUERY_IDS) : [];
27968
+ try {
27969
+ this.persist();
27970
+ } catch (err) {
27971
+ this.queries = before;
27972
+ this.queryIds.delete(id);
27973
+ this.log(`widget query record write failed: ${String(err)}`);
27974
+ return "unsaved";
27975
+ }
27976
+ for (const old of evicted) this.queryIds.delete(old);
27977
+ return "claimed";
27978
+ }
27979
+ };
27980
+ var stateSchema = { type: "string", maxLength: WIDGET_STATE_MAX_BYTES };
27981
+ var SEND_SCHEMA = {
27982
+ type: "object",
27983
+ additionalProperties: false,
27984
+ required: ["request_id", "html"],
27985
+ properties: {
27986
+ request_id: { type: "string", pattern: REQUEST_ID_RE.source, description: "Idempotency key: repeating it returns the first outcome and never re-sends." },
27987
+ html: { type: "string", minLength: 1, maxLength: WIDGET_HTML_MAX_BYTES, description: "Self-contained widget HTML: \u226432768 UTF-8 bytes and \u22644096 bytes after zlib level 9; no NUL." },
27988
+ chat_data: { ...stateSchema, description: "Initial chat state (TelegramWidget.chatData), \u22641024 UTF-8 bytes." },
27989
+ public_data: { ...stateSchema, description: "Initial public state (TelegramWidget.publicData), \u22641024 UTF-8 bytes." },
27990
+ caption: { type: "string", maxLength: WIDGET_CAPTION_MAX, description: "Plain-text caption, shown by clients that cannot run widgets." },
27991
+ width: { type: "integer", minimum: 1, maximum: 4096 },
27992
+ height: { type: "integer", minimum: 1, maximum: 4096 }
27993
+ }
27994
+ };
27995
+ var UPDATE_SCHEMA = {
27996
+ type: "object",
27997
+ additionalProperties: false,
27998
+ required: ["widget_ref"],
27999
+ minProperties: 2,
28000
+ properties: {
28001
+ widget_ref: { type: "string", pattern: REF_RE.source, description: "widget_ref returned by telegram_widget_send." },
28002
+ chat_data: { ...stateSchema, description: 'New chat state; "" clears it; omit to keep.' },
28003
+ public_data: { ...stateSchema, description: 'New public state; "" clears it; omit to keep.' }
28004
+ }
28005
+ };
28006
+ var refuse = (code, description) => ({ status: "rejected", code, description });
28007
+ function asObject(v2) {
28008
+ return v2 && typeof v2 === "object" && !Array.isArray(v2) ? v2 : null;
28009
+ }
28010
+ function optString(o, key) {
28011
+ if (!(key in o)) return void 0;
28012
+ return typeof o[key] === "string" ? o[key] : null;
28013
+ }
28014
+ function optInt(o, key) {
28015
+ if (!(key in o)) return void 0;
28016
+ const v2 = o[key];
28017
+ return typeof v2 === "number" && Number.isInteger(v2) && v2 >= 1 && v2 <= 4096 ? v2 : null;
28018
+ }
28019
+ function authorize(route, ctx) {
28020
+ if (!widgetEligible(route.chatId, route.threadId)) {
28021
+ return refuse("unsupported_route", "widgets need a route pinned to one private Telegram chat");
28022
+ }
28023
+ if (!route.peerCid || ctx.sender_cid !== route.peerCid) {
28024
+ return refuse("not_authorized", "only the agent connected to this route may use its widgets");
28025
+ }
28026
+ return null;
28027
+ }
28028
+ function recordResult(rec, extra = {}) {
28029
+ return {
28030
+ status: rec.status === "sending" ? "unknown" : rec.status,
28031
+ widget_ref: rec.ref,
28032
+ request_id: rec.requestId,
28033
+ ...rec.status === "sent" ? { message_id: rec.messageId } : {},
28034
+ ...rec.detail ? { description: rec.detail } : {},
28035
+ ...extra
28036
+ };
28037
+ }
28038
+ async function sendWidgetCommand(deps, args, ctx) {
28039
+ const route = deps.route();
28040
+ const denied = authorize(route, ctx);
28041
+ if (denied) return denied;
28042
+ const o = asObject(args);
28043
+ if (!o) return refuse("invalid_arguments", "arguments must be an object");
28044
+ const allowed = /* @__PURE__ */ new Set(["request_id", "html", "chat_data", "public_data", "caption", "width", "height"]);
28045
+ const extra = Object.keys(o).find((k) => !allowed.has(k));
28046
+ if (extra) return refuse("invalid_arguments", `unknown argument "${extra}"`);
28047
+ const requestId = o.request_id;
28048
+ if (typeof requestId !== "string" || !REQUEST_ID_RE.test(requestId)) {
28049
+ return refuse("invalid_arguments", "request_id must be 1-64 characters of A-Z a-z 0-9 _ -");
28050
+ }
28051
+ if (deps.store.broken) return refuse("ledger_unavailable", "widget records for this route are unreadable; an operator must repair them");
28052
+ const payloadHash = createHash("sha256").update(JSON.stringify(Object.keys(o).sort().map((k) => [k, o[k]]))).digest("hex");
28053
+ const previous = deps.store.byRequest(ctx.sender_cid, requestId);
28054
+ if (previous) {
28055
+ if (previous.payloadHash !== payloadHash) {
28056
+ return {
28057
+ status: "rejected",
28058
+ code: "request_id_conflict",
28059
+ description: "this request_id was already used with different arguments; nothing was sent",
28060
+ widget_ref: previous.ref,
28061
+ original_status: previous.status === "sending" ? "unknown" : previous.status
28062
+ };
28063
+ }
28064
+ return recordResult(previous, { duplicate: true });
28065
+ }
28066
+ if (deps.store.full()) return refuse("ledger_full", "this route has reached its widget record capacity; nothing was sent");
28067
+ if (typeof o.html !== "string") return refuse("invalid_arguments", "html must be a string");
28068
+ const html = o.html;
28069
+ const htmlBad = htmlProblem(html);
28070
+ if (htmlBad) return refuse("invalid_html", htmlBad);
28071
+ const chatData = optString(o, "chat_data");
28072
+ const publicData = optString(o, "public_data");
28073
+ const caption = optString(o, "caption");
28074
+ const width = optInt(o, "width");
28075
+ const height = optInt(o, "height");
28076
+ if (chatData === null || publicData === null || caption === null || width === null || height === null) {
28077
+ return refuse("invalid_arguments", "chat_data, public_data and caption must be strings; width and height integers 1-4096");
28078
+ }
28079
+ for (const [name, v2] of [["chat_data", chatData], ["public_data", publicData]]) {
28080
+ const bad = v2 === void 0 ? null : stateProblem(name, v2);
28081
+ if (bad) return refuse("invalid_state", bad);
28082
+ }
28083
+ if (caption !== void 0) {
28084
+ const bad = textProblem(caption);
28085
+ if (bad) return refuse("invalid_arguments", `caption ${bad}`);
28086
+ if (caption.length > WIDGET_CAPTION_MAX) return refuse("invalid_arguments", `caption is longer than ${WIDGET_CAPTION_MAX} characters`);
28087
+ }
28088
+ let rec;
28089
+ try {
28090
+ rec = deps.store.begin(ctx.sender_cid, requestId, payloadHash, route.chatId);
28091
+ } catch (err) {
28092
+ deps.log(`[${route.name}] widget record write failed, not sending: ${String(err)}`);
28093
+ return refuse("state_unwritable", "the connector could not record the send; nothing was sent");
28094
+ }
28095
+ const outcome = await deps.tg.sendWidget({
28096
+ chat_id: Number(route.chatId),
28097
+ html,
28098
+ ...width !== void 0 ? { width } : {},
28099
+ ...height !== void 0 ? { height } : {},
28100
+ ...publicData !== void 0 ? { public_data: publicData } : {},
28101
+ ...chatData !== void 0 ? { chat_data: chatData } : {},
28102
+ ...caption !== void 0 ? { caption } : {}
28103
+ });
28104
+ const saved = deps.store.settle(rec, outcome);
28105
+ deps.log(`[${route.name}] widget ${rec.ref} send ${outcome.status}${outcome.status === "sent" ? ` as message ${outcome.messageId}` : ""}`);
28106
+ if (!saved) {
28107
+ return recordResult(rec, {
28108
+ ledger_saved: false,
28109
+ warning: "the outcome could not be saved; after a connector restart this widget becomes unknown and stops accepting requests and updates"
28110
+ });
28111
+ }
28112
+ if (outcome.status === "rejected") {
28113
+ return recordResult(rec, {
28114
+ code: "telegram_refused",
28115
+ telegram_error_code: outcome.code,
28116
+ ...outcome.retryAfter !== void 0 ? { retry_after: outcome.retryAfter } : {}
28117
+ });
28118
+ }
28119
+ return recordResult(rec);
28120
+ }
28121
+ async function updateWidgetCommand(deps, args, ctx) {
28122
+ const route = deps.route();
28123
+ const denied = authorize(route, ctx);
28124
+ if (denied) return denied;
28125
+ const o = asObject(args);
28126
+ if (!o) return refuse("invalid_arguments", "arguments must be an object");
28127
+ const extra = Object.keys(o).find((k) => k !== "widget_ref" && k !== "chat_data" && k !== "public_data");
28128
+ if (extra) return refuse("invalid_arguments", `unknown argument "${extra}"`);
28129
+ const ref = o.widget_ref;
28130
+ if (typeof ref !== "string" || !REF_RE.test(ref)) return refuse("invalid_arguments", "widget_ref is malformed");
28131
+ const chatData = optString(o, "chat_data");
28132
+ const publicData = optString(o, "public_data");
28133
+ if (chatData === null || publicData === null) return refuse("invalid_arguments", "chat_data and public_data must be strings");
28134
+ if (chatData === void 0 && publicData === void 0) return refuse("invalid_arguments", "give chat_data and/or public_data");
28135
+ for (const [name, v2] of [["chat_data", chatData], ["public_data", publicData]]) {
28136
+ const bad = v2 === void 0 ? null : stateProblem(name, v2);
28137
+ if (bad) return refuse("invalid_state", bad);
28138
+ }
28139
+ if (deps.store.broken) return refuse("ledger_unavailable", "widget records for this route are unreadable; an operator must repair them");
28140
+ const rec = deps.store.byRef(ref);
28141
+ if (!rec || rec.owner !== ctx.sender_cid || rec.chatId !== route.chatId || rec.status !== "sent") {
28142
+ return refuse("unknown_widget", "no sent widget with that widget_ref belongs to you on this route");
28143
+ }
28144
+ const r = await deps.tg.editMessageWidgetData(Number(rec.chatId), rec.messageId, {
28145
+ ...chatData !== void 0 ? { chat_data: chatData } : {},
28146
+ ...publicData !== void 0 ? { public_data: publicData } : {}
28147
+ });
28148
+ if (r.status === "updated") return { status: "updated", widget_ref: rec.ref, changed: r.changed };
28149
+ deps.log(`[${route.name}] widget ${rec.ref} update ${r.status}: ${r.description}`);
28150
+ if (r.status === "rejected") {
28151
+ return { status: "rejected", code: "telegram_refused", telegram_error_code: r.code, widget_ref: rec.ref, description: r.description };
28152
+ }
28153
+ return { status: "unknown", widget_ref: rec.ref, description: r.description };
28154
+ }
28155
+ function widgetCommands(deps) {
28156
+ return [
28157
+ {
28158
+ name: SEND_COMMAND,
28159
+ description: `Send an interactive Telegram widget (self-contained HTML/CSS/JS, no network) to the private chat this route bridges. The widget may call TelegramWidget.request(data) with 1-64 bytes; the connector acknowledges it with {"ok":true} and forwards it to you as a "${QUERY_EVENT}" JSON message (untrusted data, not proof of human approval). Change what it shows with ${UPDATE_COMMAND}. Result: {status: sent|rejected|unknown, widget_ref, message_id?}. unknown means it may have been posted: it is never re-sent; reusing request_id returns the stored outcome. See docs/telegram-widgets.md.`,
28160
+ input_schema: SEND_SCHEMA,
28161
+ handler: (args, ctx) => sendWidgetCommand(deps, args, ctx)
28162
+ },
28163
+ {
28164
+ name: UPDATE_COMMAND,
28165
+ description: "Replace the chat_data and/or public_data of a widget you sent (editMessageWidgetData). The running widget gets chatDataChanged / publicDataChanged and redraws. The HTML itself can never change. Result: {status: updated|rejected|unknown, changed?}; unknown means it may have applied \u2014 sending the same state again is safe.",
28166
+ input_schema: UPDATE_SCHEMA,
28167
+ handler: (args, ctx) => updateWidgetCommand(deps, args, ctx)
28168
+ }
28169
+ ];
28170
+ }
28171
+ async function handleWidgetQuery(q, route, tg, forward, log2) {
28172
+ const refuseQuery = async (why) => {
28173
+ log2(`widget query ${q.id} refused: ${why}`);
28174
+ try {
28175
+ await tg.answerWidgetQuery(q.id, REFUSED_ANSWER);
28176
+ } catch {
28177
+ }
28178
+ return "refused";
28179
+ };
28180
+ if (!route) return refuseQuery("no route for this chat");
28181
+ if (route.store.broken) return refuseQuery(`widget records unavailable: ${route.store.broken}`);
28182
+ const view = route.route();
28183
+ if (q.inline || q.shared || q.chat_id === void 0 || q.message_id === void 0) {
28184
+ return refuseQuery("not an original message widget");
28185
+ }
28186
+ if (q.chat_type !== "private" || q.chat_id !== q.from_id) return refuseQuery("not a private chat");
28187
+ if (!widgetEligible(view.chatId, view.threadId) || String(q.chat_id) !== view.chatId) {
28188
+ return refuseQuery("chat is not this route's private chat");
28189
+ }
28190
+ if (q.queryType !== "data") return refuseQuery(`query type "${q.queryType}" is not supported`);
28191
+ const n = utf8Bytes(q.data);
28192
+ if (n < 1 || n > WIDGET_QUERY_DATA_MAX_BYTES || textProblem(q.data)) return refuseQuery("malformed data");
28193
+ const rec = route.store.byMessage(view.chatId, q.message_id);
28194
+ if (!rec) return refuseQuery(`message ${q.message_id} is not a widget sent through this route`);
28195
+ if (!view.peerCid || rec.owner !== view.peerCid) return refuseQuery("the widget's agent is no longer this route's agent");
28196
+ const claim = route.store.claimQuery(q.id);
28197
+ if (claim === "duplicate") {
28198
+ log2(`widget query ${q.id} is a duplicate update \u2014 ignored`);
28199
+ return "duplicate";
28200
+ }
28201
+ if (claim === "unsaved") return refuseQuery("its id could not be recorded, so it cannot be deduplicated");
28202
+ try {
28203
+ await tg.answerWidgetQuery(q.id, ACCEPTED_ANSWER);
28204
+ } catch (err) {
28205
+ log2(`widget query ${q.id} could not be answered (stale?) \u2014 not forwarded: ${String(err)}`);
28206
+ return "stale";
28207
+ }
28208
+ const event = {
28209
+ type: QUERY_EVENT,
28210
+ widget_ref: rec.ref,
28211
+ request_id: rec.requestId,
28212
+ message_id: rec.messageId,
28213
+ from: { id: q.from_id, label: q.from },
28214
+ data: q.data,
28215
+ note: QUERY_NOTE
28216
+ };
28217
+ try {
28218
+ await forward(rec.owner, JSON.stringify(event));
28219
+ } catch (err) {
28220
+ log2(`widget query ${q.id} answered but forwarding to the agent failed: ${String(err)}`);
28221
+ return "undelivered";
28222
+ }
28223
+ return "forwarded";
28224
+ }
28225
+
27620
28226
  // src/envelope.ts
27621
28227
  var ENVELOPE_VERSION = 2;
27622
28228
  var VOICE_MESSAGE_MIME = "audio/ogg; x-ours-kind=voice-message";
@@ -27841,8 +28447,8 @@ function deliveryTarget(chatId, threadId, lastChat) {
27841
28447
  var DEFAULT_DENIED = "You are not allowed to speak to this bot, please contact the admin.";
27842
28448
 
27843
28449
  // src/msgmap.ts
27844
- import * as fs2 from "node:fs";
27845
- import { join as join3 } from "node:path";
28450
+ import * as fs3 from "node:fs";
28451
+ import { join as join4 } from "node:path";
27846
28452
 
27847
28453
  // src/receipts.ts
27848
28454
  var ALLOWED_REACTIONS = [
@@ -28108,10 +28714,10 @@ var MessageMap = class {
28108
28714
  }) {
28109
28715
  this.dir = dir;
28110
28716
  this.log = log2;
28111
- this.path = join3(dir, FILE_NAME);
28717
+ this.path = join4(dir, FILE_NAME);
28112
28718
  this.data = emptyFile();
28113
28719
  try {
28114
- if (fs2.existsSync(this.path)) this.data = parseMapFile(fs2.readFileSync(this.path, "utf8"), Date.now());
28720
+ if (fs3.existsSync(this.path)) this.data = parseMapFile(fs3.readFileSync(this.path, "utf8"), Date.now());
28115
28721
  } catch (err) {
28116
28722
  this.log(`message map unreadable, starting empty: ${String(err)}`);
28117
28723
  }
@@ -28120,10 +28726,10 @@ var MessageMap = class {
28120
28726
  path;
28121
28727
  persist() {
28122
28728
  try {
28123
- fs2.mkdirSync(this.dir, { recursive: true });
28729
+ fs3.mkdirSync(this.dir, { recursive: true });
28124
28730
  const tmp = `${this.path}.tmp`;
28125
- fs2.writeFileSync(tmp, JSON.stringify(this.data), { mode: 384 });
28126
- fs2.renameSync(tmp, this.path);
28731
+ fs3.writeFileSync(tmp, JSON.stringify(this.data), { mode: 384 });
28732
+ fs3.renameSync(tmp, this.path);
28127
28733
  } catch (err) {
28128
28734
  this.log(`message map write failed: ${String(err)}`);
28129
28735
  }
@@ -28208,6 +28814,10 @@ async function drainMessages(client, deliver) {
28208
28814
  const pending = await client.listIncomingMessages();
28209
28815
  if (pending.length === 0) return delivered;
28210
28816
  for (const ref of pending) {
28817
+ if (ref.message_kind === "command" || ref.message_kind === "command_result") {
28818
+ await consumeTyped(client, ref);
28819
+ continue;
28820
+ }
28211
28821
  const item = await client.getHistoryItem({ wire_id: ref.wire_id });
28212
28822
  if (!item || item.direction !== "in" || item.inbox_state !== "unread") {
28213
28823
  throw new Error(`history lookup for unread message ${ref.wire_id} did not return that unread inbound row`);
@@ -28222,6 +28832,15 @@ async function drainMessages(client, deliver) {
28222
28832
  }
28223
28833
  }
28224
28834
  }
28835
+ async function consumeTyped(client, ref) {
28836
+ const ack = await client.getMessages({ limit: 1 });
28837
+ const results = ack.command_results ?? [];
28838
+ const ok = ref.message_kind === "command" ? ack.messages.length === 0 && results.length === 0 && ack.commands_handled === 1 : ack.messages.length === 0 && results.length === 1 && results[0].wire_id === ref.wire_id && !ack.commands_handled;
28839
+ if (!ok) {
28840
+ const got = [...ack.messages.map((m2) => m2.wire_id), ...results.map((r) => r.wire_id)].join(", ") || `${ack.commands_handled ?? 0} command(s)`;
28841
+ throw new Error(`oldest-first ${ref.message_kind} ack mismatch: expected ${ref.wire_id}, got ${got}`);
28842
+ }
28843
+ }
28225
28844
  async function drainFiles(client, deliver) {
28226
28845
  let delivered = 0;
28227
28846
  for (; ; ) {
@@ -28310,6 +28929,12 @@ function makeConnection(client, dir, cfg, bot) {
28310
28929
  drainMessages: singleFlight(() => forwardToTelegram(conn)),
28311
28930
  drainFiles: singleFlight(() => forwardFilesToTelegram(conn)),
28312
28931
  syncReceipts: singleFlight(() => syncReceiptHistory(conn)),
28932
+ widgets: {
28933
+ route: () => ({ name: cfg.name, chatId: cfg.chatId, threadId: cfg.threadId, peerCid: cfg.peerCid }),
28934
+ tg: bot.tg,
28935
+ store: new WidgetStore(dir, (m2) => log(`[${cfg.name}] ${m2}`)),
28936
+ log: (m2) => log(m2)
28937
+ },
28313
28938
  watch: null,
28314
28939
  watchHandle: null,
28315
28940
  inbound: null
@@ -28339,7 +28964,7 @@ function daemonSelectionOptions() {
28339
28964
  async function attachToDaemon() {
28340
28965
  const options = daemonSelectionOptions();
28341
28966
  const legacy = options.expectedInstanceId ? null : De(options);
28342
- const client = await Q({ ...options, leaseToken: randomBytes(24).toString("hex") });
28967
+ const client = await Q({ ...options, leaseToken: randomBytes2(24).toString("hex") });
28343
28968
  try {
28344
28969
  daemonIdentityNames = new Set((await client.identities()).map((row) => row.name));
28345
28970
  log(`attached to daemon ${JSON.stringify(legacy ? un(legacy) : {
@@ -28365,15 +28990,15 @@ function routeNameError(name) {
28365
28990
  }
28366
28991
  return null;
28367
28992
  }
28368
- var connDir = (name) => join4(STATE_DIR, name);
28369
- var metaPath = (dir) => join4(dir, "connection.json");
28370
- var botsPath = () => join4(STATE_DIR, "bots.json");
28993
+ var connDir = (name) => join5(STATE_DIR, name);
28994
+ var metaPath = (dir) => join5(dir, "connection.json");
28995
+ var botsPath = () => join5(STATE_DIR, "bots.json");
28371
28996
  function listPersistedNames() {
28372
- if (!fs3.existsSync(STATE_DIR)) return [];
28373
- return fs3.readdirSync(STATE_DIR, { withFileTypes: true }).filter((d2) => d2.isDirectory() && fs3.existsSync(metaPath(join4(STATE_DIR, d2.name)))).map((d2) => d2.name);
28997
+ if (!fs4.existsSync(STATE_DIR)) return [];
28998
+ return fs4.readdirSync(STATE_DIR, { withFileTypes: true }).filter((d2) => d2.isDirectory() && fs4.existsSync(metaPath(join5(STATE_DIR, d2.name)))).map((d2) => d2.name);
28374
28999
  }
28375
29000
  function readMeta(dir) {
28376
- const cfg = JSON.parse(fs3.readFileSync(metaPath(dir), "utf8"));
29001
+ const cfg = JSON.parse(fs4.readFileSync(metaPath(dir), "utf8"));
28377
29002
  if (typeof cfg.threadId !== "string") cfg.threadId = "";
28378
29003
  if (typeof cfg.bio !== "string") cfg.bio = "";
28379
29004
  if (typeof cfg.deniedMessage !== "string") cfg.deniedMessage = DEFAULT_DENIED;
@@ -28381,17 +29006,17 @@ function readMeta(dir) {
28381
29006
  return cfg;
28382
29007
  }
28383
29008
  function writeMeta(dir, cfg) {
28384
- fs3.mkdirSync(dir, { recursive: true });
29009
+ fs4.mkdirSync(dir, { recursive: true });
28385
29010
  const tmp = `${metaPath(dir)}.tmp`;
28386
- fs3.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 384 });
28387
- fs3.renameSync(tmp, metaPath(dir));
29011
+ fs4.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 384 });
29012
+ fs4.renameSync(tmp, metaPath(dir));
28388
29013
  }
28389
29014
  function botLabel(bot) {
28390
29015
  return bot.username ? `${bot.name} (@${bot.username})` : bot.name;
28391
29016
  }
28392
29017
  function loadBotRegistry() {
28393
29018
  try {
28394
- const raw = JSON.parse(fs3.readFileSync(botsPath(), "utf8"));
29019
+ const raw = JSON.parse(fs4.readFileSync(botsPath(), "utf8"));
28395
29020
  return Object.values(raw.bots ?? {});
28396
29021
  } catch {
28397
29022
  return [];
@@ -28404,10 +29029,10 @@ function saveBotRegistry() {
28404
29029
  [...bots.values()].map((b2) => [b2.name, { name: b2.name, token: b2.token, username: b2.username, createdAt: b2.createdAt }])
28405
29030
  )
28406
29031
  };
28407
- fs3.mkdirSync(STATE_DIR, { recursive: true });
29032
+ fs4.mkdirSync(STATE_DIR, { recursive: true });
28408
29033
  const tmp = `${botsPath()}.tmp`;
28409
- fs3.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
28410
- fs3.renameSync(tmp, botsPath());
29034
+ fs4.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
29035
+ fs4.renameSync(tmp, botsPath());
28411
29036
  }
28412
29037
  function instantiateBot(rec) {
28413
29038
  const tg = new TelegramClient(rec.token, CONFIG.pollTimeoutSec, (m2) => log(`[bot ${rec.name}] tg: ${m2}`), TG_NET);
@@ -28490,6 +29115,30 @@ function sttEngineLabel(baseUrl) {
28490
29115
  return "stt";
28491
29116
  }
28492
29117
  }
29118
+ async function registerWidgetCommands(conn) {
29119
+ const { cfg } = conn;
29120
+ if (!widgetEligible(cfg.chatId, cfg.threadId)) return;
29121
+ try {
29122
+ await conn.client.registerCommands(widgetCommands(conn.widgets));
29123
+ } catch (err) {
29124
+ log(`[${cfg.name}] registering widget commands failed (widgets unavailable on this route):`, String(err));
29125
+ }
29126
+ }
29127
+ async function onBotWidgetQuery(bot, q) {
29128
+ const conn = q.chat_id !== void 0 ? bot.exact.get(chatKey(q.chat_id)) ?? null : null;
29129
+ const tag = conn ? `[${conn.cfg.name}]` : `[bot ${botLabel(bot)}]`;
29130
+ const outcome = await handleWidgetQuery(
29131
+ q,
29132
+ conn?.widgets ?? null,
29133
+ bot.tg,
29134
+ async (owner, text2) => {
29135
+ const sent = await conn.client.sendMessage({ contact: owner, text: text2 });
29136
+ if (sent.kind !== "sent" && sent.kind !== "e2e") log(`${tag} widget query event to ${owner}: ${sent.kind}`);
29137
+ },
29138
+ (m2) => log(`${tag} ${m2}`)
29139
+ );
29140
+ if (outcome === "forwarded") log(`${tag} widget query forwarded to the agent`);
29141
+ }
28493
29142
  function watchRoute(conn) {
28494
29143
  if (conn.watch) return;
28495
29144
  const ctrl = new AbortController();
@@ -28845,7 +29494,7 @@ async function onBotMessage(bot, m2) {
28845
29494
  }
28846
29495
  function activateBot(bot) {
28847
29496
  if (bot.pollHandle) return;
28848
- bot.pollHandle = bot.tg.poll((m2) => onBotMessage(bot, m2));
29497
+ bot.pollHandle = bot.tg.poll((m2) => onBotMessage(bot, m2), (q) => onBotWidgetQuery(bot, q));
28849
29498
  void publishBotCommands(bot);
28850
29499
  }
28851
29500
  async function publishBotCommands(bot) {
@@ -28866,7 +29515,7 @@ async function createConnection(args) {
28866
29515
  const slotErr = routeSlotConflict(bot, args.chatId, args.threadId);
28867
29516
  if (slotErr) throw new Error(slotErr);
28868
29517
  const dir = connDir(args.name);
28869
- fs3.mkdirSync(dir, { recursive: true });
29518
+ fs4.mkdirSync(dir, { recursive: true });
28870
29519
  const cfg = {
28871
29520
  v: 1,
28872
29521
  name: args.name,
@@ -28879,7 +29528,7 @@ async function createConnection(args) {
28879
29528
  deniedMessage: DEFAULT_DENIED,
28880
29529
  peerCid: "",
28881
29530
  // Minted once, here, and persisted. See ConnectionFile.leaseToken.
28882
- leaseToken: randomBytes(24).toString("hex"),
29531
+ leaseToken: randomBytes2(24).toString("hex"),
28883
29532
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
28884
29533
  };
28885
29534
  const client = await clientFor(cfg);
@@ -28897,6 +29546,7 @@ async function createConnection(args) {
28897
29546
  ownedIdentityNames.add(args.name);
28898
29547
  daemonIdentityNames.add(args.name);
28899
29548
  writeMeta(dir, cfg);
29549
+ await registerWidgetCommands(conn);
28900
29550
  watchRoute(conn);
28901
29551
  activateBot(bot);
28902
29552
  const invite = await client.generateInvite({});
@@ -28916,7 +29566,7 @@ async function createConnection(args) {
28916
29566
  } catch {
28917
29567
  }
28918
29568
  try {
28919
- fs3.rmSync(connDir(args.name), { recursive: true, force: true });
29569
+ fs4.rmSync(connDir(args.name), { recursive: true, force: true });
28920
29570
  } catch {
28921
29571
  }
28922
29572
  }
@@ -28929,7 +29579,7 @@ async function restoreConnection(name) {
28929
29579
  const bot = bots.get(cfg.botName);
28930
29580
  if (!bot) throw new Error(`route "${name}" references unknown bot "${cfg.botName}"`);
28931
29581
  if (!cfg.leaseToken) {
28932
- cfg.leaseToken = randomBytes(24).toString("hex");
29582
+ cfg.leaseToken = randomBytes2(24).toString("hex");
28933
29583
  writeMeta(dir, cfg);
28934
29584
  log(`[${name}] minted a lease token for a legacy route`);
28935
29585
  }
@@ -28949,6 +29599,7 @@ async function restoreConnection(name) {
28949
29599
  connections.set(name, conn);
28950
29600
  const conflict = registerRoute(conn);
28951
29601
  if (conflict) throw new Error(conflict);
29602
+ await registerWidgetCommands(conn);
28952
29603
  watchRoute(conn);
28953
29604
  await Promise.all([conn.drainMessages(), conn.drainFiles(), conn.syncReceipts()]);
28954
29605
  log(`[${name}] route restored (bot ${botLabel(bot)})`);
@@ -28982,11 +29633,11 @@ async function removeConnection(name) {
28982
29633
  const conn = connections.get(name);
28983
29634
  if (!conn) {
28984
29635
  const dir = connDir(name);
28985
- if (!fs3.existsSync(metaPath(dir))) {
29636
+ if (!fs4.existsSync(metaPath(dir))) {
28986
29637
  return { found: false, localRemoved: false, identityRemoved: false, identityLeftBehind: false, error: `no connection named "${name}"` };
28987
29638
  }
28988
29639
  try {
28989
- fs3.rmSync(dir, { recursive: true, force: true });
29640
+ fs4.rmSync(dir, { recursive: true, force: true });
28990
29641
  } catch (err) {
28991
29642
  return {
28992
29643
  found: true,
@@ -29034,7 +29685,7 @@ async function removeConnection(name) {
29034
29685
  }
29035
29686
  connections.delete(name);
29036
29687
  try {
29037
- fs3.rmSync(conn.dir, { recursive: true, force: true });
29688
+ fs4.rmSync(conn.dir, { recursive: true, force: true });
29038
29689
  } catch (err) {
29039
29690
  return {
29040
29691
  found: true,