#!/usr/bin/env node import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const MCP_PROTOCOL = "2025-11-25"; export function parseEnv(text) { const out = {}; for (const raw of (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).split(/\r?\n/)) { const line = raw.trim(); if (!line || line.startsWith("#")) continue; const eq = line.indexOf("="); if (eq < 1) continue; const k = line.slice(0, eq).trim(); let v = line.slice(eq + 1).trim(); if (v.length >= 2 && (v[0] === '"' || v[0] === "'") && v.at(-1) === v[0]) v = v.slice(1, -1); out[k] = v; } return out; } export function loadConfig(file, { tokenOnly = false } = {}) { if (!fs.existsSync(file)) { throw new Error( `Settings file not found: ${file}. Copy gateway.env.example to gateway.env and fill it in.`, ); } const env = parseEnv(fs.readFileSync(file, "utf8")); const filled = (k) => Boolean(env[k]) && !env[k].includes("PASTE_"); const need = (k) => { if (!filled(k)) throw new Error(`Setting ${k} is empty in ${file}.`); return env[k]; }; const either = (name, old) => (filled(name) ? name : filled(old) ? old : name); const urlKey = either("RECADIA_URL", "MINDKEEP_URL"); const keyKey = either("RECADIA_AGENT_KEY", "MINDKEEP_AGENT_KEY"); const dir = path.dirname(file); const lang = (env.BOT_LANG || "auto").trim().toLowerCase(); const cfg = { botToken: need("TELEGRAM_BOT_TOKEN"), ownerId: tokenOnly && !filled("TELEGRAM_OWNER_ID") ? "0" : need("TELEGRAM_OWNER_ID"), recadiaUrl: (tokenOnly && !filled(urlKey) ? "" : need(urlKey)) .replace(/\/+$/, "") .replace(/\/mcp$/, ""), agentKey: tokenOnly && !filled(keyKey) ? "roma_" : need(keyKey), lang, notesFolder: env.NOTES_FOLDER ?? "Telegram", taskList: env.TASK_LIST ?? "", stateFile: path.resolve(dir, env.STATE_FILE || "gateway.state.json"), telegramApi: (env.TELEGRAM_API_URL || "https://api.telegram.org").replace(/\/+$/, ""), pollSeconds: Number(env.POLL_SECONDS || 30), }; if (!/^\d+:[\w-]+$/.test(cfg.botToken)) { throw new Error("TELEGRAM_BOT_TOKEN does not look like a bot token (digits:letters)."); } if (!/^\d+$/.test(cfg.ownerId)) { throw new Error("TELEGRAM_OWNER_ID must be a number (your Telegram user id)."); } if (!cfg.agentKey.startsWith("roma_")) { throw new Error(`${keyKey} must start with roma_ (an agent key from Recadia).`); } if (lang !== "auto" && !LANGS.includes(lang)) { throw new Error(`BOT_LANG must be auto or one of: ${LANGS.join(", ")}.`); } if (!Number.isFinite(cfg.pollSeconds) || cfg.pollSeconds < 0 || cfg.pollSeconds > 50) { throw new Error("POLL_SECONDS must be a number from 0 to 50."); } return cfg; } export function makeLogger(secrets, sink = console) { const list = secrets.filter((s) => typeof s === "string" && s.length >= 6); const clean = (s) => { let out = String(s); for (const x of list) out = out.split(x).join("***"); return out.replace(/\d{5,}:[\w-]{30,}/g, "***").replace(/roma_[\w-]{10,}/g, "roma_***"); }; const stamp = () => { const d = new Date(); const p = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; }; return { info: (msg) => sink.log(`${stamp()} ${clean(msg)}`), error: (msg) => sink.error(`${stamp()} ${clean(msg)}`), }; } function errText(e) { if (!(e instanceof Error)) return String(e); const cause = e.cause instanceof Error ? ` (${e.cause.message})` : ""; return `${e.message}${cause}`; } export class RetryableError extends Error {} export class RecadiaRefusal extends Error { constructor(code, reason) { super(`${code}: ${reason}`); this.code = code; } } function sleep(ms, signal) { return new Promise((resolve) => { if (signal?.aborted) return resolve(); const t = setTimeout(done, ms); function done() { clearTimeout(t); signal?.removeEventListener("abort", done); resolve(); } signal?.addEventListener("abort", done, { once: true }); }); } function withTimeout(signal, ms) { const t = AbortSignal.timeout(ms); return signal ? AbortSignal.any([signal, t]) : t; } export function telegramClient(cfg) { const base = `${cfg.telegramApi}/bot${cfg.botToken}`; return async function call(method, params, signal, timeoutMs = 15_000) { let res; try { res = await fetch(`${base}/${method}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params ?? {}), signal: withTimeout(signal, timeoutMs), }); } catch (e) { throw new RetryableError(`Telegram ${method}: network error: ${errText(e)}`); } const body = await res.json().catch(() => null); if (res.ok && body?.ok) return body.result; const desc = body?.description ?? `HTTP ${res.status}`; if (res.status === 401 || res.status === 404) { const err = new Error( `Telegram refused the bot token (${desc}). Check TELEGRAM_BOT_TOKEN or get a new one in @BotFather.`, ); err.fatal = true; throw err; } if (res.status === 409) { throw new RetryableError( `Telegram ${method}: ${desc}. Another copy of the gateway (or a webhook) uses this bot.`, ); } if (res.status === 429) { const wait = Number(body?.parameters?.retry_after ?? 5); const err = new RetryableError(`Telegram ${method}: too many requests, wait ${wait} s.`); err.waitMs = wait * 1000; throw err; } if (res.status >= 500) throw new RetryableError(`Telegram ${method}: ${desc}`); throw new Error(`Telegram ${method}: ${desc}`); }; } function readRpc(contentType, text) { if (contentType.includes("text/event-stream")) { let last = null; for (const line of text.split(/\r?\n/)) { if (!line.startsWith("data:")) continue; try { const msg = JSON.parse(line.slice(5).trim()); if (msg && ("result" in msg || "error" in msg)) last = msg; } catch { } } return last; } try { return JSON.parse(text); } catch { return null; } } export function recadiaClient(cfg) { let seq = 0; return async function tool(name, args, signal) { let res; try { res = await fetch(`${cfg.recadiaUrl}/mcp`, { method: "POST", headers: { Authorization: `Bearer ${cfg.agentKey}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": MCP_PROTOCOL, }, body: JSON.stringify({ jsonrpc: "2.0", id: ++seq, method: "tools/call", params: { name, arguments: args ?? {} }, }), signal: withTimeout(signal, 30_000), }); } catch (e) { throw new RetryableError(`Recadia is not reachable at ${cfg.recadiaUrl}: ${errText(e)}`); } const text = await res.text().catch(() => ""); if (res.status === 401) { throw new RecadiaRefusal("unauthorized", "The agent key is wrong or revoked."); } if (res.status >= 500) throw new RetryableError(`Recadia answered HTTP ${res.status}.`); const rpc = readRpc(res.headers.get("content-type") ?? "", text); if (!rpc) { if (!res.ok) { let code = `http_${res.status}`; try { code = JSON.parse(text).error.code ?? code; } catch { } throw new RecadiaRefusal(code, `HTTP ${res.status}`); } throw new RecadiaRefusal("bad_answer", "Recadia sent an answer the gateway cannot read."); } if (rpc.error) { throw new RecadiaRefusal("invalid_input", rpc.error.message ?? "JSON-RPC error"); } const r = rpc.result ?? {}; let data = r.structuredContent; if (!data) { try { data = JSON.parse(r.content?.[0]?.text ?? "null"); } catch { data = null; } } if (r.isError) { const e = data?.error; throw new RecadiaRefusal( e?.code ?? "invalid_input", e?.reason ?? r.content?.[0]?.text ?? "", ); } return data ?? {}; }; } const PREFIXES = [ { kind: "task", re: /^\/task(?:@\w+)?(?:\s+|$)/i }, { kind: "task", re: /^(?:задача|task|tarea)\s*:\s*/i }, { kind: "fact", re: /^\/fact(?:@\w+)?(?:\s+|$)/i }, { kind: "fact", re: /^(?:факт|память|fact|hecho|dato)\s*:\s*/i }, { kind: "note", re: /^\/note(?:@\w+)?(?:\s+|$)/i }, { kind: "note", re: /^(?:заметка|note|nota)\s*:\s*/i }, { kind: "help", re: /^\/(?:start|help)(?:@\w+)?(?:\s|$)/i }, ]; const FOR_LINE = /^\s*(?:для|агент|исполнитель|for|agent|para)\s*:\s*(.+?)\s*$/i; export const LANGS = ["en", "ru", "es"]; const TEXTS = { en: { saved: "Saved", alreadySaved: "Already saved", down: "Recadia is not reachable right now. I will retry by myself.", notSaved: "Not saved: ", refusals: { duplicate: "this record already exists or already waits in the Inbox.", previously_corrected: "you already corrected this record.", too_large: "too long. Split it into several messages.", unauthorized: "the gateway key does not fit or was revoked in Recadia.", memory_disabled: "memory is off for this gateway's agent in Recadia.", forbidden: "this gateway's agent has no right to do this in Recadia.", no_list: "Recadia has no task list this gateway can see.", not_found: "task list not found. Check TASK_LIST.", invalid_input: "Recadia did not accept the record (wrong format).", other: (code) => `Recadia refused (${code}).`, }, empty: { task: "a task text is needed after /task.", fact: "a text is needed after /fact.", note: "the message has no text.", }, help: [ "Write here, everything goes to the Recadia Inbox:", "plain text - a note;", '/task or "task:" - a task proposal (a line "For: agent name" says for whom);', '/fact or "fact:" - a memory record ("subject: statement").', "You decide: accept or decline in the Inbox.", ].join("\n"), fromTelegram: (when) => `From Telegram, ${when}.`, forwarded: (who, when) => `Forwarded from: ${who} (${when})`, attachment: (what) => `Attachment: ${what}. The file itself was not saved, it stayed in Telegram.`, attachmentTitle: (what, when) => `${what} from Telegram ${when}`, hiddenUser: "hidden user", chat: "chat", unknownSource: "unknown source", file: "file", kinds: { photo: "photo", voice: "voice message", video_note: "video message", video: "video", audio: "audio", animation: "animation", sticker: "sticker", location: "location", contact: "contact", }, reasonNote: "Message from Telegram", reasonTask: "Task from Telegram", stamp: (p, d) => `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`, }, ru: { saved: "Сохранено", alreadySaved: "Уже сохранено", down: "Recadia сейчас недоступна. Повторю сам позже.", notSaved: "Не сохранено: ", refusals: { duplicate: "такая запись уже есть или уже ждёт во Входящих.", previously_corrected: "вы уже исправили такую запись.", too_large: "слишком длинно. Разделите на несколько сообщений.", unauthorized: "ключ шлюза в Recadia не подходит или отозван.", memory_disabled: "память выключена для агента этого шлюза в Recadia.", forbidden: "у агента этого шлюза нет права на это в Recadia.", no_list: "в Recadia нет списка задач, который виден шлюзу.", not_found: "список задач не найден. Проверьте TASK_LIST.", invalid_input: "Recadia не приняла запись (неверный формат).", other: (code) => `Recadia отказала (${code}).`, }, empty: { task: "после /task нужен текст задачи.", fact: "после /fact нужен текст.", note: "в сообщении нет текста.", }, help: [ "Пишите сюда, всё попадёт во Входящие Recadia:", "обычный текст - заметка;", "/task или «задача:» - предложение задачи (строка «Для: имя агента» - для кого);", "/fact или «факт:» - запись в память («тема: утверждение»).", "Решаете вы: принять или отклонить во Входящих.", ].join("\n"), fromTelegram: (when) => `Из Telegram, ${when}.`, forwarded: (who, when) => `Переслано от: ${who} (${when})`, attachment: (what) => `Вложение: ${what}. Сам файл не сохранён, он остался в Telegram.`, attachmentTitle: (what, when) => `${what} из Telegram ${when}`, hiddenUser: "скрытый пользователь", chat: "чат", unknownSource: "неизвестный источник", file: "файл", kinds: { photo: "фото", voice: "голосовое сообщение", video_note: "видеосообщение", video: "видео", audio: "аудио", animation: "анимация", sticker: "стикер", location: "геопозиция", contact: "контакт", }, reasonNote: "Сообщение из Telegram", reasonTask: "Задача из Telegram", stamp: (p, d) => `${p(d.getDate())}.${p(d.getMonth() + 1)}.${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}`, }, es: { saved: "Guardado", alreadySaved: "Ya guardado", down: "Recadia no está disponible ahora. Lo volveré a intentar.", notSaved: "No guardado: ", refusals: { duplicate: "este registro ya existe o ya espera en la Bandeja de entrada.", previously_corrected: "ya corregiste este registro.", too_large: "demasiado largo. Divídelo en varios mensajes.", unauthorized: "la clave de la pasarela no sirve o fue revocada en Recadia.", memory_disabled: "la memoria está desactivada para el agente de esta pasarela en Recadia.", forbidden: "el agente de esta pasarela no tiene permiso para esto en Recadia.", no_list: "Recadia no tiene ninguna lista de tareas visible para la pasarela.", not_found: "lista de tareas no encontrada. Revisa TASK_LIST.", invalid_input: "Recadia no aceptó el registro (formato incorrecto).", other: (code) => `Recadia lo rechazó (${code}).`, }, empty: { task: "después de /task hace falta el texto de la tarea.", fact: "después de /fact hace falta un texto.", note: "el mensaje no tiene texto.", }, help: [ "Escribe aquí, todo llega a la Bandeja de entrada de Recadia:", "texto normal - una nota;", '/task o "tarea:" - una propuesta de tarea (una línea "Para: nombre del agente" dice para quién);', '/fact o "hecho:" - un registro de memoria ("tema: afirmación").', "Tú decides: aceptar o rechazar en la Bandeja de entrada.", ].join("\n"), fromTelegram: (when) => `Desde Telegram, ${when}.`, forwarded: (who, when) => `Reenviado de: ${who} (${when})`, attachment: (what) => `Adjunto: ${what}. El archivo no se guardó, quedó en Telegram.`, attachmentTitle: (what, when) => `${what} desde Telegram ${when}`, hiddenUser: "usuario oculto", chat: "chat", unknownSource: "origen desconocido", file: "archivo", kinds: { photo: "foto", voice: "mensaje de voz", video_note: "videomensaje", video: "vídeo", audio: "audio", animation: "animación", sticker: "sticker", location: "ubicación", contact: "contacto", }, reasonNote: "Mensaje de Telegram", reasonTask: "Tarea de Telegram", stamp: (p, d) => `${p(d.getDate())}/${p(d.getMonth() + 1)}/${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}`, }, }; export function langOf(setting, m) { if (setting && setting !== "auto") return LANGS.includes(setting) ? setting : "en"; const code = String(m?.from?.language_code ?? "").toLowerCase(); if (code.startsWith("ru")) return "ru"; if (code.startsWith("es")) return "es"; return "en"; } export function texts(lang) { return TEXTS[lang] ?? TEXTS.en; } function forwardedFrom(m, t) { const o = m.forward_origin; if (o) { if (o.type === "user" && o.sender_user) { const u = o.sender_user; const name = [u.first_name, u.last_name].filter(Boolean).join(" "); return u.username ? `${name} (@${u.username})` : name; } if (o.type === "hidden_user") return o.sender_user_name ?? t.hiddenUser; if (o.type === "chat" || o.type === "channel") { const c = o.sender_chat ?? o.chat ?? {}; const title = c.title ?? t.chat; return c.username ? `${title} (@${c.username})` : title; } return t.unknownSource; } if (m.forward_from) return [m.forward_from.first_name, m.forward_from.last_name].join(" ").trim(); if (m.forward_from_chat) return m.forward_from_chat.title ?? t.chat; if (m.forward_sender_name) return m.forward_sender_name; return null; } function attachmentOf(m, t) { for (const k of ["photo", "voice", "video_note", "video", "audio", "animation", "sticker"]) { if (m[k]) return t.kinds[k]; } if (m.document) return `${t.file} ${m.document.file_name ?? ""}`.trim(); if (m.location) return t.kinds.location; if (m.contact) return t.kinds.contact; return null; } function localStamp(unixSeconds, t) { return t.stamp((n) => String(n).padStart(2, "0"), new Date(unixSeconds * 1000)); } function shortTitle(text, max = 80) { const line = text .split(/\r?\n/) .find((l) => l.trim()) ?.trim() ?? ""; if (line.length <= max) return line; const cut = line.slice(0, max); const space = cut.lastIndexOf(" "); return `${(space > 30 ? cut.slice(0, space) : cut).trimEnd()}...`; } export function planMessage(m, lang = langOf("auto", m)) { const t = texts(lang); let text = (m.text ?? m.caption ?? "").trim(); let kind = "note"; for (const p of PREFIXES) { if (p.re.test(text)) { kind = p.kind; text = text.replace(p.re, "").trim(); break; } } if (kind === "help") return { kind }; const sourceKey = `telegram:${m.chat.id}:${m.message_id}`; const from = forwardedFrom(m, t); const attachment = attachmentOf(m, t); const when = localStamp(m.forward_date ?? m.forward_origin?.date ?? m.date, t); const origin = t.fromTelegram(localStamp(m.date, t)); const forwardLine = from ? t.forwarded(from, when) : null; const attachLine = attachment ? t.attachment(attachment) : null; if (kind === "task") { let forAgent = null; const lines = text.split(/\r?\n/).filter((l) => { const hit = l.match(FOR_LINE); if (hit && !forAgent) { forAgent = hit[1]; return false; } return true; }); text = lines.join("\n").trim(); if (!text) return { kind: "empty", wanted: "task" }; const [first, ...rest] = text.split(/\r?\n/); const title = shortTitle(first, 200); const restText = [first.trim().length > title.length ? first.trim() : "", ...rest] .join("\n") .trim(); const meta = [origin, forwardLine && `${forwardLine}.`, attachLine].filter(Boolean); const body = [restText, meta.join("\n")].filter(Boolean).join("\n\n"); return { kind, title, body, forAgent, sourceKey }; } if (kind === "fact") { if (!text) return { kind: "empty", wanted: "fact" }; const colon = text.indexOf(":"); const firstLineEnd = text.search(/\r?\n/); const hasSubject = colon > 0 && colon <= 100 && (firstLineEnd < 0 || colon < firstLineEnd); const subject = hasSubject ? text.slice(0, colon).trim() : "Telegram"; const statement = hasSubject ? text.slice(colon + 1).trim() : text; if (!statement) return { kind: "empty", wanted: "fact" }; return { kind, subject, statement, confidence: from ? "inferred" : "confirmed", ref: `chat ${m.chat.id}, message ${m.message_id}, ${new Date(m.date * 1000).toISOString()}`, sourceKey, }; } if (!text && !attachment) return { kind: "empty", wanted: "note" }; const title = text ? shortTitle(text) : t.attachmentTitle( `${attachment[0].toUpperCase()}${attachment.slice(1)}`, localStamp(m.date, t), ); const parts = []; if (forwardLine) parts.push(forwardLine); if (text) parts.push(text); parts.push(`---\n${[origin, attachLine].filter(Boolean).join("\n")}`); return { kind: "note", title, body: parts.join("\n\n"), sourceKey }; } export function helpText(lang = "en") { return texts(lang).help; } export const HELP_TEXT = helpText("en"); function refusalReason(code, lang) { const r = texts(lang).refusals; return typeof r[code] === "string" ? r[code] : r.other(code); } export function refusalText(code, lang = "en") { return `${texts(lang).notSaved}${refusalReason(code, lang)}`; } function emptyText(wanted, lang) { const t = texts(lang); return `${t.notSaved}${t.empty[wanted] ?? t.empty.note}`; } async function findList(tool, wanted, signal) { const { lists = [] } = await tool("list_lists", {}, signal); if (!lists.length) throw new RecadiaRefusal("no_list", "No task list visible to the agent."); if (!wanted) return lists[0].id; const w = wanted.trim().toLowerCase(); const hit = lists.find((l) => l.id === wanted.trim() || l.name.trim().toLowerCase() === w); if (!hit) throw new RecadiaRefusal("not_found", `No list named "${wanted}".`); return hit.id; } export async function deliver(plan, cfg, tool, signal, lang = "en") { const t = texts(lang); const key = plan.sourceKey ? { sourceKey: plan.sourceKey } : {}; if (plan.kind === "note") { const r = await tool( "propose_edit", { create: { title: plan.title, folder: cfg.notesFolder }, content: plan.body, reason: t.reasonNote, ...key, }, signal, ); return { what: "note", repeated: r?.repeated === true }; } if (plan.kind === "task") { const listId = await findList(tool, cfg.taskList, signal); const r = await tool( "propose_item", { listId, title: plan.title, ...(plan.body ? { body: plan.body } : {}), ...(plan.forAgent ? { suggestedAssignee: plan.forAgent } : {}), reason: t.reasonTask, ...key, }, signal, ); return { what: "task", repeated: r?.repeated === true }; } const r = await tool( "propose_memory", { kind: "fact", subject: plan.subject, statement: plan.statement, source: { type: "telegram", ref: plan.ref }, confidence: plan.confidence, ...key, }, signal, ); return { what: "fact", repeated: r?.repeated === true }; } function readState(file) { try { const s = JSON.parse(fs.readFileSync(file, "utf8")); return { offset: Number.isInteger(s.offset) ? s.offset : 0 }; } catch { return { offset: 0 }; } } function writeState(file, state) { const tmp = `${file}.tmp`; fs.writeFileSync(tmp, JSON.stringify(state)); fs.renameSync(tmp, file); } export function createGateway(cfg, opts = {}) { const log = opts.log ?? makeLogger([cfg.botToken, cfg.agentKey]); const tg = telegramClient(cfg); const tool = recadiaClient(cfg); const controller = new AbortController(); const signal = controller.signal; const state = readState(cfg.stateFile); const warnedDown = new Set(); async function reply(chatId, messageId, text) { try { await tg( "sendMessage", { chat_id: chatId, text, reply_parameters: { message_id: messageId, allow_sending_without_reply: true }, }, signal, ); } catch (e) { log.error(`Could not answer in Telegram: ${errText(e)}`); } } async function handle(u) { const m = u.message; if (!m) return; const fromOwner = String(m.from?.id) === cfg.ownerId && String(m.chat?.id) === cfg.ownerId; if (!fromOwner) { log.info(`Update ${u.update_id}: not from the owner's private chat, ignored.`); return; } const lang = langOf(cfg.lang, m); const t = texts(lang); const plan = planMessage(m, lang); if (plan.kind === "help") return reply(m.chat.id, m.message_id, t.help); if (plan.kind === "empty") return reply(m.chat.id, m.message_id, emptyText(plan.wanted, lang)); try { const { what, repeated } = await deliver(plan, cfg, tool, signal, lang); if (repeated) { log.info(`Update ${u.update_id}: already saved as proposed ${what}, nothing new.`); await reply(m.chat.id, m.message_id, t.alreadySaved); } else { log.info(`Update ${u.update_id}: saved as proposed ${what}.`); await reply(m.chat.id, m.message_id, t.saved); } } catch (e) { if (e instanceof RetryableError) { if (!warnedDown.has(u.update_id)) { warnedDown.add(u.update_id); await reply(m.chat.id, m.message_id, t.down); } throw e; } if (e instanceof RecadiaRefusal) { log.info(`Update ${u.update_id}: Recadia refused (${e.code}).`); return reply(m.chat.id, m.message_id, refusalText(e.code, lang)); } throw e; } } async function pollOnce(timeoutSec = cfg.pollSeconds) { const updates = await tg( "getUpdates", { offset: state.offset, timeout: timeoutSec, allowed_updates: ["message"] }, signal, (timeoutSec + 15) * 1000, ); let taken = 0; for (const u of updates) { if (signal.aborted) break; await handle(u); state.offset = u.update_id + 1; writeState(cfg.stateFile, state); warnedDown.delete(u.update_id); taken++; } return taken; } async function run() { log.info(`Gateway started. Recadia: ${cfg.recadiaUrl}. Press Ctrl+C to stop.`); let delay = 2000; while (!signal.aborted) { try { await pollOnce(); delay = 2000; } catch (e) { if (signal.aborted) break; if (e.fatal) { log.error(errText(e)); return 2; } const wait = e.waitMs ?? delay; log.error(`${errText(e)} Retrying in ${Math.round(wait / 1000)} s.`); await sleep(wait, signal); delay = Math.min(delay * 2, 60_000); } } log.info("Gateway stopped."); return 0; } return { pollOnce, run, stop: () => controller.abort(), get offset() { return state.offset; }, }; } async function whoami(cfg, log) { try { const updates = await telegramClient(cfg)("getUpdates", { timeout: 0, allowed_updates: ["message"], }); const seen = new Map(); for (const u of updates) { const f = u.message?.from; if (f && u.message.chat?.type === "private") { seen.set(f.id, [f.first_name, f.last_name].filter(Boolean).join(" ")); } } if (!seen.size) { log.info("No messages yet. Write anything to the bot in Telegram, then run --whoami again."); return 1; } for (const [id, name] of seen) log.info(`TELEGRAM_OWNER_ID=${id} (${name})`); return 0; } catch (e) { log.error(errText(e)); return 1; } } function checkText(e) { return e instanceof RecadiaRefusal ? refusalReason(e.code, "en") : errText(e); } async function check(cfg, log) { const tg = telegramClient(cfg); const tool = recadiaClient(cfg); let ok = true; try { const me = await tg("getMe", {}); log.info(`Telegram: OK, bot @${me.username}.`); } catch (e) { ok = false; log.error(`Telegram: ${errText(e)}`); } try { const r = await tool("register_agent", {}); log.info(`Recadia: OK, agent "${r.agent?.name ?? "?"}".`); try { await findList(tool, cfg.taskList); log.info("Task list: OK."); } catch (e) { log.error(`Task list: ${checkText(e)} Notes still work.`); } } catch (e) { ok = false; log.error(`Recadia: ${checkText(e)}`); } return ok ? 0 : 1; } async function main(argv) { const at = argv.indexOf("--config"); const file = path.resolve(at >= 0 ? argv[at + 1] : path.join(HERE, "gateway.env")); const whoamiMode = argv.includes("--whoami"); let cfg; try { cfg = loadConfig(file, { tokenOnly: whoamiMode }); } catch (e) { console.error(errText(e)); return 1; } const log = makeLogger([cfg.botToken, cfg.agentKey]); if (whoamiMode) return whoami(cfg, log); if (argv.includes("--check")) return check(cfg, log); const gw = createGateway(cfg, { log }); const stop = () => gw.stop(); process.on("SIGINT", stop); process.on("SIGTERM", stop); if (argv.includes("--once")) { try { const n = await gw.pollOnce(0); log.info(`Processed ${n} message(s).`); return 0; } catch (e) { log.error(errText(e)); return 1; } } return gw.run(); } const isMain = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url)); if (isMain) { main(process.argv.slice(2)).then((code) => { process.exitCode = code; }); }