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

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,465 @@ 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
+ async function routeForCommand(deps) {
27981
+ if (!deps.route().peerCid && deps.ensureBound) await deps.ensureBound("command");
27982
+ return deps.route();
27983
+ }
27984
+ var stateSchema = { type: "string", maxLength: WIDGET_STATE_MAX_BYTES };
27985
+ var SEND_SCHEMA = {
27986
+ type: "object",
27987
+ additionalProperties: false,
27988
+ required: ["request_id", "html"],
27989
+ properties: {
27990
+ request_id: { type: "string", pattern: REQUEST_ID_RE.source, description: "Idempotency key: repeating it returns the first outcome and never re-sends." },
27991
+ 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." },
27992
+ chat_data: { ...stateSchema, description: "Initial chat state (TelegramWidget.chatData), \u22641024 UTF-8 bytes." },
27993
+ public_data: { ...stateSchema, description: "Initial public state (TelegramWidget.publicData), \u22641024 UTF-8 bytes." },
27994
+ caption: { type: "string", maxLength: WIDGET_CAPTION_MAX, description: "Plain-text caption, shown by clients that cannot run widgets." },
27995
+ width: { type: "integer", minimum: 1, maximum: 4096 },
27996
+ height: { type: "integer", minimum: 1, maximum: 4096 }
27997
+ }
27998
+ };
27999
+ var UPDATE_SCHEMA = {
28000
+ type: "object",
28001
+ additionalProperties: false,
28002
+ required: ["widget_ref"],
28003
+ minProperties: 2,
28004
+ properties: {
28005
+ widget_ref: { type: "string", pattern: REF_RE.source, description: "widget_ref returned by telegram_widget_send." },
28006
+ chat_data: { ...stateSchema, description: 'New chat state; "" clears it; omit to keep.' },
28007
+ public_data: { ...stateSchema, description: 'New public state; "" clears it; omit to keep.' }
28008
+ }
28009
+ };
28010
+ var refuse = (code, description) => ({ status: "rejected", code, description });
28011
+ function asObject(v2) {
28012
+ return v2 && typeof v2 === "object" && !Array.isArray(v2) ? v2 : null;
28013
+ }
28014
+ function optString(o, key) {
28015
+ if (!(key in o)) return void 0;
28016
+ return typeof o[key] === "string" ? o[key] : null;
28017
+ }
28018
+ function optInt(o, key) {
28019
+ if (!(key in o)) return void 0;
28020
+ const v2 = o[key];
28021
+ return typeof v2 === "number" && Number.isInteger(v2) && v2 >= 1 && v2 <= 4096 ? v2 : null;
28022
+ }
28023
+ function authorize(route, ctx) {
28024
+ if (!widgetEligible(route.chatId, route.threadId)) {
28025
+ return refuse("unsupported_route", "widgets need a route pinned to one private Telegram chat");
28026
+ }
28027
+ if (!route.peerCid || ctx.sender_cid !== route.peerCid) {
28028
+ return refuse("not_authorized", "only the agent connected to this route may use its widgets");
28029
+ }
28030
+ return null;
28031
+ }
28032
+ function recordResult(rec, extra = {}) {
28033
+ return {
28034
+ status: rec.status === "sending" ? "unknown" : rec.status,
28035
+ widget_ref: rec.ref,
28036
+ request_id: rec.requestId,
28037
+ ...rec.status === "sent" ? { message_id: rec.messageId } : {},
28038
+ ...rec.detail ? { description: rec.detail } : {},
28039
+ ...extra
28040
+ };
28041
+ }
28042
+ async function sendWidgetCommand(deps, args, ctx) {
28043
+ const route = await routeForCommand(deps);
28044
+ const denied = authorize(route, ctx);
28045
+ if (denied) return denied;
28046
+ const o = asObject(args);
28047
+ if (!o) return refuse("invalid_arguments", "arguments must be an object");
28048
+ const allowed = /* @__PURE__ */ new Set(["request_id", "html", "chat_data", "public_data", "caption", "width", "height"]);
28049
+ const extra = Object.keys(o).find((k) => !allowed.has(k));
28050
+ if (extra) return refuse("invalid_arguments", `unknown argument "${extra}"`);
28051
+ const requestId = o.request_id;
28052
+ if (typeof requestId !== "string" || !REQUEST_ID_RE.test(requestId)) {
28053
+ return refuse("invalid_arguments", "request_id must be 1-64 characters of A-Z a-z 0-9 _ -");
28054
+ }
28055
+ if (deps.store.broken) return refuse("ledger_unavailable", "widget records for this route are unreadable; an operator must repair them");
28056
+ const payloadHash = createHash("sha256").update(JSON.stringify(Object.keys(o).sort().map((k) => [k, o[k]]))).digest("hex");
28057
+ const previous = deps.store.byRequest(ctx.sender_cid, requestId);
28058
+ if (previous) {
28059
+ if (previous.payloadHash !== payloadHash) {
28060
+ return {
28061
+ status: "rejected",
28062
+ code: "request_id_conflict",
28063
+ description: "this request_id was already used with different arguments; nothing was sent",
28064
+ widget_ref: previous.ref,
28065
+ original_status: previous.status === "sending" ? "unknown" : previous.status
28066
+ };
28067
+ }
28068
+ return recordResult(previous, { duplicate: true });
28069
+ }
28070
+ if (deps.store.full()) return refuse("ledger_full", "this route has reached its widget record capacity; nothing was sent");
28071
+ if (typeof o.html !== "string") return refuse("invalid_arguments", "html must be a string");
28072
+ const html = o.html;
28073
+ const htmlBad = htmlProblem(html);
28074
+ if (htmlBad) return refuse("invalid_html", htmlBad);
28075
+ const chatData = optString(o, "chat_data");
28076
+ const publicData = optString(o, "public_data");
28077
+ const caption = optString(o, "caption");
28078
+ const width = optInt(o, "width");
28079
+ const height = optInt(o, "height");
28080
+ if (chatData === null || publicData === null || caption === null || width === null || height === null) {
28081
+ return refuse("invalid_arguments", "chat_data, public_data and caption must be strings; width and height integers 1-4096");
28082
+ }
28083
+ for (const [name, v2] of [["chat_data", chatData], ["public_data", publicData]]) {
28084
+ const bad = v2 === void 0 ? null : stateProblem(name, v2);
28085
+ if (bad) return refuse("invalid_state", bad);
28086
+ }
28087
+ if (caption !== void 0) {
28088
+ const bad = textProblem(caption);
28089
+ if (bad) return refuse("invalid_arguments", `caption ${bad}`);
28090
+ if (caption.length > WIDGET_CAPTION_MAX) return refuse("invalid_arguments", `caption is longer than ${WIDGET_CAPTION_MAX} characters`);
28091
+ }
28092
+ let rec;
28093
+ try {
28094
+ rec = deps.store.begin(ctx.sender_cid, requestId, payloadHash, route.chatId);
28095
+ } catch (err) {
28096
+ deps.log(`[${route.name}] widget record write failed, not sending: ${String(err)}`);
28097
+ return refuse("state_unwritable", "the connector could not record the send; nothing was sent");
28098
+ }
28099
+ const outcome = await deps.tg.sendWidget({
28100
+ chat_id: Number(route.chatId),
28101
+ html,
28102
+ ...width !== void 0 ? { width } : {},
28103
+ ...height !== void 0 ? { height } : {},
28104
+ ...publicData !== void 0 ? { public_data: publicData } : {},
28105
+ ...chatData !== void 0 ? { chat_data: chatData } : {},
28106
+ ...caption !== void 0 ? { caption } : {}
28107
+ });
28108
+ const saved = deps.store.settle(rec, outcome);
28109
+ deps.log(`[${route.name}] widget ${rec.ref} send ${outcome.status}${outcome.status === "sent" ? ` as message ${outcome.messageId}` : ""}`);
28110
+ if (!saved) {
28111
+ return recordResult(rec, {
28112
+ ledger_saved: false,
28113
+ warning: "the outcome could not be saved; after a connector restart this widget becomes unknown and stops accepting requests and updates"
28114
+ });
28115
+ }
28116
+ if (outcome.status === "rejected") {
28117
+ return recordResult(rec, {
28118
+ code: "telegram_refused",
28119
+ telegram_error_code: outcome.code,
28120
+ ...outcome.retryAfter !== void 0 ? { retry_after: outcome.retryAfter } : {}
28121
+ });
28122
+ }
28123
+ return recordResult(rec);
28124
+ }
28125
+ async function updateWidgetCommand(deps, args, ctx) {
28126
+ const route = await routeForCommand(deps);
28127
+ const denied = authorize(route, ctx);
28128
+ if (denied) return denied;
28129
+ const o = asObject(args);
28130
+ if (!o) return refuse("invalid_arguments", "arguments must be an object");
28131
+ const extra = Object.keys(o).find((k) => k !== "widget_ref" && k !== "chat_data" && k !== "public_data");
28132
+ if (extra) return refuse("invalid_arguments", `unknown argument "${extra}"`);
28133
+ const ref = o.widget_ref;
28134
+ if (typeof ref !== "string" || !REF_RE.test(ref)) return refuse("invalid_arguments", "widget_ref is malformed");
28135
+ const chatData = optString(o, "chat_data");
28136
+ const publicData = optString(o, "public_data");
28137
+ if (chatData === null || publicData === null) return refuse("invalid_arguments", "chat_data and public_data must be strings");
28138
+ if (chatData === void 0 && publicData === void 0) return refuse("invalid_arguments", "give chat_data and/or public_data");
28139
+ for (const [name, v2] of [["chat_data", chatData], ["public_data", publicData]]) {
28140
+ const bad = v2 === void 0 ? null : stateProblem(name, v2);
28141
+ if (bad) return refuse("invalid_state", bad);
28142
+ }
28143
+ if (deps.store.broken) return refuse("ledger_unavailable", "widget records for this route are unreadable; an operator must repair them");
28144
+ const rec = deps.store.byRef(ref);
28145
+ if (!rec || rec.owner !== ctx.sender_cid || rec.chatId !== route.chatId || rec.status !== "sent") {
28146
+ return refuse("unknown_widget", "no sent widget with that widget_ref belongs to you on this route");
28147
+ }
28148
+ const r = await deps.tg.editMessageWidgetData(Number(rec.chatId), rec.messageId, {
28149
+ ...chatData !== void 0 ? { chat_data: chatData } : {},
28150
+ ...publicData !== void 0 ? { public_data: publicData } : {}
28151
+ });
28152
+ if (r.status === "updated") return { status: "updated", widget_ref: rec.ref, changed: r.changed };
28153
+ deps.log(`[${route.name}] widget ${rec.ref} update ${r.status}: ${r.description}`);
28154
+ if (r.status === "rejected") {
28155
+ return { status: "rejected", code: "telegram_refused", telegram_error_code: r.code, widget_ref: rec.ref, description: r.description };
28156
+ }
28157
+ return { status: "unknown", widget_ref: rec.ref, description: r.description };
28158
+ }
28159
+ function widgetCommands(deps) {
28160
+ return [
28161
+ {
28162
+ name: SEND_COMMAND,
28163
+ 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.`,
28164
+ input_schema: SEND_SCHEMA,
28165
+ handler: (args, ctx) => sendWidgetCommand(deps, args, ctx)
28166
+ },
28167
+ {
28168
+ name: UPDATE_COMMAND,
28169
+ 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.",
28170
+ input_schema: UPDATE_SCHEMA,
28171
+ handler: (args, ctx) => updateWidgetCommand(deps, args, ctx)
28172
+ }
28173
+ ];
28174
+ }
28175
+ async function handleWidgetQuery(q, route, tg, forward, log2) {
28176
+ const refuseQuery = async (why) => {
28177
+ log2(`widget query ${q.id} refused: ${why}`);
28178
+ try {
28179
+ await tg.answerWidgetQuery(q.id, REFUSED_ANSWER);
28180
+ } catch {
28181
+ }
28182
+ return "refused";
28183
+ };
28184
+ if (!route) return refuseQuery("no route for this chat");
28185
+ if (route.store.broken) return refuseQuery(`widget records unavailable: ${route.store.broken}`);
28186
+ const view = route.route();
28187
+ if (q.inline || q.shared || q.chat_id === void 0 || q.message_id === void 0) {
28188
+ return refuseQuery("not an original message widget");
28189
+ }
28190
+ if (q.chat_type !== "private" || q.chat_id !== q.from_id) return refuseQuery("not a private chat");
28191
+ if (!widgetEligible(view.chatId, view.threadId) || String(q.chat_id) !== view.chatId) {
28192
+ return refuseQuery("chat is not this route's private chat");
28193
+ }
28194
+ if (q.queryType !== "data") return refuseQuery(`query type "${q.queryType}" is not supported`);
28195
+ const n = utf8Bytes(q.data);
28196
+ if (n < 1 || n > WIDGET_QUERY_DATA_MAX_BYTES || textProblem(q.data)) return refuseQuery("malformed data");
28197
+ const rec = route.store.byMessage(view.chatId, q.message_id);
28198
+ if (!rec) return refuseQuery(`message ${q.message_id} is not a widget sent through this route`);
28199
+ if (!view.peerCid || rec.owner !== view.peerCid) return refuseQuery("the widget's agent is no longer this route's agent");
28200
+ const claim = route.store.claimQuery(q.id);
28201
+ if (claim === "duplicate") {
28202
+ log2(`widget query ${q.id} is a duplicate update \u2014 ignored`);
28203
+ return "duplicate";
28204
+ }
28205
+ if (claim === "unsaved") return refuseQuery("its id could not be recorded, so it cannot be deduplicated");
28206
+ try {
28207
+ await tg.answerWidgetQuery(q.id, ACCEPTED_ANSWER);
28208
+ } catch (err) {
28209
+ log2(`widget query ${q.id} could not be answered (stale?) \u2014 not forwarded: ${String(err)}`);
28210
+ return "stale";
28211
+ }
28212
+ const event = {
28213
+ type: QUERY_EVENT,
28214
+ widget_ref: rec.ref,
28215
+ request_id: rec.requestId,
28216
+ message_id: rec.messageId,
28217
+ from: { id: q.from_id, label: q.from },
28218
+ data: q.data,
28219
+ note: QUERY_NOTE
28220
+ };
28221
+ try {
28222
+ await forward(rec.owner, JSON.stringify(event));
28223
+ } catch (err) {
28224
+ log2(`widget query ${q.id} answered but forwarding to the agent failed: ${String(err)}`);
28225
+ return "undelivered";
28226
+ }
28227
+ return "forwarded";
28228
+ }
28229
+
27620
28230
  // src/envelope.ts
27621
28231
  var ENVELOPE_VERSION = 2;
27622
28232
  var VOICE_MESSAGE_MIME = "audio/ogg; x-ours-kind=voice-message";
@@ -27841,8 +28451,8 @@ function deliveryTarget(chatId, threadId, lastChat) {
27841
28451
  var DEFAULT_DENIED = "You are not allowed to speak to this bot, please contact the admin.";
27842
28452
 
27843
28453
  // src/msgmap.ts
27844
- import * as fs2 from "node:fs";
27845
- import { join as join3 } from "node:path";
28454
+ import * as fs3 from "node:fs";
28455
+ import { join as join4 } from "node:path";
27846
28456
 
27847
28457
  // src/receipts.ts
27848
28458
  var ALLOWED_REACTIONS = [
@@ -28108,10 +28718,10 @@ var MessageMap = class {
28108
28718
  }) {
28109
28719
  this.dir = dir;
28110
28720
  this.log = log2;
28111
- this.path = join3(dir, FILE_NAME);
28721
+ this.path = join4(dir, FILE_NAME);
28112
28722
  this.data = emptyFile();
28113
28723
  try {
28114
- if (fs2.existsSync(this.path)) this.data = parseMapFile(fs2.readFileSync(this.path, "utf8"), Date.now());
28724
+ if (fs3.existsSync(this.path)) this.data = parseMapFile(fs3.readFileSync(this.path, "utf8"), Date.now());
28115
28725
  } catch (err) {
28116
28726
  this.log(`message map unreadable, starting empty: ${String(err)}`);
28117
28727
  }
@@ -28120,10 +28730,10 @@ var MessageMap = class {
28120
28730
  path;
28121
28731
  persist() {
28122
28732
  try {
28123
- fs2.mkdirSync(this.dir, { recursive: true });
28733
+ fs3.mkdirSync(this.dir, { recursive: true });
28124
28734
  const tmp = `${this.path}.tmp`;
28125
- fs2.writeFileSync(tmp, JSON.stringify(this.data), { mode: 384 });
28126
- fs2.renameSync(tmp, this.path);
28735
+ fs3.writeFileSync(tmp, JSON.stringify(this.data), { mode: 384 });
28736
+ fs3.renameSync(tmp, this.path);
28127
28737
  } catch (err) {
28128
28738
  this.log(`message map write failed: ${String(err)}`);
28129
28739
  }
@@ -28208,6 +28818,10 @@ async function drainMessages(client, deliver) {
28208
28818
  const pending = await client.listIncomingMessages();
28209
28819
  if (pending.length === 0) return delivered;
28210
28820
  for (const ref of pending) {
28821
+ if (ref.message_kind === "command" || ref.message_kind === "command_result") {
28822
+ await consumeTyped(client, ref);
28823
+ continue;
28824
+ }
28211
28825
  const item = await client.getHistoryItem({ wire_id: ref.wire_id });
28212
28826
  if (!item || item.direction !== "in" || item.inbox_state !== "unread") {
28213
28827
  throw new Error(`history lookup for unread message ${ref.wire_id} did not return that unread inbound row`);
@@ -28222,6 +28836,15 @@ async function drainMessages(client, deliver) {
28222
28836
  }
28223
28837
  }
28224
28838
  }
28839
+ async function consumeTyped(client, ref) {
28840
+ const ack = await client.getMessages({ limit: 1 });
28841
+ const results = ack.command_results ?? [];
28842
+ 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;
28843
+ if (!ok) {
28844
+ const got = [...ack.messages.map((m2) => m2.wire_id), ...results.map((r) => r.wire_id)].join(", ") || `${ack.commands_handled ?? 0} command(s)`;
28845
+ throw new Error(`oldest-first ${ref.message_kind} ack mismatch: expected ${ref.wire_id}, got ${got}`);
28846
+ }
28847
+ }
28225
28848
  async function drainFiles(client, deliver) {
28226
28849
  let delivered = 0;
28227
28850
  for (; ; ) {
@@ -28287,6 +28910,47 @@ function singleFlight(task) {
28287
28910
  return Object.assign(run, { idle: () => active ?? Promise.resolve() });
28288
28911
  }
28289
28912
 
28913
+ // src/proxy-binding.ts
28914
+ var CONTAINER_ID = /^[0-9A-F]{64}$/;
28915
+ function makeProxyBinder(deps) {
28916
+ let chain = Promise.resolve();
28917
+ const evaluate = async (reason) => {
28918
+ if (deps.current()) return "kept";
28919
+ let contacts;
28920
+ try {
28921
+ contacts = await deps.listContacts();
28922
+ } catch (err) {
28923
+ deps.log(`proxy agent not bound (${reason}): listing contacts failed: ${String(err)}`);
28924
+ return "error";
28925
+ }
28926
+ if (deps.current()) return "kept";
28927
+ if (contacts.length === 0) return "none";
28928
+ if (contacts.length > 1) {
28929
+ deps.log(`proxy agent not bound (${reason}): the route has ${contacts.length} contacts; widgets stay unavailable until exactly one remains`);
28930
+ return "ambiguous";
28931
+ }
28932
+ const [only] = contacts;
28933
+ if (typeof only.container_id !== "string" || !CONTAINER_ID.test(only.container_id)) {
28934
+ deps.log(`proxy agent not bound (${reason}): the only contact has a malformed container id`);
28935
+ return "invalid";
28936
+ }
28937
+ try {
28938
+ deps.persist(only.container_id);
28939
+ } catch (err) {
28940
+ deps.log(`proxy agent not bound (${reason}): saving the binding failed: ${String(err)}`);
28941
+ return "error";
28942
+ }
28943
+ deps.commit(only.container_id);
28944
+ deps.log(`proxy agent bound (${reason}): "${only.name}" (${only.container_id})`);
28945
+ return "bound";
28946
+ };
28947
+ return (reason) => {
28948
+ const run = chain.then(() => evaluate(reason));
28949
+ chain = run.catch(() => void 0);
28950
+ return run;
28951
+ };
28952
+ }
28953
+
28290
28954
  // src/connector.ts
28291
28955
  var CONFIG = loadConfig();
28292
28956
  var STATE_DIR = CONFIG.stateDir;
@@ -28310,6 +28974,22 @@ function makeConnection(client, dir, cfg, bot) {
28310
28974
  drainMessages: singleFlight(() => forwardToTelegram(conn)),
28311
28975
  drainFiles: singleFlight(() => forwardFilesToTelegram(conn)),
28312
28976
  syncReceipts: singleFlight(() => syncReceiptHistory(conn)),
28977
+ bindProxy: makeProxyBinder({
28978
+ current: () => cfg.peerCid,
28979
+ listContacts: async () => (await client.listContacts()).contacts,
28980
+ persist: (peerCid) => writeMeta(dir, { ...cfg, peerCid }),
28981
+ commit: (peerCid) => {
28982
+ cfg.peerCid = peerCid;
28983
+ },
28984
+ log: (m2) => log(`[${cfg.name}] ${m2}`)
28985
+ }),
28986
+ widgets: {
28987
+ route: () => ({ name: cfg.name, chatId: cfg.chatId, threadId: cfg.threadId, peerCid: cfg.peerCid }),
28988
+ tg: bot.tg,
28989
+ store: new WidgetStore(dir, (m2) => log(`[${cfg.name}] ${m2}`)),
28990
+ log: (m2) => log(m2),
28991
+ ensureBound: (reason) => conn.bindProxy(reason)
28992
+ },
28313
28993
  watch: null,
28314
28994
  watchHandle: null,
28315
28995
  inbound: null
@@ -28339,7 +29019,7 @@ function daemonSelectionOptions() {
28339
29019
  async function attachToDaemon() {
28340
29020
  const options = daemonSelectionOptions();
28341
29021
  const legacy = options.expectedInstanceId ? null : De(options);
28342
- const client = await Q({ ...options, leaseToken: randomBytes(24).toString("hex") });
29022
+ const client = await Q({ ...options, leaseToken: randomBytes2(24).toString("hex") });
28343
29023
  try {
28344
29024
  daemonIdentityNames = new Set((await client.identities()).map((row) => row.name));
28345
29025
  log(`attached to daemon ${JSON.stringify(legacy ? un(legacy) : {
@@ -28365,15 +29045,15 @@ function routeNameError(name) {
28365
29045
  }
28366
29046
  return null;
28367
29047
  }
28368
- var connDir = (name) => join4(STATE_DIR, name);
28369
- var metaPath = (dir) => join4(dir, "connection.json");
28370
- var botsPath = () => join4(STATE_DIR, "bots.json");
29048
+ var connDir = (name) => join5(STATE_DIR, name);
29049
+ var metaPath = (dir) => join5(dir, "connection.json");
29050
+ var botsPath = () => join5(STATE_DIR, "bots.json");
28371
29051
  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);
29052
+ if (!fs4.existsSync(STATE_DIR)) return [];
29053
+ return fs4.readdirSync(STATE_DIR, { withFileTypes: true }).filter((d2) => d2.isDirectory() && fs4.existsSync(metaPath(join5(STATE_DIR, d2.name)))).map((d2) => d2.name);
28374
29054
  }
28375
29055
  function readMeta(dir) {
28376
- const cfg = JSON.parse(fs3.readFileSync(metaPath(dir), "utf8"));
29056
+ const cfg = JSON.parse(fs4.readFileSync(metaPath(dir), "utf8"));
28377
29057
  if (typeof cfg.threadId !== "string") cfg.threadId = "";
28378
29058
  if (typeof cfg.bio !== "string") cfg.bio = "";
28379
29059
  if (typeof cfg.deniedMessage !== "string") cfg.deniedMessage = DEFAULT_DENIED;
@@ -28381,17 +29061,17 @@ function readMeta(dir) {
28381
29061
  return cfg;
28382
29062
  }
28383
29063
  function writeMeta(dir, cfg) {
28384
- fs3.mkdirSync(dir, { recursive: true });
29064
+ fs4.mkdirSync(dir, { recursive: true });
28385
29065
  const tmp = `${metaPath(dir)}.tmp`;
28386
- fs3.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 384 });
28387
- fs3.renameSync(tmp, metaPath(dir));
29066
+ fs4.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 384 });
29067
+ fs4.renameSync(tmp, metaPath(dir));
28388
29068
  }
28389
29069
  function botLabel(bot) {
28390
29070
  return bot.username ? `${bot.name} (@${bot.username})` : bot.name;
28391
29071
  }
28392
29072
  function loadBotRegistry() {
28393
29073
  try {
28394
- const raw = JSON.parse(fs3.readFileSync(botsPath(), "utf8"));
29074
+ const raw = JSON.parse(fs4.readFileSync(botsPath(), "utf8"));
28395
29075
  return Object.values(raw.bots ?? {});
28396
29076
  } catch {
28397
29077
  return [];
@@ -28404,10 +29084,10 @@ function saveBotRegistry() {
28404
29084
  [...bots.values()].map((b2) => [b2.name, { name: b2.name, token: b2.token, username: b2.username, createdAt: b2.createdAt }])
28405
29085
  )
28406
29086
  };
28407
- fs3.mkdirSync(STATE_DIR, { recursive: true });
29087
+ fs4.mkdirSync(STATE_DIR, { recursive: true });
28408
29088
  const tmp = `${botsPath()}.tmp`;
28409
- fs3.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
28410
- fs3.renameSync(tmp, botsPath());
29089
+ fs4.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
29090
+ fs4.renameSync(tmp, botsPath());
28411
29091
  }
28412
29092
  function instantiateBot(rec) {
28413
29093
  const tg = new TelegramClient(rec.token, CONFIG.pollTimeoutSec, (m2) => log(`[bot ${rec.name}] tg: ${m2}`), TG_NET);
@@ -28490,6 +29170,30 @@ function sttEngineLabel(baseUrl) {
28490
29170
  return "stt";
28491
29171
  }
28492
29172
  }
29173
+ async function registerWidgetCommands(conn) {
29174
+ const { cfg } = conn;
29175
+ if (!widgetEligible(cfg.chatId, cfg.threadId)) return;
29176
+ try {
29177
+ await conn.client.registerCommands(widgetCommands(conn.widgets));
29178
+ } catch (err) {
29179
+ log(`[${cfg.name}] registering widget commands failed (widgets unavailable on this route):`, String(err));
29180
+ }
29181
+ }
29182
+ async function onBotWidgetQuery(bot, q) {
29183
+ const conn = q.chat_id !== void 0 ? bot.exact.get(chatKey(q.chat_id)) ?? null : null;
29184
+ const tag = conn ? `[${conn.cfg.name}]` : `[bot ${botLabel(bot)}]`;
29185
+ const outcome = await handleWidgetQuery(
29186
+ q,
29187
+ conn?.widgets ?? null,
29188
+ bot.tg,
29189
+ async (owner, text2) => {
29190
+ const sent = await conn.client.sendMessage({ contact: owner, text: text2 });
29191
+ if (sent.kind !== "sent" && sent.kind !== "e2e") log(`${tag} widget query event to ${owner}: ${sent.kind}`);
29192
+ },
29193
+ (m2) => log(`${tag} ${m2}`)
29194
+ );
29195
+ if (outcome === "forwarded") log(`${tag} widget query forwarded to the agent`);
29196
+ }
28493
29197
  function watchRoute(conn) {
28494
29198
  if (conn.watch) return;
28495
29199
  const ctrl = new AbortController();
@@ -28523,13 +29227,8 @@ function watchRoute(conn) {
28523
29227
  } else if (event === "contact_accepted" || event === "sibling_contact_added" || event === "local_contact_added") {
28524
29228
  const name = String(ev.from ?? ev.name ?? "");
28525
29229
  const cid = String(ev.container_id ?? ev.cid ?? "");
28526
- if (cid && !cfg.peerCid) {
28527
- cfg.peerCid = cid;
28528
- writeMeta(conn.dir, cfg);
28529
- log(`[${cfg.name}] proxy agent connected: "${name}" (${cid})`);
28530
- } else {
28531
- log(`[${cfg.name}] contact added: "${name}" (${cid})`);
28532
- }
29230
+ log(`[${cfg.name}] contact added: "${name}" (${cid})`);
29231
+ await conn.bindProxy(event);
28533
29232
  } else if (event === "contact_restored") {
28534
29233
  log(`[${cfg.name}] contact "${String(ev.from ?? "")}" restored (re-keyed)`);
28535
29234
  }
@@ -28845,7 +29544,7 @@ async function onBotMessage(bot, m2) {
28845
29544
  }
28846
29545
  function activateBot(bot) {
28847
29546
  if (bot.pollHandle) return;
28848
- bot.pollHandle = bot.tg.poll((m2) => onBotMessage(bot, m2));
29547
+ bot.pollHandle = bot.tg.poll((m2) => onBotMessage(bot, m2), (q) => onBotWidgetQuery(bot, q));
28849
29548
  void publishBotCommands(bot);
28850
29549
  }
28851
29550
  async function publishBotCommands(bot) {
@@ -28866,7 +29565,7 @@ async function createConnection(args) {
28866
29565
  const slotErr = routeSlotConflict(bot, args.chatId, args.threadId);
28867
29566
  if (slotErr) throw new Error(slotErr);
28868
29567
  const dir = connDir(args.name);
28869
- fs3.mkdirSync(dir, { recursive: true });
29568
+ fs4.mkdirSync(dir, { recursive: true });
28870
29569
  const cfg = {
28871
29570
  v: 1,
28872
29571
  name: args.name,
@@ -28879,7 +29578,7 @@ async function createConnection(args) {
28879
29578
  deniedMessage: DEFAULT_DENIED,
28880
29579
  peerCid: "",
28881
29580
  // Minted once, here, and persisted. See ConnectionFile.leaseToken.
28882
- leaseToken: randomBytes(24).toString("hex"),
29581
+ leaseToken: randomBytes2(24).toString("hex"),
28883
29582
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
28884
29583
  };
28885
29584
  const client = await clientFor(cfg);
@@ -28897,6 +29596,7 @@ async function createConnection(args) {
28897
29596
  ownedIdentityNames.add(args.name);
28898
29597
  daemonIdentityNames.add(args.name);
28899
29598
  writeMeta(dir, cfg);
29599
+ await registerWidgetCommands(conn);
28900
29600
  watchRoute(conn);
28901
29601
  activateBot(bot);
28902
29602
  const invite = await client.generateInvite({});
@@ -28916,7 +29616,7 @@ async function createConnection(args) {
28916
29616
  } catch {
28917
29617
  }
28918
29618
  try {
28919
- fs3.rmSync(connDir(args.name), { recursive: true, force: true });
29619
+ fs4.rmSync(connDir(args.name), { recursive: true, force: true });
28920
29620
  } catch {
28921
29621
  }
28922
29622
  }
@@ -28929,7 +29629,7 @@ async function restoreConnection(name) {
28929
29629
  const bot = bots.get(cfg.botName);
28930
29630
  if (!bot) throw new Error(`route "${name}" references unknown bot "${cfg.botName}"`);
28931
29631
  if (!cfg.leaseToken) {
28932
- cfg.leaseToken = randomBytes(24).toString("hex");
29632
+ cfg.leaseToken = randomBytes2(24).toString("hex");
28933
29633
  writeMeta(dir, cfg);
28934
29634
  log(`[${name}] minted a lease token for a legacy route`);
28935
29635
  }
@@ -28949,6 +29649,8 @@ async function restoreConnection(name) {
28949
29649
  connections.set(name, conn);
28950
29650
  const conflict = registerRoute(conn);
28951
29651
  if (conflict) throw new Error(conflict);
29652
+ await conn.bindProxy("restore");
29653
+ await registerWidgetCommands(conn);
28952
29654
  watchRoute(conn);
28953
29655
  await Promise.all([conn.drainMessages(), conn.drainFiles(), conn.syncReceipts()]);
28954
29656
  log(`[${name}] route restored (bot ${botLabel(bot)})`);
@@ -28982,11 +29684,11 @@ async function removeConnection(name) {
28982
29684
  const conn = connections.get(name);
28983
29685
  if (!conn) {
28984
29686
  const dir = connDir(name);
28985
- if (!fs3.existsSync(metaPath(dir))) {
29687
+ if (!fs4.existsSync(metaPath(dir))) {
28986
29688
  return { found: false, localRemoved: false, identityRemoved: false, identityLeftBehind: false, error: `no connection named "${name}"` };
28987
29689
  }
28988
29690
  try {
28989
- fs3.rmSync(dir, { recursive: true, force: true });
29691
+ fs4.rmSync(dir, { recursive: true, force: true });
28990
29692
  } catch (err) {
28991
29693
  return {
28992
29694
  found: true,
@@ -29034,7 +29736,7 @@ async function removeConnection(name) {
29034
29736
  }
29035
29737
  connections.delete(name);
29036
29738
  try {
29037
- fs3.rmSync(conn.dir, { recursive: true, force: true });
29739
+ fs4.rmSync(conn.dir, { recursive: true, force: true });
29038
29740
  } catch (err) {
29039
29741
  return {
29040
29742
  found: true,