@ours.network/tg-connector 0.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.
Files changed (37) hide show
  1. package/LICENSE +98 -0
  2. package/README.md +318 -0
  3. package/dist/cli.js +726 -0
  4. package/dist/connector.js +1578 -0
  5. package/dist/mufl_code/2DA1D5F860E42C605D92F1E24E2466C70EFDDBF057BBCBA52F0ECC639EFCA387.muflo +0 -0
  6. package/dist/mufl_code/actor.mu +1757 -0
  7. package/dist/mufl_code/config.mufl +27 -0
  8. package/dist/mufl_code/core/CLUSTER_API.md +640 -0
  9. package/dist/mufl_code/core/CLUSTER_CONTRACT.md +121 -0
  10. package/dist/mufl_code/core/CLUSTER_INTRODUCTION_PLAN.md +200 -0
  11. package/dist/mufl_code/core/CONFIGURATION_DESIGN.md +35 -0
  12. package/dist/mufl_code/core/CONFIGURATION_PLAN.md +394 -0
  13. package/dist/mufl_code/core/DEVELOPMENT.md +168 -0
  14. package/dist/mufl_code/core/EPHEMERAL_INVITE_PLAN.md +465 -0
  15. package/dist/mufl_code/core/GROUP_CHAT_DESIGN.md +520 -0
  16. package/dist/mufl_code/core/LICENSE +98 -0
  17. package/dist/mufl_code/core/README.md +76 -0
  18. package/dist/mufl_code/core/a2a_capabilities.mm +350 -0
  19. package/dist/mufl_code/core/a2a_cluster.mm +601 -0
  20. package/dist/mufl_code/core/a2a_control.mm +89 -0
  21. package/dist/mufl_code/core/a2a_messaging.mm +2103 -0
  22. package/dist/mufl_code/core/a2a_monitoring.mm +94 -0
  23. package/dist/mufl_code/core/a2a_protocol.mm +231 -0
  24. package/dist/mufl_code/core/config.mufl +26 -0
  25. package/dist/mufl_code/core/release-notes/2.0.md +268 -0
  26. package/dist/mufl_code/core/release-notes/2.1.md +92 -0
  27. package/dist/mufl_code/core/release-notes/2.2.md +94 -0
  28. package/dist/mufl_code/core/release-notes/3.0.md +162 -0
  29. package/dist/mufl_code/core/release-notes/3.1.md +43 -0
  30. package/dist/mufl_code/core/release-notes/README.md +32 -0
  31. package/dist/mufl_code/core/tests/README.md +66 -0
  32. package/dist/mufl_code/core/tests/run.sh +67 -0
  33. package/dist/mufl_code/core/tests/test.mjs +467 -0
  34. package/dist/mufl_code/core/tests/test_actor.mu +287 -0
  35. package/dist/mufl_code/core/version.mm +24 -0
  36. package/dist/mufl_code/protocol_container.mm +18 -0
  37. package/package.json +46 -0
package/dist/cli.js ADDED
@@ -0,0 +1,726 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
3
+
4
+ // src/cli.ts
5
+ import { spawn, spawnSync } from "node:child_process";
6
+ import { connect } from "node:net";
7
+ import { homedir as homedir2, userInfo } from "node:os";
8
+ import { join as join2, dirname as dirname2 } from "node:path";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import * as fs2 from "node:fs";
11
+
12
+ // src/config.ts
13
+ import * as fs from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { resolve, join, dirname } from "node:path";
16
+ var DEFAULT_CONFIG = {
17
+ brokerUrl: "wss://ours.network/broker_new",
18
+ controlPort: 3051,
19
+ stateDir: resolve(homedir(), ".ours-telegram"),
20
+ pollTimeoutSec: 30,
21
+ attachmentMaxBytes: 10 * 1024 * 1024,
22
+ // 10 MB (encoded ≈ 13.5 MB; under Telegram's 20 MB bot-API download limit)
23
+ outboundFileMaxBytes: 50 * 1024 * 1024
24
+ // Telegram bot sendDocument upper bound
25
+ };
26
+ function configPath() {
27
+ return process.env.OURS_TG_CONFIG ?? join(homedir(), ".ours-telegram", "config.json");
28
+ }
29
+ function readFileConfig() {
30
+ let raw;
31
+ try {
32
+ raw = fs.readFileSync(configPath(), "utf8");
33
+ } catch {
34
+ return {};
35
+ }
36
+ let parsed;
37
+ try {
38
+ parsed = JSON.parse(raw);
39
+ } catch {
40
+ return {};
41
+ }
42
+ const out2 = {};
43
+ if (typeof parsed.brokerUrl === "string") out2.brokerUrl = parsed.brokerUrl;
44
+ if (typeof parsed.controlPort === "number" && Number.isFinite(parsed.controlPort)) out2.controlPort = parsed.controlPort;
45
+ if (typeof parsed.stateDir === "string") out2.stateDir = resolve(parsed.stateDir);
46
+ if (typeof parsed.pollTimeoutSec === "number" && Number.isFinite(parsed.pollTimeoutSec)) {
47
+ out2.pollTimeoutSec = parsed.pollTimeoutSec;
48
+ }
49
+ if (typeof parsed.attachmentMaxBytes === "number" && Number.isFinite(parsed.attachmentMaxBytes)) {
50
+ out2.attachmentMaxBytes = parsed.attachmentMaxBytes;
51
+ }
52
+ if (typeof parsed.outboundFileMaxBytes === "number" && Number.isFinite(parsed.outboundFileMaxBytes)) {
53
+ out2.outboundFileMaxBytes = parsed.outboundFileMaxBytes;
54
+ }
55
+ return out2;
56
+ }
57
+ function envInt(name) {
58
+ const v = process.env[name];
59
+ if (v === void 0) return void 0;
60
+ const n = parseInt(v, 10);
61
+ return Number.isNaN(n) ? void 0 : n;
62
+ }
63
+ function loadConfig() {
64
+ const file = readFileConfig();
65
+ return {
66
+ brokerUrl: process.env.OURS_TG_BROKER_URL ?? file.brokerUrl ?? DEFAULT_CONFIG.brokerUrl,
67
+ controlPort: envInt("OURS_TG_CONTROL_PORT") ?? file.controlPort ?? DEFAULT_CONFIG.controlPort,
68
+ stateDir: resolve(process.env.OURS_TG_STATE_DIR ?? file.stateDir ?? DEFAULT_CONFIG.stateDir),
69
+ pollTimeoutSec: envInt("OURS_TG_POLL_TIMEOUT") ?? file.pollTimeoutSec ?? DEFAULT_CONFIG.pollTimeoutSec,
70
+ attachmentMaxBytes: envInt("OURS_TG_ATTACHMENT_MAX_BYTES") ?? file.attachmentMaxBytes ?? DEFAULT_CONFIG.attachmentMaxBytes,
71
+ outboundFileMaxBytes: envInt("OURS_TG_OUTBOUND_FILE_MAX_BYTES") ?? file.outboundFileMaxBytes ?? DEFAULT_CONFIG.outboundFileMaxBytes
72
+ };
73
+ }
74
+
75
+ // src/routing.ts
76
+ function looksLikeBotToken(s) {
77
+ return /^\d+:[A-Za-z0-9_-]+$/.test(s);
78
+ }
79
+
80
+ // src/cli.ts
81
+ var CONFIG = loadConfig();
82
+ var STATE_DIR = CONFIG.stateDir;
83
+ var PORT = CONFIG.controlPort;
84
+ var PID_PATH = join2(STATE_DIR, "daemon.pid");
85
+ var LOG_PATH = join2(STATE_DIR, "daemon.log");
86
+ var BASE = `http://127.0.0.1:${PORT}`;
87
+ var SELF = fileURLToPath(import.meta.url);
88
+ var out = (...p) => process.stdout.write(`${p.join(" ")}
89
+ `);
90
+ var err = (...p) => process.stderr.write(`${p.join(" ")}
91
+ `);
92
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
93
+ function readPid() {
94
+ try {
95
+ const n = parseInt(fs2.readFileSync(PID_PATH, "utf8").trim(), 10);
96
+ return Number.isFinite(n) ? n : null;
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+ function isAlive(pid) {
102
+ try {
103
+ process.kill(pid, 0);
104
+ return true;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ function runningPid() {
110
+ const pid = readPid();
111
+ if (pid && isAlive(pid)) return pid;
112
+ if (pid) {
113
+ try {
114
+ fs2.rmSync(PID_PATH, { force: true });
115
+ } catch {
116
+ }
117
+ }
118
+ return null;
119
+ }
120
+ function portOpen(port, timeoutMs = 1e3) {
121
+ return new Promise((res) => {
122
+ const sock = connect({ host: "127.0.0.1", port });
123
+ const done = (ok) => {
124
+ sock.destroy();
125
+ res(ok);
126
+ };
127
+ sock.setTimeout(timeoutMs);
128
+ sock.once("connect", () => done(true));
129
+ sock.once("timeout", () => done(false));
130
+ sock.once("error", () => done(false));
131
+ });
132
+ }
133
+ async function waitForPort(port, totalMs = 3e4) {
134
+ const deadline = Date.now() + totalMs;
135
+ while (Date.now() < deadline) {
136
+ if (await portOpen(port)) return true;
137
+ await sleep(400);
138
+ }
139
+ return false;
140
+ }
141
+ async function cmdStart() {
142
+ const existing = runningPid();
143
+ if (existing) {
144
+ out(`ours-tg-connector is already running (pid ${existing}, control port ${PORT}).`);
145
+ return;
146
+ }
147
+ fs2.mkdirSync(STATE_DIR, { recursive: true });
148
+ const logFd = fs2.openSync(LOG_PATH, "a");
149
+ const child = spawn(process.execPath, [SELF, "serve"], {
150
+ detached: true,
151
+ stdio: ["ignore", logFd, logFd],
152
+ env: { ...process.env }
153
+ });
154
+ child.unref();
155
+ if (!child.pid) {
156
+ err("failed to spawn the daemon.");
157
+ process.exit(1);
158
+ }
159
+ fs2.writeFileSync(PID_PATH, String(child.pid));
160
+ out(`starting ours-tg-connector (pid ${child.pid})\u2026`);
161
+ const ready = await waitForPort(PORT);
162
+ if (ready) {
163
+ out(`up on ${BASE}`);
164
+ out(` broker: ${CONFIG.brokerUrl}`);
165
+ out(` state: ${STATE_DIR}`);
166
+ out(` logs: ${LOG_PATH}`);
167
+ } else {
168
+ err(`daemon started (pid ${child.pid}) but control port ${PORT} did not open within 30s \u2014 check ${LOG_PATH}.`);
169
+ process.exit(1);
170
+ }
171
+ }
172
+ async function cmdStop() {
173
+ const pid = runningPid();
174
+ if (!pid) {
175
+ out("ours-tg-connector is not running.");
176
+ return;
177
+ }
178
+ out(`stopping (pid ${pid})\u2026`);
179
+ try {
180
+ process.kill(pid, "SIGTERM");
181
+ } catch (e) {
182
+ err(`failed to signal pid ${pid}: ${String(e)}`);
183
+ }
184
+ for (let i = 0; i < 25 && isAlive(pid); i++) await sleep(200);
185
+ if (isAlive(pid)) {
186
+ err(`pid ${pid} did not exit; sending SIGKILL.`);
187
+ try {
188
+ process.kill(pid, "SIGKILL");
189
+ } catch {
190
+ }
191
+ }
192
+ try {
193
+ fs2.rmSync(PID_PATH, { force: true });
194
+ } catch {
195
+ }
196
+ out("stopped.");
197
+ }
198
+ async function cmdStatus() {
199
+ const pid = runningPid();
200
+ const up = await portOpen(PORT);
201
+ if (!pid && !up) {
202
+ out("ours-tg-connector: stopped");
203
+ process.exitCode = 1;
204
+ return;
205
+ }
206
+ out("ours-tg-connector: running");
207
+ if (pid) out(` pid: ${pid}`);
208
+ out(` url: ${BASE} ${up ? "(reachable)" : "(port not answering!)"}`);
209
+ out(` broker: ${CONFIG.brokerUrl}`);
210
+ out(` state: ${STATE_DIR}`);
211
+ out(` logs: ${LOG_PATH}`);
212
+ if (up) {
213
+ try {
214
+ const res = await fetch(`${BASE}/connections`);
215
+ const body = await res.json();
216
+ out(` connections: ${body.connections?.length ?? 0}`);
217
+ } catch {
218
+ }
219
+ }
220
+ }
221
+ async function ensureDaemon() {
222
+ if (await portOpen(PORT)) return;
223
+ out("daemon not running \u2014 starting it\u2026");
224
+ await cmdStart();
225
+ if (!await portOpen(PORT)) {
226
+ err("daemon did not come up; aborting.");
227
+ process.exit(1);
228
+ }
229
+ }
230
+ function flagValue(argv, ...names) {
231
+ for (const name of names) {
232
+ const i = argv.indexOf(name);
233
+ if (i >= 0 && i + 1 < argv.length) return argv[i + 1];
234
+ }
235
+ return void 0;
236
+ }
237
+ async function cmdAddBot(argv) {
238
+ const positionals = argv.filter((a) => !a.startsWith("--"));
239
+ const flagged = /* @__PURE__ */ new Set();
240
+ for (const f of ["--name", "--bot-token", "--token"]) {
241
+ const i = argv.indexOf(f);
242
+ if (i >= 0 && i + 1 < argv.length) flagged.add(argv[i + 1]);
243
+ }
244
+ const pos = positionals.filter((p) => !flagged.has(p));
245
+ let name = (flagValue(argv, "--name") ?? "").trim();
246
+ let token = (flagValue(argv, "--bot-token", "--token") ?? "").trim();
247
+ for (const p of pos) {
248
+ if (!token && looksLikeBotToken(p)) token = p;
249
+ else if (!name) name = p;
250
+ }
251
+ if (!name || !token) {
252
+ err("add_bot requires a name and a bot token");
253
+ err(" e.g. ours-tg-connector add_bot supportbot 123456:ABC-DEF...");
254
+ err(" ours-tg-connector add_bot --name supportbot --bot-token 123456:ABC...");
255
+ process.exit(1);
256
+ }
257
+ await ensureDaemon();
258
+ let res;
259
+ try {
260
+ res = await fetch(`${BASE}/bots`, {
261
+ method: "POST",
262
+ headers: { "Content-Type": "application/json" },
263
+ body: JSON.stringify({ name, botToken: token })
264
+ });
265
+ } catch (e) {
266
+ err(`failed to reach the daemon control API: ${String(e)}`);
267
+ process.exit(1);
268
+ }
269
+ const body = await res.json();
270
+ if (!body.ok) {
271
+ err(`add_bot failed: ${body.error ?? `HTTP ${res.status}`}`);
272
+ process.exit(1);
273
+ }
274
+ out(`Bot "${body.name}" registered (@${body.username}).`);
275
+ out(`Add a chat route on it:`);
276
+ out(` ours-tg-connector add_new_connection --name <route> --bot ${body.name} --chat-id <id>`);
277
+ }
278
+ async function cmdListBots() {
279
+ if (!await portOpen(PORT)) {
280
+ out("daemon not running \u2014 no live bots. (Persisted ones load on `start`.)");
281
+ return;
282
+ }
283
+ const res = await fetch(`${BASE}/bots`);
284
+ const body = await res.json();
285
+ const list = body.bots ?? [];
286
+ if (list.length === 0) {
287
+ out("No bots. Register one with `add_bot <name> <token>`.");
288
+ return;
289
+ }
290
+ out(`Bots (${list.length}):`);
291
+ for (const b of list) {
292
+ out(`\u2022 ${b.name}${b.username ? ` (@${b.username})` : ""}`);
293
+ out(` token: ${b.tokenMasked}`);
294
+ out(` routes: ${b.routeCount}${b.routes.length ? ` \u2014 ${b.routes.join(", ")}` : ""}${b.polling ? "" : " (idle, not polling)"}`);
295
+ }
296
+ }
297
+ async function cmdRemoveBot(name) {
298
+ if (!name) {
299
+ err("remove_bot requires a bot name.");
300
+ process.exit(1);
301
+ }
302
+ if (!await portOpen(PORT)) {
303
+ err("daemon not running \u2014 start it first to remove a bot.");
304
+ process.exit(1);
305
+ }
306
+ const res = await fetch(`${BASE}/bots/${encodeURIComponent(name)}`, { method: "DELETE" });
307
+ const body = await res.json();
308
+ if (!body.ok) {
309
+ err(`remove_bot failed: ${body.error ?? `HTTP ${res.status}`}`);
310
+ process.exit(1);
311
+ }
312
+ out(`Removed bot "${name}".`);
313
+ }
314
+ async function cmdAddConnection(argv) {
315
+ const positionals = argv.filter((a) => !a.startsWith("--"));
316
+ const flagged = /* @__PURE__ */ new Set();
317
+ for (const f of ["--name", "--bot", "--chat-id", "--thread-id", "--label", "--bio"]) {
318
+ const i = argv.indexOf(f);
319
+ if (i >= 0 && i + 1 < argv.length) flagged.add(argv[i + 1]);
320
+ }
321
+ const pos = positionals.filter((p) => !flagged.has(p));
322
+ const name = (flagValue(argv, "--name") ?? pos[0] ?? "").trim();
323
+ const botName = (flagValue(argv, "--bot") ?? pos[1] ?? "").trim();
324
+ const chatId = (flagValue(argv, "--chat-id", "--chat") ?? pos[2] ?? "").trim();
325
+ const threadId = (flagValue(argv, "--thread-id", "--topic") ?? "").trim();
326
+ const label = (flagValue(argv, "--label") ?? "").trim();
327
+ const bio = (flagValue(argv, "--bio") ?? "").trim();
328
+ if (!name || !botName || !chatId) {
329
+ err("add_new_connection requires --name, --bot and --chat-id");
330
+ err(" (register the bot first: ours-tg-connector add_bot <name> <token>)");
331
+ err(" e.g. ours-tg-connector add_new_connection --name support \\");
332
+ err(" --bot supportbot --chat-id -1001234567890 \\");
333
+ err(' [--thread-id 42] [--bio "ACME #support \u2014 paying customers"]');
334
+ process.exit(1);
335
+ }
336
+ await ensureDaemon();
337
+ let res;
338
+ try {
339
+ res = await fetch(`${BASE}/connections`, {
340
+ method: "POST",
341
+ headers: { "Content-Type": "application/json" },
342
+ body: JSON.stringify({ name, botName, chatId, threadId, label, bio })
343
+ });
344
+ } catch (e) {
345
+ err(`failed to reach the daemon control API: ${String(e)}`);
346
+ process.exit(1);
347
+ }
348
+ const body = await res.json();
349
+ if (!body.ok || !body.invite) {
350
+ err(`add_new_connection failed: ${body.error ?? `HTTP ${res.status}`}`);
351
+ process.exit(1);
352
+ }
353
+ out("");
354
+ out(`Connection "${name}" created.`);
355
+ out(` identity (container id): ${body.cid}`);
356
+ out(` telegram bot: ${botName}${body.botUsername ? ` (@${body.botUsername})` : ""}`);
357
+ out(` bridged chat id: ${chatId}${threadId ? ` (topic ${threadId})` : ""}`);
358
+ if (bio) out(` identity bio: ${bio}`);
359
+ out("");
360
+ out("Paste this invite into your proxy agent (ours `add_contact`):");
361
+ out("");
362
+ out(body.invite);
363
+ out("");
364
+ out("Once the proxy agent accepts it, the bridge is live:");
365
+ out(" \u2022 messages in this Telegram chat/topic \u2192 forwarded to the proxy agent");
366
+ out(" \u2022 messages from the proxy agent \u2192 delivered back to this chat/topic");
367
+ out("");
368
+ out(`Re-run with --bot ${botName} and a different --chat-id (or --thread-id)`);
369
+ out("to bridge more chats through this one bot \u2014 each becomes its own identity.");
370
+ }
371
+ async function cmdListConnections() {
372
+ if (!await portOpen(PORT)) {
373
+ out("daemon not running \u2014 no live connections. (Persisted ones load on `start`.)");
374
+ return;
375
+ }
376
+ const res = await fetch(`${BASE}/connections`);
377
+ const body = await res.json();
378
+ const conns = body.connections ?? [];
379
+ if (conns.length === 0) {
380
+ out("No connections.");
381
+ return;
382
+ }
383
+ const byBot = /* @__PURE__ */ new Map();
384
+ for (const c of conns) {
385
+ (byBot.get(c.botName) ?? byBot.set(c.botName, []).get(c.botName)).push(c);
386
+ }
387
+ out(`Connections (${conns.length}) across ${byBot.size} bot(s):`);
388
+ for (const [botName, routes] of byBot) {
389
+ const uname = routes[0]?.botUsername;
390
+ out(`\u25B8 bot ${botName}${uname ? ` (@${uname})` : ""} \u2014 ${routes.length} route(s)`);
391
+ for (const c of routes) {
392
+ const peer = c.peerCid ? `proxy ${c.peerCid}` : "awaiting proxy";
393
+ const chat = c.chatId === "0" || c.chatId === "" ? "any chat (catch-all)" : `${c.chatId}${c.threadId ? ` \xB7 topic ${c.threadId}` : ""}`;
394
+ out(` \u2022 ${c.name}${c.label ? ` (${c.label})` : ""}`);
395
+ out(` identity: ${c.cid}`);
396
+ out(` chat: ${chat}`);
397
+ if (c.bio) out(` bio: ${c.bio}`);
398
+ out(` status: ${peer}`);
399
+ if (c.contacts.length) out(` contacts: ${c.contacts.map((x) => `${x.name} (${x.cid})`).join(", ")}`);
400
+ }
401
+ }
402
+ }
403
+ async function cmdCpInvite(name) {
404
+ if (!name) {
405
+ err("cp_invite requires a connection name.");
406
+ process.exit(1);
407
+ }
408
+ if (!await portOpen(PORT)) {
409
+ err("daemon not running \u2014 start it first.");
410
+ process.exit(1);
411
+ }
412
+ const res = await fetch(`${BASE}/connections/${encodeURIComponent(name)}/cp-invite`, { method: "POST" });
413
+ const body = await res.json();
414
+ if (!body.ok || !body.invite) {
415
+ err(`cp_invite failed: ${body.error ?? `HTTP ${res.status}`}`);
416
+ process.exit(1);
417
+ }
418
+ out("");
419
+ out(`Add the messenger control plane as a contact of "${name}".`);
420
+ out("Paste this invite into the messenger (add contact / add node):");
421
+ out("");
422
+ out(body.invite);
423
+ out("");
424
+ out(`Once it is a contact, bind it: ours-tg-connector bind_proxy ${name} <contact-name-or-cid>`);
425
+ }
426
+ async function cmdBindProxy(name, contact) {
427
+ if (!name || !contact) {
428
+ err("bind_proxy requires <connection-name> <contact-name-or-cid>.");
429
+ process.exit(1);
430
+ }
431
+ if (!await portOpen(PORT)) {
432
+ err("daemon not running \u2014 start it first.");
433
+ process.exit(1);
434
+ }
435
+ const res = await fetch(`${BASE}/connections/${encodeURIComponent(name)}/bind`, {
436
+ method: "POST",
437
+ headers: { "Content-Type": "application/json" },
438
+ body: JSON.stringify({ contact })
439
+ });
440
+ const body = await res.json();
441
+ if (!body.ok || !body.code) {
442
+ err(`bind_proxy failed: ${body.error ?? `HTTP ${res.status}`}`);
443
+ process.exit(1);
444
+ }
445
+ out("");
446
+ out(`Verification code: ${body.code}`);
447
+ out("");
448
+ out("Enter it in the messenger Control Panel within 5 minutes (3 attempts).");
449
+ out("Do NOT send it over ours \u2014 it must travel out-of-band (this terminal counts).");
450
+ }
451
+ async function cmdRemoveConnection(name) {
452
+ if (!name) {
453
+ err("remove_connection requires a connection name.");
454
+ process.exit(1);
455
+ }
456
+ if (!await portOpen(PORT)) {
457
+ err("daemon not running \u2014 start it first to remove a live connection.");
458
+ process.exit(1);
459
+ }
460
+ const res = await fetch(`${BASE}/connections/${encodeURIComponent(name)}`, { method: "DELETE" });
461
+ const body = await res.json();
462
+ if (!body.ok) {
463
+ err(`remove_connection failed: ${body.error ?? `HTTP ${res.status}`}`);
464
+ process.exit(1);
465
+ }
466
+ out(`Removed connection "${name}" and its state.`);
467
+ }
468
+ var SYSTEMD_UNIT = "ours-telegram.service";
469
+ var LAUNCHD_LABEL = "solutions.adaptframework.ours-telegram";
470
+ function systemdUnitPath() {
471
+ return join2(homedir2(), ".config", "systemd", "user", SYSTEMD_UNIT);
472
+ }
473
+ function launchdPlistPath() {
474
+ return join2(homedir2(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
475
+ }
476
+ function run(cmd, args) {
477
+ const r = spawnSync(cmd, args, { stdio: "inherit" });
478
+ return r.status === 0;
479
+ }
480
+ function serviceEnv() {
481
+ return {
482
+ OURS_TG_BROKER_URL: CONFIG.brokerUrl,
483
+ OURS_TG_CONTROL_PORT: String(CONFIG.controlPort),
484
+ OURS_TG_STATE_DIR: STATE_DIR,
485
+ OURS_TG_POLL_TIMEOUT: String(CONFIG.pollTimeoutSec)
486
+ };
487
+ }
488
+ function installSystemd() {
489
+ const unitPath = systemdUnitPath();
490
+ fs2.mkdirSync(dirname2(unitPath), { recursive: true });
491
+ const env = serviceEnv();
492
+ const envLines = Object.entries(env).map(([k, v]) => `Environment=${k}=${v}`).join("\n");
493
+ const unit = `[Unit]
494
+ Description=ours Telegram connector (bridge Telegram bots to ours proxy nodes)
495
+ After=network-online.target
496
+ Wants=network-online.target
497
+
498
+ [Service]
499
+ Type=simple
500
+ ExecStart=${process.execPath} ${SELF} serve
501
+ ${envLines}
502
+ Restart=on-failure
503
+ RestartSec=2
504
+
505
+ [Install]
506
+ WantedBy=default.target
507
+ `;
508
+ fs2.writeFileSync(unitPath, unit);
509
+ out(`wrote ${unitPath}`);
510
+ run("systemctl", ["--user", "daemon-reload"]);
511
+ if (!run("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT])) {
512
+ err("failed to enable/start the service via systemctl --user.");
513
+ process.exit(1);
514
+ }
515
+ if (!run("loginctl", ["enable-linger", userInfo().username])) {
516
+ err("warning: could not enable linger \u2014 the daemon may not start until you log in.");
517
+ err(` run manually: loginctl enable-linger ${userInfo().username}`);
518
+ }
519
+ out("");
520
+ out("ours-tg-connector installed as a systemd user service and started.");
521
+ out(` status: systemctl --user status ${SYSTEMD_UNIT}`);
522
+ out(` logs: journalctl --user -u ${SYSTEMD_UNIT} -f`);
523
+ out(` remove: ours-tg-connector uninstall-service`);
524
+ }
525
+ function uninstallSystemd() {
526
+ run("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT]);
527
+ const unitPath = systemdUnitPath();
528
+ try {
529
+ fs2.rmSync(unitPath, { force: true });
530
+ out(`removed ${unitPath}`);
531
+ } catch (e) {
532
+ err(`failed to remove ${unitPath}: ${String(e)}`);
533
+ }
534
+ run("systemctl", ["--user", "daemon-reload"]);
535
+ out("ours-tg-connector service uninstalled.");
536
+ }
537
+ function installLaunchd() {
538
+ const plistPath = launchdPlistPath();
539
+ fs2.mkdirSync(dirname2(plistPath), { recursive: true });
540
+ const env = serviceEnv();
541
+ const envEntries = Object.entries(env).map(([k, v]) => ` <key>${k}</key><string>${v}</string>`).join("\n");
542
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
543
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
544
+ <plist version="1.0">
545
+ <dict>
546
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
547
+ <key>ProgramArguments</key>
548
+ <array>
549
+ <string>${process.execPath}</string>
550
+ <string>${SELF}</string>
551
+ <string>serve</string>
552
+ </array>
553
+ <key>EnvironmentVariables</key>
554
+ <dict>
555
+ ${envEntries}
556
+ </dict>
557
+ <key>RunAtLoad</key><true/>
558
+ <key>KeepAlive</key><true/>
559
+ <key>StandardOutPath</key><string>${LOG_PATH}</string>
560
+ <key>StandardErrorPath</key><string>${LOG_PATH}</string>
561
+ </dict>
562
+ </plist>
563
+ `;
564
+ fs2.writeFileSync(plistPath, plist);
565
+ out(`wrote ${plistPath}`);
566
+ run("launchctl", ["unload", plistPath]);
567
+ if (!run("launchctl", ["load", "-w", plistPath])) {
568
+ err("failed to load the launchd agent.");
569
+ process.exit(1);
570
+ }
571
+ out("");
572
+ out("ours-tg-connector installed as a launchd agent and started.");
573
+ out(" remove: ours-tg-connector uninstall-service");
574
+ }
575
+ function uninstallLaunchd() {
576
+ const plistPath = launchdPlistPath();
577
+ run("launchctl", ["unload", plistPath]);
578
+ try {
579
+ fs2.rmSync(plistPath, { force: true });
580
+ out(`removed ${plistPath}`);
581
+ } catch (e) {
582
+ err(`failed to remove ${plistPath}: ${String(e)}`);
583
+ }
584
+ out("ours-tg-connector service uninstalled.");
585
+ }
586
+ async function cmdInstallService() {
587
+ await cmdStop();
588
+ if (process.platform === "linux") return installSystemd();
589
+ if (process.platform === "darwin") return installLaunchd();
590
+ err(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`);
591
+ process.exit(1);
592
+ }
593
+ function cmdUninstallService() {
594
+ if (process.platform === "linux") return uninstallSystemd();
595
+ if (process.platform === "darwin") return uninstallLaunchd();
596
+ err(`uninstall-service: unsupported platform "${process.platform}".`);
597
+ process.exit(1);
598
+ }
599
+ function usage() {
600
+ out("ours-tg-connector \u2014 bridge Telegram bots to ours proxy nodes");
601
+ out("");
602
+ out("Usage: ours-tg-connector <command>");
603
+ out(" bots:");
604
+ out(" add_bot register a Telegram bot under a name (validates via getMe)");
605
+ out(" --name <n> --bot-token <t> (positional, any order: add_bot <name> <token>)");
606
+ out(" list_bots list registered bots: @username, masked token, route count");
607
+ out(" remove_bot <name> delete a registered bot (refused while routes reference it)");
608
+ out("");
609
+ out(" routes:");
610
+ out(" add_new_connection create a chat\u2194agent route (one identity) and print an invite");
611
+ out(" --name <n> --bot <bot-name> --chat-id <c> [--thread-id <topic>] [--label <l>] [--bio <text>]");
612
+ out(" (positional also accepted: add_new_connection <name> <bot-name> <chat-id>)");
613
+ out(" reuse the same --bot with different --chat-id/--thread-id to bridge many");
614
+ out(" chats/topics through one bot; --bio gives the agent that chat's context");
615
+ out(" list_connections list configured routes grouped by bot");
616
+ out(" remove_connection <name> delete a route and its state");
617
+ out("");
618
+ out(" control plane (ours messenger):");
619
+ out(" cp_invite <name> print an invite to add the messenger as a contact");
620
+ out(" bind_proxy <name> <contact> start binding the messenger as control plane (prints a 6-digit code)");
621
+ out("");
622
+ out(" start start the daemon in the background");
623
+ out(" stop stop the running daemon");
624
+ out(" restart stop then start");
625
+ out(" status show whether the daemon is running");
626
+ out(" serve run the daemon in the foreground (used by start; handy for debugging)");
627
+ out("");
628
+ out(" install-service install + start a boot-persistent service (systemd/launchd)");
629
+ out(" uninstall-service stop + remove that service");
630
+ out("");
631
+ out("Config precedence (per field): env var > config.json > default.");
632
+ out(" config.json: OURS_TG_CONFIG, else ~/.ours-telegram/config.json");
633
+ out(" env: OURS_TG_BROKER_URL, OURS_TG_CONTROL_PORT (3051), OURS_TG_STATE_DIR, OURS_TG_POLL_TIMEOUT (30)");
634
+ }
635
+ async function main() {
636
+ const cmd = process.argv[2] ?? "help";
637
+ switch (cmd) {
638
+ case "serve":
639
+ case "run": {
640
+ fs2.mkdirSync(STATE_DIR, { recursive: true });
641
+ fs2.writeFileSync(PID_PATH, String(process.pid));
642
+ const cleanup = () => {
643
+ try {
644
+ fs2.rmSync(PID_PATH, { force: true });
645
+ } catch {
646
+ }
647
+ };
648
+ process.on("exit", cleanup);
649
+ for (const sig of ["SIGTERM", "SIGINT"]) {
650
+ process.on(sig, () => {
651
+ cleanup();
652
+ process.exit(0);
653
+ });
654
+ }
655
+ await import(pathToFileURL(join2(dirname2(SELF), "connector.js")).href);
656
+ break;
657
+ }
658
+ case "add_bot":
659
+ case "add-bot":
660
+ await cmdAddBot(process.argv.slice(3));
661
+ break;
662
+ case "list_bots":
663
+ case "list-bots":
664
+ await cmdListBots();
665
+ break;
666
+ case "remove_bot":
667
+ case "remove-bot":
668
+ await cmdRemoveBot(process.argv[3]);
669
+ break;
670
+ case "add_new_connection":
671
+ case "add-connection":
672
+ await cmdAddConnection(process.argv.slice(3));
673
+ break;
674
+ case "list_connections":
675
+ case "list-connections":
676
+ case "list":
677
+ await cmdListConnections();
678
+ break;
679
+ case "remove_connection":
680
+ case "remove-connection":
681
+ case "remove":
682
+ await cmdRemoveConnection(process.argv[3]);
683
+ break;
684
+ case "cp_invite":
685
+ case "cp-invite":
686
+ await cmdCpInvite(process.argv[3]);
687
+ break;
688
+ case "bind_proxy":
689
+ case "bind-proxy":
690
+ await cmdBindProxy(process.argv[3], process.argv[4]);
691
+ break;
692
+ case "start":
693
+ await cmdStart();
694
+ break;
695
+ case "stop":
696
+ await cmdStop();
697
+ break;
698
+ case "restart":
699
+ await cmdStop();
700
+ await cmdStart();
701
+ break;
702
+ case "status":
703
+ await cmdStatus();
704
+ break;
705
+ case "install-service":
706
+ await cmdInstallService();
707
+ break;
708
+ case "uninstall-service":
709
+ cmdUninstallService();
710
+ break;
711
+ case "help":
712
+ case "--help":
713
+ case "-h":
714
+ usage();
715
+ break;
716
+ default:
717
+ err(`unknown command: ${cmd}
718
+ `);
719
+ usage();
720
+ process.exit(1);
721
+ }
722
+ }
723
+ main().catch((e) => {
724
+ err(`ours-tg-connector error: ${e?.stack ?? e}`);
725
+ process.exit(1);
726
+ });