@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.
- package/LICENSE +98 -0
- package/README.md +318 -0
- package/dist/cli.js +726 -0
- package/dist/connector.js +1578 -0
- package/dist/mufl_code/2DA1D5F860E42C605D92F1E24E2466C70EFDDBF057BBCBA52F0ECC639EFCA387.muflo +0 -0
- package/dist/mufl_code/actor.mu +1757 -0
- package/dist/mufl_code/config.mufl +27 -0
- package/dist/mufl_code/core/CLUSTER_API.md +640 -0
- package/dist/mufl_code/core/CLUSTER_CONTRACT.md +121 -0
- package/dist/mufl_code/core/CLUSTER_INTRODUCTION_PLAN.md +200 -0
- package/dist/mufl_code/core/CONFIGURATION_DESIGN.md +35 -0
- package/dist/mufl_code/core/CONFIGURATION_PLAN.md +394 -0
- package/dist/mufl_code/core/DEVELOPMENT.md +168 -0
- package/dist/mufl_code/core/EPHEMERAL_INVITE_PLAN.md +465 -0
- package/dist/mufl_code/core/GROUP_CHAT_DESIGN.md +520 -0
- package/dist/mufl_code/core/LICENSE +98 -0
- package/dist/mufl_code/core/README.md +76 -0
- package/dist/mufl_code/core/a2a_capabilities.mm +350 -0
- package/dist/mufl_code/core/a2a_cluster.mm +601 -0
- package/dist/mufl_code/core/a2a_control.mm +89 -0
- package/dist/mufl_code/core/a2a_messaging.mm +2103 -0
- package/dist/mufl_code/core/a2a_monitoring.mm +94 -0
- package/dist/mufl_code/core/a2a_protocol.mm +231 -0
- package/dist/mufl_code/core/config.mufl +26 -0
- package/dist/mufl_code/core/release-notes/2.0.md +268 -0
- package/dist/mufl_code/core/release-notes/2.1.md +92 -0
- package/dist/mufl_code/core/release-notes/2.2.md +94 -0
- package/dist/mufl_code/core/release-notes/3.0.md +162 -0
- package/dist/mufl_code/core/release-notes/3.1.md +43 -0
- package/dist/mufl_code/core/release-notes/README.md +32 -0
- package/dist/mufl_code/core/tests/README.md +66 -0
- package/dist/mufl_code/core/tests/run.sh +67 -0
- package/dist/mufl_code/core/tests/test.mjs +467 -0
- package/dist/mufl_code/core/tests/test_actor.mu +287 -0
- package/dist/mufl_code/core/version.mm +24 -0
- package/dist/mufl_code/protocol_container.mm +18 -0
- package/package.json +46 -0
|
@@ -0,0 +1,1578 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/connector.ts
|
|
5
|
+
import { createServer as createHttpServer } from "node:http";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import { join as join3 } from "node:path";
|
|
8
|
+
import * as fs3 from "node:fs";
|
|
9
|
+
|
|
10
|
+
// src/config.ts
|
|
11
|
+
import * as fs from "node:fs";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { resolve, join, dirname } from "node:path";
|
|
14
|
+
var DEFAULT_CONFIG = {
|
|
15
|
+
brokerUrl: "wss://ours.network/broker_new",
|
|
16
|
+
controlPort: 3051,
|
|
17
|
+
stateDir: resolve(homedir(), ".ours-telegram"),
|
|
18
|
+
pollTimeoutSec: 30,
|
|
19
|
+
attachmentMaxBytes: 10 * 1024 * 1024,
|
|
20
|
+
// 10 MB (encoded ≈ 13.5 MB; under Telegram's 20 MB bot-API download limit)
|
|
21
|
+
outboundFileMaxBytes: 50 * 1024 * 1024
|
|
22
|
+
// Telegram bot sendDocument upper bound
|
|
23
|
+
};
|
|
24
|
+
function configPath() {
|
|
25
|
+
return process.env.OURS_TG_CONFIG ?? join(homedir(), ".ours-telegram", "config.json");
|
|
26
|
+
}
|
|
27
|
+
function readFileConfig() {
|
|
28
|
+
let raw;
|
|
29
|
+
try {
|
|
30
|
+
raw = fs.readFileSync(configPath(), "utf8");
|
|
31
|
+
} catch {
|
|
32
|
+
return {};
|
|
33
|
+
}
|
|
34
|
+
let parsed;
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(raw);
|
|
37
|
+
} catch {
|
|
38
|
+
return {};
|
|
39
|
+
}
|
|
40
|
+
const out = {};
|
|
41
|
+
if (typeof parsed.brokerUrl === "string") out.brokerUrl = parsed.brokerUrl;
|
|
42
|
+
if (typeof parsed.controlPort === "number" && Number.isFinite(parsed.controlPort)) out.controlPort = parsed.controlPort;
|
|
43
|
+
if (typeof parsed.stateDir === "string") out.stateDir = resolve(parsed.stateDir);
|
|
44
|
+
if (typeof parsed.pollTimeoutSec === "number" && Number.isFinite(parsed.pollTimeoutSec)) {
|
|
45
|
+
out.pollTimeoutSec = parsed.pollTimeoutSec;
|
|
46
|
+
}
|
|
47
|
+
if (typeof parsed.attachmentMaxBytes === "number" && Number.isFinite(parsed.attachmentMaxBytes)) {
|
|
48
|
+
out.attachmentMaxBytes = parsed.attachmentMaxBytes;
|
|
49
|
+
}
|
|
50
|
+
if (typeof parsed.outboundFileMaxBytes === "number" && Number.isFinite(parsed.outboundFileMaxBytes)) {
|
|
51
|
+
out.outboundFileMaxBytes = parsed.outboundFileMaxBytes;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function envInt(name) {
|
|
56
|
+
const v = process.env[name];
|
|
57
|
+
if (v === void 0) return void 0;
|
|
58
|
+
const n = parseInt(v, 10);
|
|
59
|
+
return Number.isNaN(n) ? void 0 : n;
|
|
60
|
+
}
|
|
61
|
+
function loadConfig() {
|
|
62
|
+
const file = readFileConfig();
|
|
63
|
+
return {
|
|
64
|
+
brokerUrl: process.env.OURS_TG_BROKER_URL ?? file.brokerUrl ?? DEFAULT_CONFIG.brokerUrl,
|
|
65
|
+
controlPort: envInt("OURS_TG_CONTROL_PORT") ?? file.controlPort ?? DEFAULT_CONFIG.controlPort,
|
|
66
|
+
stateDir: resolve(process.env.OURS_TG_STATE_DIR ?? file.stateDir ?? DEFAULT_CONFIG.stateDir),
|
|
67
|
+
pollTimeoutSec: envInt("OURS_TG_POLL_TIMEOUT") ?? file.pollTimeoutSec ?? DEFAULT_CONFIG.pollTimeoutSec,
|
|
68
|
+
attachmentMaxBytes: envInt("OURS_TG_ATTACHMENT_MAX_BYTES") ?? file.attachmentMaxBytes ?? DEFAULT_CONFIG.attachmentMaxBytes,
|
|
69
|
+
outboundFileMaxBytes: envInt("OURS_TG_OUTBOUND_FILE_MAX_BYTES") ?? file.outboundFileMaxBytes ?? DEFAULT_CONFIG.outboundFileMaxBytes
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/adapt.ts
|
|
74
|
+
import { resolve as resolve2, join as join2, dirname as dirname2 } from "node:path";
|
|
75
|
+
import { fileURLToPath } from "node:url";
|
|
76
|
+
import * as fs2 from "node:fs";
|
|
77
|
+
import { brotliCompressSync, brotliDecompressSync, constants as zlibConstants } from "node:zlib";
|
|
78
|
+
import { adapt_wrapper } from "@adapt-toolkit/sdk/executables";
|
|
79
|
+
import { PacketWrapperConfigurator } from "@adapt-toolkit/sdk/wrappers";
|
|
80
|
+
import { object_to_adapt_value } from "@adapt-toolkit/sdk/wrapper";
|
|
81
|
+
import { AdaptObjectLifetime } from "@adapt-toolkit/sdk/common";
|
|
82
|
+
function withScope(fn) {
|
|
83
|
+
const lt = new AdaptObjectLifetime();
|
|
84
|
+
try {
|
|
85
|
+
return fn(lt);
|
|
86
|
+
} finally {
|
|
87
|
+
lt.Finalize();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function withScopeAsync(fn) {
|
|
91
|
+
const lt = new AdaptObjectLifetime();
|
|
92
|
+
try {
|
|
93
|
+
return await fn(lt);
|
|
94
|
+
} finally {
|
|
95
|
+
lt.Finalize();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function locateUnit() {
|
|
99
|
+
const here = dirname2(fileURLToPath(import.meta.url));
|
|
100
|
+
const override = process.env.OURS_TG_UNIT_DIR;
|
|
101
|
+
const candidates = override ? [resolve2(override)] : [join2(here, "mufl_code"), join2(here, "..", "mufl_code")];
|
|
102
|
+
for (const dir of candidates) {
|
|
103
|
+
if (!fs2.existsSync(dir)) continue;
|
|
104
|
+
const muflo = fs2.readdirSync(dir).find((f) => f.endsWith(".muflo"));
|
|
105
|
+
if (muflo) {
|
|
106
|
+
const hash = muflo.slice(0, -".muflo".length);
|
|
107
|
+
const contents = new Uint8Array(fs2.readFileSync(join2(dir, muflo)));
|
|
108
|
+
return { dir, hash, contents };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
throw new Error(`no compiled .muflo packet found (looked in: ${candidates.join(", ")})`);
|
|
112
|
+
}
|
|
113
|
+
var Packet = class {
|
|
114
|
+
constructor(name, cid, pw) {
|
|
115
|
+
this.name = name;
|
|
116
|
+
this.cid = cid;
|
|
117
|
+
this.pw = pw;
|
|
118
|
+
}
|
|
119
|
+
pending = [];
|
|
120
|
+
lock = Promise.resolve();
|
|
121
|
+
// Read-only transaction. The envelope is detached scratch that ExecuteTransaction
|
|
122
|
+
// clones synchronously, so we Destroy it immediately. The result is attached to
|
|
123
|
+
// `lt` when supplied (callers wrap in withScope); without `lt` the caller owns the
|
|
124
|
+
// returned value and must free it.
|
|
125
|
+
readonlyTx(name, lt) {
|
|
126
|
+
const envelope = object_to_adapt_value({ name, targ: void 0 });
|
|
127
|
+
const result = this.pw.packet.ExecuteTransaction(envelope);
|
|
128
|
+
envelope.Destroy();
|
|
129
|
+
return lt ? result.Attach(lt) : result;
|
|
130
|
+
}
|
|
131
|
+
async withLock(fn) {
|
|
132
|
+
const prev = this.lock;
|
|
133
|
+
let release;
|
|
134
|
+
this.lock = new Promise((r) => release = r);
|
|
135
|
+
await prev;
|
|
136
|
+
try {
|
|
137
|
+
return await fn();
|
|
138
|
+
} finally {
|
|
139
|
+
release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
enqueue(envelope, timeoutMs) {
|
|
143
|
+
return new Promise((res, rej) => {
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
const i = this.pending.findIndex((p) => p.timer === timer);
|
|
146
|
+
if (i >= 0) this.pending.splice(i, 1);
|
|
147
|
+
rej(new Error("timed out waiting for the transaction result"));
|
|
148
|
+
}, timeoutMs);
|
|
149
|
+
this.pending.push({ resolve: res, reject: rej, timer });
|
|
150
|
+
this.pw.add_client_message(envelope);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
// Mutating transaction. The envelope is detached scratch (add_client_message
|
|
154
|
+
// copies it, it is not taken over), so we Destroy it once the transaction
|
|
155
|
+
// settles. The result is attached to `lt` when supplied; without one the caller
|
|
156
|
+
// owns the returned value and must free it.
|
|
157
|
+
mutatingTx(name, targ, lt, timeoutMs = 25e3) {
|
|
158
|
+
const envelope = object_to_adapt_value({ name, targ });
|
|
159
|
+
return this.withLock(() => this.enqueue(envelope, timeoutMs)).then(
|
|
160
|
+
(payload) => {
|
|
161
|
+
envelope.Destroy();
|
|
162
|
+
return lt ? payload.Attach(lt) : payload;
|
|
163
|
+
},
|
|
164
|
+
(err) => {
|
|
165
|
+
try {
|
|
166
|
+
envelope.Destroy();
|
|
167
|
+
} catch {
|
|
168
|
+
}
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
newBinary(buf, lt) {
|
|
174
|
+
const v = this.pw.packet.NewBinaryFromBuffer(buf);
|
|
175
|
+
return lt ? v.Attach(lt) : v;
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
function wireHandlers(pkt, hooks, log2) {
|
|
179
|
+
pkt.pw.on_return_data = (data) => {
|
|
180
|
+
const lt = new AdaptObjectLifetime();
|
|
181
|
+
data.Attach(lt);
|
|
182
|
+
try {
|
|
183
|
+
const kind = data.Reduce("kind").Visualize();
|
|
184
|
+
if (kind === "save_state") {
|
|
185
|
+
hooks.onSaveState();
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (kind === "notify_agent") {
|
|
189
|
+
const payload = data.Reduce("payload");
|
|
190
|
+
hooks.onNotify(payload.Reduce("event").Visualize(), payload);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const p = pkt.pending.shift();
|
|
194
|
+
if (!p) return;
|
|
195
|
+
clearTimeout(p.timer);
|
|
196
|
+
p.resolve(data.Reduce("payload").Detach());
|
|
197
|
+
} finally {
|
|
198
|
+
lt.Finalize();
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
pkt.pw.on_transaction_failure = (message) => {
|
|
202
|
+
const p = pkt.pending.shift();
|
|
203
|
+
if (p) {
|
|
204
|
+
clearTimeout(p.timer);
|
|
205
|
+
p.reject(new Error(message));
|
|
206
|
+
} else {
|
|
207
|
+
log2(`[${pkt.name}] inbound transaction rejected:`, message);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
var AdaptHost = class {
|
|
212
|
+
constructor(brokerUrl, log2) {
|
|
213
|
+
this.brokerUrl = brokerUrl;
|
|
214
|
+
this.log = log2;
|
|
215
|
+
this.unit = locateUnit();
|
|
216
|
+
}
|
|
217
|
+
wrapper;
|
|
218
|
+
unit;
|
|
219
|
+
async boot() {
|
|
220
|
+
const argv = [
|
|
221
|
+
"--broker_address",
|
|
222
|
+
this.brokerUrl,
|
|
223
|
+
"--test_mode",
|
|
224
|
+
"--logger_config",
|
|
225
|
+
"--level",
|
|
226
|
+
"INFO",
|
|
227
|
+
"--stdout",
|
|
228
|
+
"stderr",
|
|
229
|
+
"--logger_config_end"
|
|
230
|
+
];
|
|
231
|
+
this.log(`booting wrapper (unit ${this.unit.hash.slice(0, 12)}\u2026, broker ${this.brokerUrl})`);
|
|
232
|
+
this.wrapper = await adapt_wrapper.start(argv);
|
|
233
|
+
this.wrapper.on_packet_created_cb = (cid) => this.log(`wrapper: packet ready ${cid.slice(0, 12)}\u2026`);
|
|
234
|
+
this.wrapper.start();
|
|
235
|
+
}
|
|
236
|
+
createPacket(name, seed, signingSecret) {
|
|
237
|
+
const config = new PacketWrapperConfigurator();
|
|
238
|
+
const args = [
|
|
239
|
+
"--unit_hash",
|
|
240
|
+
this.unit.hash,
|
|
241
|
+
"--seed_phrase",
|
|
242
|
+
seed,
|
|
243
|
+
"--unit_dir_path",
|
|
244
|
+
this.unit.dir
|
|
245
|
+
];
|
|
246
|
+
if (signingSecret) {
|
|
247
|
+
args.push("--init_trn_argument", JSON.stringify(signingSecret));
|
|
248
|
+
}
|
|
249
|
+
config.process_arguments(args);
|
|
250
|
+
return new Promise((resolveCreate, rejectCreate) => {
|
|
251
|
+
const timer = setTimeout(
|
|
252
|
+
() => rejectCreate(new Error(`packet creation for "${name}" timed out`)),
|
|
253
|
+
3e4
|
|
254
|
+
);
|
|
255
|
+
this.wrapper.packet_manager.create_packet(
|
|
256
|
+
config,
|
|
257
|
+
(pw) => {
|
|
258
|
+
clearTimeout(timer);
|
|
259
|
+
const cid = withScope((lt) => pw.packet.GetContainerID().Attach(lt).Visualize());
|
|
260
|
+
this.log(`[${name}] packet created \u2014 container id ${cid}`);
|
|
261
|
+
resolveCreate(new Packet(name, cid, pw));
|
|
262
|
+
},
|
|
263
|
+
this.unit.contents
|
|
264
|
+
);
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
removePacket(cid) {
|
|
268
|
+
this.wrapper.remove_packet(cid);
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
function packInvite(raw) {
|
|
272
|
+
const compressed = brotliCompressSync(raw, {
|
|
273
|
+
params: {
|
|
274
|
+
[zlibConstants.BROTLI_PARAM_QUALITY]: 11,
|
|
275
|
+
[zlibConstants.BROTLI_PARAM_SIZE_HINT]: raw.length
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
return compressed.toString("base64url");
|
|
279
|
+
}
|
|
280
|
+
function renderInbox(v) {
|
|
281
|
+
const out = [];
|
|
282
|
+
if (v.IsNil()) return out;
|
|
283
|
+
for (let i = 0; ; i++) {
|
|
284
|
+
const m = v.Reduce(i);
|
|
285
|
+
if (m.IsNil()) break;
|
|
286
|
+
out.push({
|
|
287
|
+
msg_id: parseInt(m.Reduce("msg_id").Visualize(), 10),
|
|
288
|
+
sender_id: m.Reduce("sender_id").Visualize(),
|
|
289
|
+
sender_name: m.Reduce("sender_name").Visualize(),
|
|
290
|
+
text: m.Reduce("text").Visualize(),
|
|
291
|
+
date: m.Reduce("date").Visualize(),
|
|
292
|
+
status: m.Reduce("status").Visualize(),
|
|
293
|
+
wire_id: m.Reduce("wire_id").Visualize()
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
return out;
|
|
297
|
+
}
|
|
298
|
+
function renderFiles(v) {
|
|
299
|
+
const out = [];
|
|
300
|
+
if (v.IsNil()) return out;
|
|
301
|
+
for (let i = 0; ; i++) {
|
|
302
|
+
const f = v.Reduce(i);
|
|
303
|
+
if (f.IsNil()) break;
|
|
304
|
+
out.push({
|
|
305
|
+
file_id: parseInt(f.Reduce("file_id").Visualize(), 10),
|
|
306
|
+
sender_id: f.Reduce("sender_id").Visualize(),
|
|
307
|
+
sender_name: f.Reduce("sender_name").Visualize(),
|
|
308
|
+
filename: f.Reduce("filename").Visualize(),
|
|
309
|
+
mime: f.Reduce("mime").Visualize(),
|
|
310
|
+
bytes: Buffer.from(f.Reduce("data").GetBinary()),
|
|
311
|
+
date: f.Reduce("date").Visualize(),
|
|
312
|
+
wire_id: f.Reduce("wire_id").Visualize()
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
function renderControlRequests(v) {
|
|
318
|
+
const out = [];
|
|
319
|
+
if (v.IsNil()) return out;
|
|
320
|
+
for (let i = 0; ; i++) {
|
|
321
|
+
const m = v.Reduce(i);
|
|
322
|
+
if (m.IsNil()) break;
|
|
323
|
+
out.push({
|
|
324
|
+
senderCid: m.Reduce("sender_cid").Visualize(),
|
|
325
|
+
senderName: m.Reduce("sender_name").Visualize(),
|
|
326
|
+
payload: m.Reduce("payload").Visualize(),
|
|
327
|
+
date: m.Reduce("date").Visualize()
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
332
|
+
function renderMonitoringStatus(v) {
|
|
333
|
+
return {
|
|
334
|
+
proxyCid: v.Reduce("proxy_cid").Visualize(),
|
|
335
|
+
proxyPending: v.Reduce("proxy_pending").GetBoolean(),
|
|
336
|
+
controlQueued: parseInt(v.Reduce("control_queued").Visualize(), 10) || 0
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
function renderContacts(v) {
|
|
340
|
+
const out = [];
|
|
341
|
+
if (v.IsNil()) return out;
|
|
342
|
+
for (const key of v.GetKeys()) {
|
|
343
|
+
const c = v.Reduce(key);
|
|
344
|
+
if (c.IsNil()) continue;
|
|
345
|
+
out.push({
|
|
346
|
+
name: c.Reduce("name").Visualize(),
|
|
347
|
+
container_id: c.Reduce("container_id").Visualize()
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// src/control.ts
|
|
354
|
+
var APP_ID = "network.ours.telegram-connector";
|
|
355
|
+
var DEFAULT_DENIED = "You are not allowed to speak to this bot, please contact the admin.";
|
|
356
|
+
var CONFIG_SCHEMA = {
|
|
357
|
+
version: "1",
|
|
358
|
+
groups: [
|
|
359
|
+
{
|
|
360
|
+
id: "routing",
|
|
361
|
+
title: "Telegram routing",
|
|
362
|
+
desc: "Control which Telegram chat may talk to this bot, and what everyone else is told.",
|
|
363
|
+
fields: [
|
|
364
|
+
{
|
|
365
|
+
key: "allowedChatId",
|
|
366
|
+
label: "Allowed chat ID",
|
|
367
|
+
type: "string",
|
|
368
|
+
required: true,
|
|
369
|
+
help: "Only messages from this Telegram chat are proxied to the agent. Any other chat receives the denial message.",
|
|
370
|
+
placeholder: "-1001234567890"
|
|
371
|
+
},
|
|
372
|
+
{
|
|
373
|
+
key: "deniedMessage",
|
|
374
|
+
label: "Denial message",
|
|
375
|
+
type: "string",
|
|
376
|
+
required: true,
|
|
377
|
+
help: "Sent back to any chat that is not the allowed one.",
|
|
378
|
+
placeholder: DEFAULT_DENIED
|
|
379
|
+
}
|
|
380
|
+
]
|
|
381
|
+
}
|
|
382
|
+
]
|
|
383
|
+
};
|
|
384
|
+
function monitoringStatus(pkt) {
|
|
385
|
+
return withScope((lt) => renderMonitoringStatus(pkt.readonlyTx("::a2a_messaging::get_monitoring_status", lt)));
|
|
386
|
+
}
|
|
387
|
+
async function sendControl(pkt, contactCid, payload) {
|
|
388
|
+
await withScopeAsync(
|
|
389
|
+
(lt) => pkt.mutatingTx("::a2a_control::send_control", { contact: contactCid, payload: JSON.stringify(payload) }, lt)
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
function readPacketCapabilities(pkt) {
|
|
393
|
+
return withScope((lt) => {
|
|
394
|
+
const caps = pkt.readonlyTx("::a2a_capabilities::get_manifest", lt).Reduce("capabilities");
|
|
395
|
+
if (caps.IsNil()) return [];
|
|
396
|
+
return caps.GetKeys().map((k) => k.Visualize());
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
function buildManifest(pkt, cfg, bound) {
|
|
400
|
+
return {
|
|
401
|
+
version: "1",
|
|
402
|
+
app_id: APP_ID,
|
|
403
|
+
name: cfg.label || cfg.name,
|
|
404
|
+
description: "Bridges a Telegram bot to an ours proxy node.",
|
|
405
|
+
monitoring_status: bound ? "bound" : "unbound",
|
|
406
|
+
capabilities: readPacketCapabilities(pkt)
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
function configValues(cfg) {
|
|
410
|
+
return {
|
|
411
|
+
allowedChatId: cfg.chatId,
|
|
412
|
+
deniedMessage: cfg.deniedMessage || DEFAULT_DENIED
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function applyConfig(cfg, values) {
|
|
416
|
+
let changed = false;
|
|
417
|
+
if (typeof values.allowedChatId === "string") {
|
|
418
|
+
const v = values.allowedChatId.trim();
|
|
419
|
+
if (v !== cfg.chatId) {
|
|
420
|
+
cfg.chatId = v;
|
|
421
|
+
changed = true;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (typeof values.deniedMessage === "string" && values.deniedMessage !== cfg.deniedMessage) {
|
|
425
|
+
cfg.deniedMessage = values.deniedMessage;
|
|
426
|
+
changed = true;
|
|
427
|
+
}
|
|
428
|
+
return changed;
|
|
429
|
+
}
|
|
430
|
+
async function dispatchControlRequest(pkt, cfg, req, hooks) {
|
|
431
|
+
let msg;
|
|
432
|
+
try {
|
|
433
|
+
const parsed = JSON.parse(req.payload);
|
|
434
|
+
if (!parsed || typeof parsed !== "object") throw new Error("not an object");
|
|
435
|
+
msg = parsed;
|
|
436
|
+
} catch {
|
|
437
|
+
hooks.log(`dropping unparseable control request from ${req.senderName}`);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (msg.v !== 1 || typeof msg.t !== "string") {
|
|
441
|
+
hooks.log(`dropping control request with unknown envelope from ${req.senderName}`);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const reply = async (data) => {
|
|
445
|
+
try {
|
|
446
|
+
await sendControl(pkt, req.senderCid, { v: 1, t: "res", id: msg.id ?? null, req: msg.t, ...data });
|
|
447
|
+
} catch (err) {
|
|
448
|
+
hooks.log(`control reply to ${req.senderName} failed: ${String(err)}`);
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
try {
|
|
452
|
+
if (msg.t === "bind") {
|
|
453
|
+
const verdict = await withScopeAsync(async (lt) => {
|
|
454
|
+
const data = await pkt.mutatingTx(
|
|
455
|
+
"::a2a_messaging::verify_proxy_code",
|
|
456
|
+
{ code: String(msg.code ?? ""), sender: req.senderCid },
|
|
457
|
+
lt
|
|
458
|
+
);
|
|
459
|
+
return { verified: data.Reduce("verified").GetBoolean(), reason: data.Reduce("reason").Visualize() };
|
|
460
|
+
});
|
|
461
|
+
if (!verdict.verified) {
|
|
462
|
+
hooks.log(`proxy bind attempt from ${req.senderName} rejected (${verdict.reason})`);
|
|
463
|
+
await reply({ ok: false, error: verdict.reason });
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
hooks.log(`control plane bound: ${req.senderName} (${req.senderCid})`);
|
|
467
|
+
await reply({ ok: true, manifest: buildManifest(pkt, cfg, true) });
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const proxyCid = monitoringStatus(pkt).proxyCid;
|
|
471
|
+
if (!proxyCid || proxyCid !== req.senderCid) {
|
|
472
|
+
await reply({ ok: false, error: "not_authorized" });
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
switch (msg.t) {
|
|
476
|
+
case "get_manifest":
|
|
477
|
+
await reply({ ok: true, manifest: buildManifest(pkt, cfg, true) });
|
|
478
|
+
return;
|
|
479
|
+
case "get_config":
|
|
480
|
+
await reply({ ok: true, config: { schema: CONFIG_SCHEMA, values: configValues(cfg) } });
|
|
481
|
+
return;
|
|
482
|
+
case "set_config": {
|
|
483
|
+
let values;
|
|
484
|
+
try {
|
|
485
|
+
values = JSON.parse(String(msg.config ?? "{}"));
|
|
486
|
+
} catch {
|
|
487
|
+
await reply({ ok: false, error: "config is not valid JSON" });
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (applyConfig(cfg, values)) hooks.persist();
|
|
491
|
+
hooks.log(`config updated: allowedChatId=${cfg.chatId || "(any)"} deniedMessage=${JSON.stringify(cfg.deniedMessage)}`);
|
|
492
|
+
await reply({ ok: true, config: { schema: CONFIG_SCHEMA, values: configValues(cfg) } });
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
default:
|
|
496
|
+
await reply({ ok: false, error: `unknown request type "${msg.t}"` });
|
|
497
|
+
}
|
|
498
|
+
} catch (err) {
|
|
499
|
+
await reply({ ok: false, error: String(err) });
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// src/telegram.ts
|
|
504
|
+
var API_BASE = "https://api.telegram.org";
|
|
505
|
+
function userLabel(u) {
|
|
506
|
+
if (!u) return void 0;
|
|
507
|
+
const name = [u.first_name, u.last_name].filter(Boolean).join(" ").trim();
|
|
508
|
+
return name || u.username || (u.id !== void 0 ? String(u.id) : void 0);
|
|
509
|
+
}
|
|
510
|
+
function senderLabel(m) {
|
|
511
|
+
return userLabel(m?.from) ?? "telegram";
|
|
512
|
+
}
|
|
513
|
+
function fileDesc(kind, f) {
|
|
514
|
+
return { kind, file_id: f.file_id, file_name: f.file_name, mime_type: f.mime_type, file_size: f.file_size };
|
|
515
|
+
}
|
|
516
|
+
function pickAttachment(m) {
|
|
517
|
+
if (m.animation) return fileDesc("animation", m.animation);
|
|
518
|
+
if (m.video) return fileDesc("video", m.video);
|
|
519
|
+
if (m.video_note) return fileDesc("video_note", m.video_note);
|
|
520
|
+
if (m.voice) return fileDesc("voice", m.voice);
|
|
521
|
+
if (m.audio) return fileDesc("audio", m.audio);
|
|
522
|
+
if (m.photo && m.photo.length) {
|
|
523
|
+
const largest = m.photo[m.photo.length - 1];
|
|
524
|
+
return { kind: "photo", file_id: largest.file_id, file_size: largest.file_size };
|
|
525
|
+
}
|
|
526
|
+
if (m.sticker) return fileDesc("sticker", m.sticker);
|
|
527
|
+
if (m.document) return fileDesc("document", m.document);
|
|
528
|
+
return void 0;
|
|
529
|
+
}
|
|
530
|
+
function parseReply(m) {
|
|
531
|
+
const r = m.reply_to_message;
|
|
532
|
+
if (!r) return void 0;
|
|
533
|
+
return { message_id: r.message_id, text: r.text ?? r.caption };
|
|
534
|
+
}
|
|
535
|
+
function parseForwardOrigin(m) {
|
|
536
|
+
const fo = m.forward_origin;
|
|
537
|
+
if (fo) {
|
|
538
|
+
if (fo.type === "user") return { type: "user", name: userLabel(fo.sender_user), username: fo.sender_user?.username };
|
|
539
|
+
if (fo.type === "hidden_user") return { type: "hidden_user", name: fo.sender_user_name };
|
|
540
|
+
if (fo.type === "channel") return { type: "channel", name: fo.chat?.title, username: fo.chat?.username, message_id: fo.message_id };
|
|
541
|
+
if (fo.type === "chat") return { type: "chat", name: fo.sender_chat?.title, username: fo.sender_chat?.username };
|
|
542
|
+
return void 0;
|
|
543
|
+
}
|
|
544
|
+
if (m.forward_from) return { type: "user", name: userLabel(m.forward_from), username: m.forward_from.username };
|
|
545
|
+
if (m.forward_from_chat) {
|
|
546
|
+
const c = m.forward_from_chat;
|
|
547
|
+
return { type: c.type === "channel" ? "channel" : "chat", name: c.title, username: c.username, message_id: m.forward_from_message_id };
|
|
548
|
+
}
|
|
549
|
+
if (m.forward_sender_name) return { type: "hidden_user", name: m.forward_sender_name };
|
|
550
|
+
return void 0;
|
|
551
|
+
}
|
|
552
|
+
var TelegramClient = class {
|
|
553
|
+
constructor(token, pollTimeoutSec, log2) {
|
|
554
|
+
this.token = token;
|
|
555
|
+
this.pollTimeoutSec = pollTimeoutSec;
|
|
556
|
+
this.log = log2;
|
|
557
|
+
}
|
|
558
|
+
offset = 0;
|
|
559
|
+
aborter = null;
|
|
560
|
+
stopped = false;
|
|
561
|
+
url(method) {
|
|
562
|
+
return `${API_BASE}/bot${this.token}/${method}`;
|
|
563
|
+
}
|
|
564
|
+
// Validate the token and return the bot's @username (throws on a bad token).
|
|
565
|
+
async getMe() {
|
|
566
|
+
const resp = await fetch(this.url("getMe"));
|
|
567
|
+
const body = await resp.json();
|
|
568
|
+
if (!body.ok || !body.result) {
|
|
569
|
+
throw new Error(`getMe failed: ${body.description ?? `HTTP ${resp.status}`}`);
|
|
570
|
+
}
|
|
571
|
+
return { id: body.result.id, username: body.result.username };
|
|
572
|
+
}
|
|
573
|
+
// Deliver text to a chat, optionally into a specific forum topic. Passing a
|
|
574
|
+
// threadId routes the reply back into the same topic it came from; omitting it
|
|
575
|
+
// posts to the chat's General/main thread.
|
|
576
|
+
async sendMessage(chatId, text, threadId) {
|
|
577
|
+
const thread = threadId === void 0 || threadId === "" ? void 0 : Number(threadId);
|
|
578
|
+
for (const chunk of chunkText(text, 4e3)) {
|
|
579
|
+
const resp = await fetch(this.url("sendMessage"), {
|
|
580
|
+
method: "POST",
|
|
581
|
+
headers: { "Content-Type": "application/json" },
|
|
582
|
+
body: JSON.stringify({ chat_id: chatId, text: chunk, ...thread !== void 0 ? { message_thread_id: thread } : {} })
|
|
583
|
+
});
|
|
584
|
+
if (!resp.ok) {
|
|
585
|
+
const body = await resp.text();
|
|
586
|
+
throw new Error(`sendMessage failed (HTTP ${resp.status}): ${body}`);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
// Deliver a file to a chat as a document — preserves the original filename and
|
|
591
|
+
// works for any media type (photos arrive uncompressed; see design D3/OQ4 for
|
|
592
|
+
// per-type rendering). Optionally into a forum topic. Multipart/form-data, so
|
|
593
|
+
// we let fetch set the Content-Type boundary (do not set it ourselves).
|
|
594
|
+
async sendDocument(chatId, bytes, filename, mime, threadId) {
|
|
595
|
+
const thread = threadId === void 0 || threadId === "" ? void 0 : Number(threadId);
|
|
596
|
+
const form = new FormData();
|
|
597
|
+
form.set("chat_id", String(chatId));
|
|
598
|
+
if (thread !== void 0) form.set("message_thread_id", String(thread));
|
|
599
|
+
const blob = new Blob([new Uint8Array(bytes)], mime ? { type: mime } : {});
|
|
600
|
+
form.set("document", blob, filename);
|
|
601
|
+
const resp = await fetch(this.url("sendDocument"), { method: "POST", body: form });
|
|
602
|
+
if (!resp.ok) {
|
|
603
|
+
const body = await resp.text();
|
|
604
|
+
throw new Error(`sendDocument failed (HTTP ${resp.status}): ${body}`);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
// Resolve a file_id to its temporary download path (and size, when Telegram
|
|
608
|
+
// reports it). getFile is required before a media file can be fetched.
|
|
609
|
+
async getFile(fileId) {
|
|
610
|
+
const resp = await fetch(this.url("getFile"), {
|
|
611
|
+
method: "POST",
|
|
612
|
+
headers: { "Content-Type": "application/json" },
|
|
613
|
+
body: JSON.stringify({ file_id: fileId })
|
|
614
|
+
});
|
|
615
|
+
const body = await resp.json();
|
|
616
|
+
if (!body.ok || !body.result?.file_path) {
|
|
617
|
+
throw new Error(`getFile failed: ${body.description ?? `HTTP ${resp.status}`}`);
|
|
618
|
+
}
|
|
619
|
+
return { filePath: body.result.file_path, fileSize: body.result.file_size };
|
|
620
|
+
}
|
|
621
|
+
// Download a media file's bytes (getFile → fetch the file endpoint). Throws on
|
|
622
|
+
// any API/transport error; the caller decides how to degrade. Telegram's own
|
|
623
|
+
// bot-API download limit is 20 MB — the connector's configured cap is applied
|
|
624
|
+
// by the caller, not here.
|
|
625
|
+
async downloadFile(fileId) {
|
|
626
|
+
const { filePath } = await this.getFile(fileId);
|
|
627
|
+
const resp = await fetch(`${API_BASE}/file/bot${this.token}/${filePath}`);
|
|
628
|
+
if (!resp.ok) {
|
|
629
|
+
throw new Error(`file download failed: HTTP ${resp.status}`);
|
|
630
|
+
}
|
|
631
|
+
return Buffer.from(await resp.arrayBuffer());
|
|
632
|
+
}
|
|
633
|
+
// Long-poll loop. Calls `onMessage` for every inbound text message until
|
|
634
|
+
// stop() is called. Network errors are logged and retried with a short
|
|
635
|
+
// backoff so a transient outage never kills the bridge.
|
|
636
|
+
async poll(onMessage) {
|
|
637
|
+
this.stopped = false;
|
|
638
|
+
while (!this.stopped) {
|
|
639
|
+
this.aborter = new AbortController();
|
|
640
|
+
const timer = setTimeout(() => this.aborter?.abort(), (this.pollTimeoutSec + 10) * 1e3);
|
|
641
|
+
try {
|
|
642
|
+
const resp = await fetch(this.url("getUpdates"), {
|
|
643
|
+
method: "POST",
|
|
644
|
+
headers: { "Content-Type": "application/json" },
|
|
645
|
+
body: JSON.stringify({
|
|
646
|
+
offset: this.offset,
|
|
647
|
+
timeout: this.pollTimeoutSec,
|
|
648
|
+
allowed_updates: ["message"]
|
|
649
|
+
}),
|
|
650
|
+
signal: this.aborter.signal
|
|
651
|
+
});
|
|
652
|
+
clearTimeout(timer);
|
|
653
|
+
if (!resp.ok) {
|
|
654
|
+
this.log(`getUpdates HTTP ${resp.status}; backing off`);
|
|
655
|
+
await sleep(3e3);
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
const body = await resp.json();
|
|
659
|
+
if (!body.ok || !body.result) {
|
|
660
|
+
this.log(`getUpdates not ok: ${body.description ?? "unknown"}; backing off`);
|
|
661
|
+
await sleep(3e3);
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
for (const u of body.result) {
|
|
665
|
+
this.offset = Math.max(this.offset, u.update_id + 1);
|
|
666
|
+
const m = u.message;
|
|
667
|
+
if (!m) continue;
|
|
668
|
+
const attachment = pickAttachment(m);
|
|
669
|
+
if (typeof m.text !== "string" && typeof m.caption !== "string" && !attachment) continue;
|
|
670
|
+
try {
|
|
671
|
+
await onMessage({
|
|
672
|
+
update_id: u.update_id,
|
|
673
|
+
message_id: m.message_id ?? 0,
|
|
674
|
+
chat_id: m.chat.id,
|
|
675
|
+
chat_type: m.chat.type,
|
|
676
|
+
chat_username: m.chat.username,
|
|
677
|
+
thread_id: m.is_topic_message ? m.message_thread_id : void 0,
|
|
678
|
+
is_topic: m.is_topic_message === true,
|
|
679
|
+
chat_title: m.chat.title,
|
|
680
|
+
from: senderLabel(m),
|
|
681
|
+
from_id: m.from?.id,
|
|
682
|
+
from_username: m.from?.username,
|
|
683
|
+
text: m.text ?? m.caption ?? "",
|
|
684
|
+
date: m.date,
|
|
685
|
+
reply_to: parseReply(m),
|
|
686
|
+
forwarded_from: parseForwardOrigin(m),
|
|
687
|
+
attachment
|
|
688
|
+
});
|
|
689
|
+
} catch (err) {
|
|
690
|
+
this.log(`onMessage handler failed: ${String(err)}`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
} catch (err) {
|
|
694
|
+
clearTimeout(timer);
|
|
695
|
+
if (this.stopped) break;
|
|
696
|
+
const name = err?.name;
|
|
697
|
+
if (name !== "AbortError") {
|
|
698
|
+
this.log(`getUpdates error: ${String(err)}; backing off`);
|
|
699
|
+
await sleep(3e3);
|
|
700
|
+
}
|
|
701
|
+
} finally {
|
|
702
|
+
this.aborter = null;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
stop() {
|
|
707
|
+
this.stopped = true;
|
|
708
|
+
this.aborter?.abort();
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
function chunkText(text, size) {
|
|
712
|
+
if (text.length <= size) return [text];
|
|
713
|
+
const out = [];
|
|
714
|
+
for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));
|
|
715
|
+
return out;
|
|
716
|
+
}
|
|
717
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
718
|
+
|
|
719
|
+
// src/envelope.ts
|
|
720
|
+
var ENVELOPE_VERSION = 2;
|
|
721
|
+
var REPLY_EXCERPT_MAX = 200;
|
|
722
|
+
var KIND_DEFAULTS = {
|
|
723
|
+
photo: { ext: "jpg", mime: "image/jpeg" },
|
|
724
|
+
document: { ext: "bin", mime: "application/octet-stream" },
|
|
725
|
+
video: { ext: "mp4", mime: "video/mp4" },
|
|
726
|
+
audio: { ext: "mp3", mime: "audio/mpeg" },
|
|
727
|
+
voice: { ext: "ogg", mime: "audio/ogg" },
|
|
728
|
+
video_note: { ext: "mp4", mime: "video/mp4" },
|
|
729
|
+
animation: { ext: "mp4", mime: "video/mp4" },
|
|
730
|
+
sticker: { ext: "webp", mime: "image/webp" }
|
|
731
|
+
};
|
|
732
|
+
function isoDate(unixSec) {
|
|
733
|
+
return new Date(unixSec * 1e3).toISOString();
|
|
734
|
+
}
|
|
735
|
+
function excerpt(text) {
|
|
736
|
+
return text.length <= REPLY_EXCERPT_MAX ? text : `${text.slice(0, REPLY_EXCERPT_MAX)}\u2026`;
|
|
737
|
+
}
|
|
738
|
+
function buildReply(m) {
|
|
739
|
+
if (!m.reply_to) return void 0;
|
|
740
|
+
const { message_id, text } = m.reply_to;
|
|
741
|
+
return { message_id, text: text === void 0 ? void 0 : excerpt(text) };
|
|
742
|
+
}
|
|
743
|
+
function attachmentMeta(d, messageId) {
|
|
744
|
+
const defaults = KIND_DEFAULTS[d.kind] ?? KIND_DEFAULTS.document;
|
|
745
|
+
return {
|
|
746
|
+
filename: d.file_name ?? `${d.kind}_${messageId}.${defaults.ext}`,
|
|
747
|
+
mime: d.mime_type ?? defaults.mime
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
function buildAttachment(m, resolved, fileWireId) {
|
|
751
|
+
const d = m.attachment;
|
|
752
|
+
if (!d) return void 0;
|
|
753
|
+
const { filename, mime } = attachmentMeta(d, m.message_id);
|
|
754
|
+
const base = { kind: d.kind, filename, mime, size: d.file_size };
|
|
755
|
+
if (resolved?.ok) {
|
|
756
|
+
return { ...base, size: d.file_size ?? resolved.bytes.length, transport: "send_file", wire_id: fileWireId };
|
|
757
|
+
}
|
|
758
|
+
if (resolved && !resolved.ok) {
|
|
759
|
+
return resolved.reason === "too_large" ? { ...base, omitted: resolved.detail } : { ...base, error: resolved.detail };
|
|
760
|
+
}
|
|
761
|
+
return { ...base, error: "attachment not resolved" };
|
|
762
|
+
}
|
|
763
|
+
function buildEnvelope(m, resolved, fileWireId) {
|
|
764
|
+
const envelope = {
|
|
765
|
+
v: ENVELOPE_VERSION,
|
|
766
|
+
source: "telegram",
|
|
767
|
+
message_id: m.message_id,
|
|
768
|
+
date: isoDate(m.date),
|
|
769
|
+
from: { id: m.from_id, name: m.from, username: m.from_username },
|
|
770
|
+
chat: {
|
|
771
|
+
id: m.chat_id,
|
|
772
|
+
type: m.chat_type,
|
|
773
|
+
title: m.chat_title,
|
|
774
|
+
username: m.chat_username,
|
|
775
|
+
thread_id: m.thread_id
|
|
776
|
+
},
|
|
777
|
+
reply_to: buildReply(m),
|
|
778
|
+
forwarded_from: m.forwarded_from,
|
|
779
|
+
text: m.text,
|
|
780
|
+
attachment: buildAttachment(m, resolved, fileWireId)
|
|
781
|
+
};
|
|
782
|
+
return JSON.stringify(envelope);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// src/routing.ts
|
|
786
|
+
var ID_COMMAND_RE = /^\/id(?:@([A-Za-z0-9_]+))?$/i;
|
|
787
|
+
function isIdCommand(text, botUsername) {
|
|
788
|
+
const tok = text.trim().split(/\s+/)[0] ?? "";
|
|
789
|
+
const m = ID_COMMAND_RE.exec(tok);
|
|
790
|
+
if (!m) return false;
|
|
791
|
+
const at = m[1];
|
|
792
|
+
if (!at) return true;
|
|
793
|
+
if (!botUsername) return true;
|
|
794
|
+
return at.toLowerCase() === botUsername.toLowerCase();
|
|
795
|
+
}
|
|
796
|
+
function formatChatIdReply(r) {
|
|
797
|
+
const lines = [];
|
|
798
|
+
lines.push(`Chat identifiers${r.botUsername ? ` for @${r.botUsername}` : ""}:`);
|
|
799
|
+
lines.push(`\u2022 chat id: ${r.chatId}`);
|
|
800
|
+
if (r.chatType) lines.push(`\u2022 type: ${r.chatType}`);
|
|
801
|
+
if (r.chatTitle) lines.push(`\u2022 title: ${r.chatTitle}`);
|
|
802
|
+
if (r.chatUsername) lines.push(`\u2022 @username: @${r.chatUsername}`);
|
|
803
|
+
if (r.isTopic && r.threadId !== void 0 && r.threadId !== "") lines.push(`\u2022 topic (message_thread_id): ${r.threadId}`);
|
|
804
|
+
if (r.fromId !== void 0 && r.fromId !== "") lines.push(`\u2022 your user id: ${r.fromId}${r.fromLabel ? ` (${r.fromLabel})` : ""}`);
|
|
805
|
+
const bot = r.botName || "<bot>";
|
|
806
|
+
const thread = r.isTopic && r.threadId !== void 0 && r.threadId !== "" ? ` --thread-id ${r.threadId}` : "";
|
|
807
|
+
lines.push("");
|
|
808
|
+
lines.push("Bridge this chat to an agent:");
|
|
809
|
+
lines.push(` add_new_connection --name <route> --bot ${bot} --chat-id ${r.chatId}${thread}`);
|
|
810
|
+
return lines.join("\n");
|
|
811
|
+
}
|
|
812
|
+
function chatKey(chatId, threadId) {
|
|
813
|
+
const c = String(chatId);
|
|
814
|
+
const t = threadId === void 0 || threadId === null ? "" : String(threadId);
|
|
815
|
+
return t ? `${c}:${t}` : c;
|
|
816
|
+
}
|
|
817
|
+
function isCatchAll(chatId) {
|
|
818
|
+
return chatId === "" || chatId === "0";
|
|
819
|
+
}
|
|
820
|
+
function resolveRoute(exact, catchAll, chatId, threadId) {
|
|
821
|
+
const t = threadId === void 0 || threadId === null ? "" : String(threadId);
|
|
822
|
+
if (t) {
|
|
823
|
+
return exact.get(chatKey(chatId, t)) ?? exact.get(chatKey(chatId)) ?? catchAll ?? null;
|
|
824
|
+
}
|
|
825
|
+
return exact.get(chatKey(chatId)) ?? catchAll ?? null;
|
|
826
|
+
}
|
|
827
|
+
function deliveryTarget(chatId, threadId, lastChat) {
|
|
828
|
+
if (!isCatchAll(chatId) && threadId) return { chatId, threadId };
|
|
829
|
+
if (lastChat) return lastChat;
|
|
830
|
+
if (!isCatchAll(chatId)) return { chatId, threadId: "" };
|
|
831
|
+
return null;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// src/connector.ts
|
|
835
|
+
var CONFIG = loadConfig();
|
|
836
|
+
var STATE_DIR = CONFIG.stateDir;
|
|
837
|
+
var log = (...parts) => process.stderr.write(`a2adapt-tg: ${parts.join(" ")}
|
|
838
|
+
`);
|
|
839
|
+
var NAME_RE = /^[A-Za-z0-9 _.-]{1,64}$/;
|
|
840
|
+
function validateName(name) {
|
|
841
|
+
if (!NAME_RE.test(name)) return "name must be 1-64 chars of letters, digits, space, _ . or -";
|
|
842
|
+
if (name === "." || name === ".." || name.includes("/") || name.includes("\\")) return "invalid name";
|
|
843
|
+
return null;
|
|
844
|
+
}
|
|
845
|
+
var host = new AdaptHost(CONFIG.brokerUrl, log);
|
|
846
|
+
var connections = /* @__PURE__ */ new Map();
|
|
847
|
+
var bots = /* @__PURE__ */ new Map();
|
|
848
|
+
var connDir = (name) => join3(STATE_DIR, name);
|
|
849
|
+
var keyPath = (dir) => join3(dir, "identity.key");
|
|
850
|
+
var dataPath = (dir) => join3(dir, "state_data.bin");
|
|
851
|
+
var metaPath = (dir) => join3(dir, "connection.json");
|
|
852
|
+
var botsPath = () => join3(STATE_DIR, "bots.json");
|
|
853
|
+
function listPersistedNames() {
|
|
854
|
+
if (!fs3.existsSync(STATE_DIR)) return [];
|
|
855
|
+
return fs3.readdirSync(STATE_DIR, { withFileTypes: true }).filter((d) => d.isDirectory() && fs3.existsSync(metaPath(join3(STATE_DIR, d.name)))).map((d) => d.name);
|
|
856
|
+
}
|
|
857
|
+
function readMeta(dir) {
|
|
858
|
+
const cfg = JSON.parse(fs3.readFileSync(metaPath(dir), "utf8"));
|
|
859
|
+
if (typeof cfg.threadId !== "string") cfg.threadId = "";
|
|
860
|
+
if (typeof cfg.bio !== "string") cfg.bio = "";
|
|
861
|
+
if (typeof cfg.deniedMessage !== "string") cfg.deniedMessage = DEFAULT_DENIED;
|
|
862
|
+
return cfg;
|
|
863
|
+
}
|
|
864
|
+
function writeMeta(dir, cfg) {
|
|
865
|
+
fs3.mkdirSync(dir, { recursive: true });
|
|
866
|
+
const tmp = `${metaPath(dir)}.tmp`;
|
|
867
|
+
fs3.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 384 });
|
|
868
|
+
fs3.renameSync(tmp, metaPath(dir));
|
|
869
|
+
}
|
|
870
|
+
function hasSavedState(dir) {
|
|
871
|
+
try {
|
|
872
|
+
return fs3.existsSync(dataPath(dir)) && fs3.statSync(dataPath(dir)).size > 0;
|
|
873
|
+
} catch {
|
|
874
|
+
return false;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
function exportSigningSecret(pkt) {
|
|
878
|
+
return withScope((lt) => Buffer.from(pkt.readonlyTx("::actor::export_signing_secret", lt).Serialize()).toString("hex"));
|
|
879
|
+
}
|
|
880
|
+
function saveState(pkt, dir) {
|
|
881
|
+
try {
|
|
882
|
+
const bytes = withScope((lt) => Buffer.from(pkt.readonlyTx("::actor::export_state", lt).Serialize()));
|
|
883
|
+
fs3.mkdirSync(dir, { recursive: true });
|
|
884
|
+
const tmp = `${dataPath(dir)}.tmp`;
|
|
885
|
+
fs3.writeFileSync(tmp, bytes);
|
|
886
|
+
fs3.renameSync(tmp, dataPath(dir));
|
|
887
|
+
} catch (err) {
|
|
888
|
+
log(`[${pkt.name}] failed to save state:`, String(err));
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
function renderDeferredQueues(av) {
|
|
892
|
+
const out = [];
|
|
893
|
+
const arr = av.Reduce("queues");
|
|
894
|
+
if (arr.IsNil()) return out;
|
|
895
|
+
for (let i = 0; ; i++) {
|
|
896
|
+
const e = arr.Reduce(i);
|
|
897
|
+
if (e.IsNil()) break;
|
|
898
|
+
out.push({
|
|
899
|
+
cid: e.Reduce("container_id").Visualize(),
|
|
900
|
+
queued: Number(e.Reduce("queued").Visualize()),
|
|
901
|
+
degraded: e.Reduce("degraded").GetBoolean()
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
return out;
|
|
905
|
+
}
|
|
906
|
+
async function flushDeferredFor(pkt, contactCid) {
|
|
907
|
+
try {
|
|
908
|
+
const flushed = await withScopeAsync(async (lt) => {
|
|
909
|
+
const r = await pkt.mutatingTx("::a2a_messaging::flush_deferred", { contact: contactCid }, lt);
|
|
910
|
+
return Number(r.Reduce("flushed").Visualize());
|
|
911
|
+
});
|
|
912
|
+
if (flushed > 0) log(`[${pkt.name}] flushed ${flushed} deferred message(s) to ${contactCid.slice(0, 12)}\u2026`);
|
|
913
|
+
} catch (err) {
|
|
914
|
+
log(`[${pkt.name}] deferred flush to ${contactCid.slice(0, 12)}\u2026 failed:`, String(err));
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
async function contactRestoreSweep(pkt) {
|
|
918
|
+
try {
|
|
919
|
+
const requested = await withScopeAsync(async (lt) => {
|
|
920
|
+
const r = await pkt.mutatingTx("::a2a_messaging::restore_degraded_contacts", {}, lt);
|
|
921
|
+
return Number(r.Reduce("requested").Visualize());
|
|
922
|
+
});
|
|
923
|
+
if (requested > 0) log(`[${pkt.name}] contact restore requested for ${requested} degraded contact(s)`);
|
|
924
|
+
const queues = withScope((lt) => renderDeferredQueues(pkt.readonlyTx("::a2a_messaging::list_deferred_queues", lt)));
|
|
925
|
+
for (const q of queues) {
|
|
926
|
+
if (!q.degraded) await flushDeferredFor(pkt, q.cid);
|
|
927
|
+
}
|
|
928
|
+
} catch (err) {
|
|
929
|
+
log(`[${pkt.name}] contact-restore sweep failed:`, String(err));
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
function botLabel(bot) {
|
|
933
|
+
return bot.username ? `${bot.name} (@${bot.username})` : bot.name;
|
|
934
|
+
}
|
|
935
|
+
function loadBotRegistry() {
|
|
936
|
+
try {
|
|
937
|
+
const raw = JSON.parse(fs3.readFileSync(botsPath(), "utf8"));
|
|
938
|
+
return Object.values(raw.bots ?? {});
|
|
939
|
+
} catch {
|
|
940
|
+
return [];
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
function saveBotRegistry() {
|
|
944
|
+
const data = {
|
|
945
|
+
v: 1,
|
|
946
|
+
bots: Object.fromEntries(
|
|
947
|
+
[...bots.values()].map((b) => [b.name, { name: b.name, token: b.token, username: b.username, createdAt: b.createdAt }])
|
|
948
|
+
)
|
|
949
|
+
};
|
|
950
|
+
fs3.mkdirSync(STATE_DIR, { recursive: true });
|
|
951
|
+
const tmp = `${botsPath()}.tmp`;
|
|
952
|
+
fs3.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
|
|
953
|
+
fs3.renameSync(tmp, botsPath());
|
|
954
|
+
}
|
|
955
|
+
function instantiateBot(rec) {
|
|
956
|
+
const tg = new TelegramClient(rec.token, CONFIG.pollTimeoutSec, (m) => log(`[bot ${rec.name}] tg: ${m}`));
|
|
957
|
+
const bot = { name: rec.name, token: rec.token, tg, username: rec.username, createdAt: rec.createdAt, exact: /* @__PURE__ */ new Map(), catchAll: null, pollHandle: null };
|
|
958
|
+
bots.set(rec.name, bot);
|
|
959
|
+
return bot;
|
|
960
|
+
}
|
|
961
|
+
async function addBot(name, token) {
|
|
962
|
+
if (bots.has(name)) throw new Error(`a bot named "${name}" already exists`);
|
|
963
|
+
for (const b of bots.values()) if (b.token === token) throw new Error(`that token is already registered as bot "${b.name}"`);
|
|
964
|
+
const tg = new TelegramClient(token, CONFIG.pollTimeoutSec, (m) => log(`[bot ${name}] tg: ${m}`));
|
|
965
|
+
const me = await tg.getMe();
|
|
966
|
+
const bot = { name, token, tg, username: me.username, createdAt: (/* @__PURE__ */ new Date()).toISOString(), exact: /* @__PURE__ */ new Map(), catchAll: null, pollHandle: null };
|
|
967
|
+
bots.set(name, bot);
|
|
968
|
+
saveBotRegistry();
|
|
969
|
+
activateBot(bot);
|
|
970
|
+
log(`bot "${name}" registered (@${me.username})`);
|
|
971
|
+
return { name, username: me.username };
|
|
972
|
+
}
|
|
973
|
+
function removeBot(name) {
|
|
974
|
+
const bot = bots.get(name);
|
|
975
|
+
if (!bot) return `no bot named "${name}"`;
|
|
976
|
+
const routes = [...bot.exact.values()].map((c) => c.cfg.name);
|
|
977
|
+
if (bot.catchAll) routes.push(bot.catchAll.cfg.name);
|
|
978
|
+
if (routes.length) return `bot "${name}" still has ${routes.length} route(s): ${routes.join(", ")} \u2014 remove them first`;
|
|
979
|
+
try {
|
|
980
|
+
bot.tg.stop();
|
|
981
|
+
} catch {
|
|
982
|
+
}
|
|
983
|
+
bots.delete(name);
|
|
984
|
+
saveBotRegistry();
|
|
985
|
+
log(`bot "${name}" removed`);
|
|
986
|
+
return null;
|
|
987
|
+
}
|
|
988
|
+
function registerRoute(conn) {
|
|
989
|
+
const { bot, cfg } = conn;
|
|
990
|
+
if (isCatchAll(cfg.chatId)) {
|
|
991
|
+
if (bot.catchAll && bot.catchAll !== conn) return `bot ${botLabel(bot)} already has a catch-all route ("${bot.catchAll.cfg.name}")`;
|
|
992
|
+
bot.catchAll = conn;
|
|
993
|
+
} else {
|
|
994
|
+
const key = chatKey(cfg.chatId, cfg.threadId || void 0);
|
|
995
|
+
const existing = bot.exact.get(key);
|
|
996
|
+
if (existing && existing !== conn) return `bot ${botLabel(bot)} already routes ${key} to "${existing.cfg.name}"`;
|
|
997
|
+
bot.exact.set(key, conn);
|
|
998
|
+
}
|
|
999
|
+
return null;
|
|
1000
|
+
}
|
|
1001
|
+
function unregisterRoute(conn) {
|
|
1002
|
+
for (const [k, v] of conn.bot.exact) if (v === conn) conn.bot.exact.delete(k);
|
|
1003
|
+
if (conn.bot.catchAll === conn) conn.bot.catchAll = null;
|
|
1004
|
+
}
|
|
1005
|
+
function reregisterRoute(conn) {
|
|
1006
|
+
unregisterRoute(conn);
|
|
1007
|
+
return registerRoute(conn);
|
|
1008
|
+
}
|
|
1009
|
+
function routeSlotConflict(bot, chatId, threadId) {
|
|
1010
|
+
if (isCatchAll(chatId)) {
|
|
1011
|
+
if (bot.catchAll) return `bot ${botLabel(bot)} already has a catch-all route ("${bot.catchAll.cfg.name}")`;
|
|
1012
|
+
return null;
|
|
1013
|
+
}
|
|
1014
|
+
const key = chatKey(chatId, threadId || void 0);
|
|
1015
|
+
const existing = bot.exact.get(key);
|
|
1016
|
+
return existing ? `bot ${botLabel(bot)} already routes ${key} to "${existing.cfg.name}"` : null;
|
|
1017
|
+
}
|
|
1018
|
+
async function resolveAttachment(conn, d) {
|
|
1019
|
+
const cap = CONFIG.attachmentMaxBytes;
|
|
1020
|
+
if (d.file_size !== void 0 && d.file_size > cap) {
|
|
1021
|
+
return { ok: false, reason: "too_large", detail: `exceeds ${cap}-byte cap (size ${d.file_size})` };
|
|
1022
|
+
}
|
|
1023
|
+
try {
|
|
1024
|
+
const bytes = await conn.bot.tg.downloadFile(d.file_id);
|
|
1025
|
+
if (bytes.length > cap) {
|
|
1026
|
+
return { ok: false, reason: "too_large", detail: `exceeds ${cap}-byte cap (size ${bytes.length})` };
|
|
1027
|
+
}
|
|
1028
|
+
return { ok: true, bytes };
|
|
1029
|
+
} catch (err) {
|
|
1030
|
+
return { ok: false, reason: "error", detail: err instanceof Error ? err.message : String(err) };
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
async function forwardToNode(conn, m) {
|
|
1034
|
+
const { pkt, cfg } = conn;
|
|
1035
|
+
const resolved = m.attachment ? await resolveAttachment(conn, m.attachment) : void 0;
|
|
1036
|
+
const targets = [];
|
|
1037
|
+
if (cfg.peerCid) {
|
|
1038
|
+
targets.push(cfg.peerCid);
|
|
1039
|
+
} else {
|
|
1040
|
+
withScope((lt) => {
|
|
1041
|
+
for (const c of renderContacts(pkt.readonlyTx("::a2a_messaging::list_contacts", lt))) targets.push(c.container_id);
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
if (targets.length === 0) {
|
|
1045
|
+
log(`[${cfg.name}] telegram message from ${m.from} dropped \u2014 proxy agent has not accepted the invite yet`);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
for (const target of targets) {
|
|
1049
|
+
let fileWireId;
|
|
1050
|
+
if (m.attachment && resolved?.ok) {
|
|
1051
|
+
const meta = attachmentMeta(m.attachment, m.message_id);
|
|
1052
|
+
const fileBytes = resolved.bytes;
|
|
1053
|
+
try {
|
|
1054
|
+
fileWireId = await withScopeAsync(async (lt) => {
|
|
1055
|
+
const r = await pkt.mutatingTx(
|
|
1056
|
+
"::a2a_messaging::send_file",
|
|
1057
|
+
{ contact: target, filename: meta.filename, mime: meta.mime, data: pkt.newBinary(fileBytes, lt) },
|
|
1058
|
+
lt
|
|
1059
|
+
);
|
|
1060
|
+
return r.Reduce("wire_id").Visualize();
|
|
1061
|
+
});
|
|
1062
|
+
} catch (err) {
|
|
1063
|
+
log(`[${cfg.name}] send_file to ${target} failed:`, String(err));
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
const body = buildEnvelope(m, resolved, fileWireId);
|
|
1067
|
+
try {
|
|
1068
|
+
const { deferred, queued } = await withScopeAsync(async (lt) => {
|
|
1069
|
+
const sent = await pkt.mutatingTx("::a2a_messaging::send_message", { contact: target, text: body }, lt);
|
|
1070
|
+
const defAv = sent.Reduce("deferred");
|
|
1071
|
+
return {
|
|
1072
|
+
deferred: !defAv.IsNil(),
|
|
1073
|
+
queued: defAv.IsNil() ? 0 : Number(sent.Reduce("queued").Visualize())
|
|
1074
|
+
};
|
|
1075
|
+
});
|
|
1076
|
+
if (deferred) {
|
|
1077
|
+
log(`[${cfg.name}] message to ${target} queued \u2014 contact restore in progress (${queued} queued)`);
|
|
1078
|
+
}
|
|
1079
|
+
} catch (err) {
|
|
1080
|
+
log(`[${cfg.name}] send_message to ${target} failed:`, String(err));
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
async function forwardToTelegram(conn) {
|
|
1085
|
+
const { pkt, cfg, bot } = conn;
|
|
1086
|
+
let fresh;
|
|
1087
|
+
try {
|
|
1088
|
+
fresh = await withScopeAsync(async (lt) => renderInbox((await pkt.mutatingTx("::actor::get_messages", {}, lt)).Reduce("messages")));
|
|
1089
|
+
} catch (err) {
|
|
1090
|
+
log(`[${cfg.name}] get_messages failed:`, String(err));
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
if (fresh.length === 0) return;
|
|
1094
|
+
const target = deliveryTarget(cfg.chatId, cfg.threadId, conn.lastChat);
|
|
1095
|
+
if (!target || !target.chatId || isCatchAll(target.chatId)) {
|
|
1096
|
+
log(`[${cfg.name}] ${fresh.length} agent message(s) with no known destination chat \u2014 deferring`);
|
|
1097
|
+
try {
|
|
1098
|
+
await withScopeAsync((lt) => pkt.mutatingTx("::actor::defer_messages", { msg_ids: fresh.map((m) => m.msg_id) }, lt));
|
|
1099
|
+
} catch {
|
|
1100
|
+
}
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
for (const m of fresh) {
|
|
1104
|
+
try {
|
|
1105
|
+
await bot.tg.sendMessage(target.chatId, m.text, target.threadId || void 0);
|
|
1106
|
+
} catch (err) {
|
|
1107
|
+
log(`[${cfg.name}] telegram delivery failed for #${m.msg_id}:`, String(err));
|
|
1108
|
+
try {
|
|
1109
|
+
await withScopeAsync((lt) => pkt.mutatingTx("::actor::defer_messages", { msg_ids: [m.msg_id] }, lt));
|
|
1110
|
+
} catch {
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
async function forwardFilesToTelegram(conn) {
|
|
1116
|
+
const { pkt, cfg, bot } = conn;
|
|
1117
|
+
let fresh;
|
|
1118
|
+
try {
|
|
1119
|
+
fresh = await withScopeAsync(async (lt) => renderFiles((await pkt.mutatingTx("::actor::get_files", {}, lt)).Reduce("files")));
|
|
1120
|
+
} catch (err) {
|
|
1121
|
+
log(`[${cfg.name}] get_files failed:`, String(err));
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
if (fresh.length === 0) return;
|
|
1125
|
+
const target = deliveryTarget(cfg.chatId, cfg.threadId, conn.lastChat);
|
|
1126
|
+
if (!target || !target.chatId || isCatchAll(target.chatId)) {
|
|
1127
|
+
log(`[${cfg.name}] ${fresh.length} agent file(s) with no known destination chat \u2014 deferring`);
|
|
1128
|
+
try {
|
|
1129
|
+
await withScopeAsync((lt) => pkt.mutatingTx("::actor::defer_files", { file_ids: fresh.map((f) => f.file_id) }, lt));
|
|
1130
|
+
} catch {
|
|
1131
|
+
}
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
for (const f of fresh) {
|
|
1135
|
+
if (f.bytes.length > CONFIG.outboundFileMaxBytes) {
|
|
1136
|
+
log(`[${cfg.name}] file #${f.file_id} "${f.filename}" (${f.bytes.length} B) exceeds the ${CONFIG.outboundFileMaxBytes}-byte upload cap \u2014 skipping`);
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
try {
|
|
1140
|
+
await bot.tg.sendDocument(target.chatId, f.bytes, f.filename, f.mime || void 0, target.threadId || void 0);
|
|
1141
|
+
} catch (err) {
|
|
1142
|
+
log(`[${cfg.name}] telegram file delivery failed for #${f.file_id}:`, String(err));
|
|
1143
|
+
try {
|
|
1144
|
+
await withScopeAsync((lt) => pkt.mutatingTx("::actor::defer_files", { file_ids: [f.file_id] }, lt));
|
|
1145
|
+
} catch {
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
async function onBotMessage(bot, m) {
|
|
1151
|
+
if (isIdCommand(m.text, bot.username)) {
|
|
1152
|
+
const reply = formatChatIdReply({
|
|
1153
|
+
chatId: m.chat_id,
|
|
1154
|
+
chatType: m.chat_type,
|
|
1155
|
+
chatTitle: m.chat_title,
|
|
1156
|
+
chatUsername: m.chat_username,
|
|
1157
|
+
threadId: m.thread_id,
|
|
1158
|
+
isTopic: m.is_topic,
|
|
1159
|
+
fromId: m.from_id,
|
|
1160
|
+
fromLabel: m.from,
|
|
1161
|
+
botName: bot.name,
|
|
1162
|
+
botUsername: bot.username
|
|
1163
|
+
});
|
|
1164
|
+
try {
|
|
1165
|
+
await bot.tg.sendMessage(m.chat_id, reply, m.thread_id);
|
|
1166
|
+
} catch (err) {
|
|
1167
|
+
log(`[bot ${botLabel(bot)}] failed to answer /id in chat ${m.chat_id}:`, String(err));
|
|
1168
|
+
}
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
const conn = resolveRoute(bot.exact, bot.catchAll, m.chat_id, m.thread_id);
|
|
1172
|
+
if (!conn) {
|
|
1173
|
+
const only = bot.exact.size === 1 && !bot.catchAll ? [...bot.exact.values()][0] : null;
|
|
1174
|
+
if (only && only.cfg.deniedMessage) {
|
|
1175
|
+
try {
|
|
1176
|
+
await bot.tg.sendMessage(m.chat_id, only.cfg.deniedMessage, m.thread_id);
|
|
1177
|
+
} catch (err) {
|
|
1178
|
+
log(`[bot ${botLabel(bot)}] failed to send denial to chat ${m.chat_id}:`, String(err));
|
|
1179
|
+
}
|
|
1180
|
+
} else {
|
|
1181
|
+
log(`[bot ${botLabel(bot)}] no route for ${chatKey(m.chat_id, m.thread_id)} \u2014 ignoring`);
|
|
1182
|
+
}
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
conn.lastChat = { chatId: String(m.chat_id), threadId: m.thread_id ? String(m.thread_id) : "" };
|
|
1186
|
+
await forwardToNode(conn, m);
|
|
1187
|
+
}
|
|
1188
|
+
function activateRoute(conn) {
|
|
1189
|
+
const { pkt, dir, cfg } = conn;
|
|
1190
|
+
wireHandlers(
|
|
1191
|
+
pkt,
|
|
1192
|
+
{
|
|
1193
|
+
onSaveState: () => saveState(pkt, dir),
|
|
1194
|
+
onNotify: (event, payload) => {
|
|
1195
|
+
if (event === "message_received") {
|
|
1196
|
+
process.nextTick(() => void forwardToTelegram(conn));
|
|
1197
|
+
} else if (event === "file_received") {
|
|
1198
|
+
process.nextTick(() => void forwardFilesToTelegram(conn));
|
|
1199
|
+
} else if (event === "control_request") {
|
|
1200
|
+
process.nextTick(() => void processControlRequests(conn));
|
|
1201
|
+
} else if (event === "contact_accepted" || event === "sibling_contact_added") {
|
|
1202
|
+
const cid = payload.Reduce("container_id").Visualize();
|
|
1203
|
+
const name = payload.Reduce("name").Visualize();
|
|
1204
|
+
if (cid && !cfg.peerCid) {
|
|
1205
|
+
cfg.peerCid = cid;
|
|
1206
|
+
writeMeta(dir, cfg);
|
|
1207
|
+
log(`[${cfg.name}] proxy agent connected: "${name}" (${cid})`);
|
|
1208
|
+
} else {
|
|
1209
|
+
log(`[${cfg.name}] contact added: "${name}" (${cid})`);
|
|
1210
|
+
}
|
|
1211
|
+
} else if (event === "contact_restored") {
|
|
1212
|
+
const name = payload.Reduce("name").Visualize();
|
|
1213
|
+
const cid = payload.Reduce("container_id").Visualize();
|
|
1214
|
+
log(`[${cfg.name}] contact "${name}" restored (re-keyed)`);
|
|
1215
|
+
process.nextTick(() => void flushDeferredFor(pkt, String(cid)));
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
},
|
|
1219
|
+
log
|
|
1220
|
+
);
|
|
1221
|
+
}
|
|
1222
|
+
function activateBot(bot) {
|
|
1223
|
+
if (bot.pollHandle) return;
|
|
1224
|
+
bot.pollHandle = bot.tg.poll((m) => onBotMessage(bot, m));
|
|
1225
|
+
}
|
|
1226
|
+
var controlBusy = /* @__PURE__ */ new Set();
|
|
1227
|
+
async function processControlRequests(conn) {
|
|
1228
|
+
if (controlBusy.has(conn.cfg.name)) return;
|
|
1229
|
+
controlBusy.add(conn.cfg.name);
|
|
1230
|
+
try {
|
|
1231
|
+
for (; ; ) {
|
|
1232
|
+
const reqs = await withScopeAsync(async (lt) => renderControlRequests((await conn.pkt.mutatingTx("::actor::get_control_requests", {}, lt)).Reduce("requests")));
|
|
1233
|
+
if (reqs.length === 0) return;
|
|
1234
|
+
for (const req of reqs) {
|
|
1235
|
+
const beforeKey = `${conn.cfg.chatId}\0${conn.cfg.threadId}`;
|
|
1236
|
+
await dispatchControlRequest(conn.pkt, conn.cfg, req, {
|
|
1237
|
+
persist: () => writeMeta(conn.dir, conn.cfg),
|
|
1238
|
+
log: (m) => log(`[${conn.cfg.name}] ${m}`)
|
|
1239
|
+
});
|
|
1240
|
+
const afterKey = `${conn.cfg.chatId}\0${conn.cfg.threadId}`;
|
|
1241
|
+
if (beforeKey !== afterKey) {
|
|
1242
|
+
const conflict = reregisterRoute(conn);
|
|
1243
|
+
if (conflict) log(`[${conn.cfg.name}] re-route after config change failed: ${conflict}`);
|
|
1244
|
+
else log(`[${conn.cfg.name}] re-routed to ${chatKey(conn.cfg.chatId, conn.cfg.threadId || void 0)} after config change`);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
} catch (err) {
|
|
1249
|
+
log(`[${conn.cfg.name}] control dispatch failed:`, String(err));
|
|
1250
|
+
} finally {
|
|
1251
|
+
controlBusy.delete(conn.cfg.name);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
async function startBind(conn, contactRef) {
|
|
1255
|
+
const code = String(randomBytes(3).readUIntBE(0, 3) % 1e6).padStart(6, "0");
|
|
1256
|
+
await withScopeAsync((lt) => conn.pkt.mutatingTx("::a2a_messaging::set_proxy_pending", { code, proxy: contactRef }, lt));
|
|
1257
|
+
log(`[${conn.cfg.name}] proxy bind started for "${contactRef}" \u2014 code ${code}`);
|
|
1258
|
+
return code;
|
|
1259
|
+
}
|
|
1260
|
+
async function createConnection(args) {
|
|
1261
|
+
const bot = bots.get(args.botName);
|
|
1262
|
+
if (!bot) throw new Error(`no bot named "${args.botName}" \u2014 register it with add_bot`);
|
|
1263
|
+
try {
|
|
1264
|
+
const slotErr = routeSlotConflict(bot, args.chatId, args.threadId);
|
|
1265
|
+
if (slotErr) throw new Error(slotErr);
|
|
1266
|
+
const dir = connDir(args.name);
|
|
1267
|
+
fs3.mkdirSync(dir, { recursive: true });
|
|
1268
|
+
const seed = randomBytes(24).toString("hex");
|
|
1269
|
+
const pkt = await host.createPacket(args.name, seed);
|
|
1270
|
+
fs3.writeFileSync(keyPath(dir), exportSigningSecret(pkt), { mode: 384 });
|
|
1271
|
+
const cfg = {
|
|
1272
|
+
v: 1,
|
|
1273
|
+
name: args.name,
|
|
1274
|
+
botName: args.botName,
|
|
1275
|
+
chatId: args.chatId,
|
|
1276
|
+
threadId: args.threadId,
|
|
1277
|
+
label: args.label,
|
|
1278
|
+
bio: args.bio,
|
|
1279
|
+
deniedMessage: DEFAULT_DENIED,
|
|
1280
|
+
peerCid: "",
|
|
1281
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1282
|
+
};
|
|
1283
|
+
const conn = { pkt, dir, cfg, bot, lastChat: null };
|
|
1284
|
+
connections.set(args.name, conn);
|
|
1285
|
+
activateRoute(conn);
|
|
1286
|
+
const conflict = registerRoute(conn);
|
|
1287
|
+
if (conflict) throw new Error(conflict);
|
|
1288
|
+
await withScopeAsync((lt) => pkt.mutatingTx("::a2a_messaging::set_my_name", { name: args.name }, lt));
|
|
1289
|
+
if (args.bio) await withScopeAsync((lt) => pkt.mutatingTx("::a2a_messaging::set_my_bio", { bio: args.bio }, lt));
|
|
1290
|
+
writeMeta(dir, cfg);
|
|
1291
|
+
saveState(pkt, dir);
|
|
1292
|
+
activateBot(bot);
|
|
1293
|
+
const invite = await withScopeAsync(
|
|
1294
|
+
async (lt) => packInvite(Buffer.from((await pkt.mutatingTx("::a2a_messaging::generate_invite", {}, lt)).Reduce("invite").GetBinary()))
|
|
1295
|
+
);
|
|
1296
|
+
const key = isCatchAll(cfg.chatId) ? "any chat" : chatKey(cfg.chatId, cfg.threadId || void 0);
|
|
1297
|
+
log(`[${args.name}] route created (bot ${botLabel(bot)}, ${key})`);
|
|
1298
|
+
return { cid: pkt.cid, invite, botUsername: bot.username };
|
|
1299
|
+
} catch (err) {
|
|
1300
|
+
if (connections.has(args.name)) removeConnection(args.name);
|
|
1301
|
+
throw err;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
async function restoreConnection(name) {
|
|
1305
|
+
const dir = connDir(name);
|
|
1306
|
+
const cfg = readMeta(dir);
|
|
1307
|
+
const bot = bots.get(cfg.botName);
|
|
1308
|
+
if (!bot) {
|
|
1309
|
+
log(`[${name}] references unknown bot "${cfg.botName}" \u2014 skipping (add_bot then restart)`);
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
const secret = fs3.readFileSync(keyPath(dir), "utf8").trim();
|
|
1313
|
+
const pkt = await host.createPacket(name, "", secret);
|
|
1314
|
+
const conn = { pkt, dir, cfg, bot, lastChat: null };
|
|
1315
|
+
connections.set(name, conn);
|
|
1316
|
+
activateRoute(conn);
|
|
1317
|
+
const conflict = registerRoute(conn);
|
|
1318
|
+
if (conflict) log(`[${name}] route conflict on restore: ${conflict} \u2014 left unrouted`);
|
|
1319
|
+
if (hasSavedState(dir)) {
|
|
1320
|
+
try {
|
|
1321
|
+
const buf = fs3.readFileSync(dataPath(dir));
|
|
1322
|
+
await withScopeAsync(async (lt) => {
|
|
1323
|
+
const adaptData = pkt.pw.packet.ParseValue(new Uint8Array(buf)).Attach(lt);
|
|
1324
|
+
await pkt.mutatingTx("::actor::import_state", adaptData, lt);
|
|
1325
|
+
});
|
|
1326
|
+
} catch (err) {
|
|
1327
|
+
log(`[${name}] FAILED TO IMPORT SAVED STATE \u2014 continuing with the reseeded identity; surviving contacts (if the blob was partially migrated) self-heal via contact restore:`, String(err));
|
|
1328
|
+
try {
|
|
1329
|
+
fs3.renameSync(dataPath(dir), `${dataPath(dir)}.failed-${Date.now()}`);
|
|
1330
|
+
log(`[${name}] unreadable state blob preserved as state_data.bin.failed-*`);
|
|
1331
|
+
} catch {
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
const key = isCatchAll(cfg.chatId) ? "any chat" : chatKey(cfg.chatId, cfg.threadId || void 0);
|
|
1336
|
+
log(`[${name}] restored (bot ${botLabel(bot)}, ${key}${cfg.peerCid ? `, peer ${cfg.peerCid}` : ", awaiting proxy"})`);
|
|
1337
|
+
await contactRestoreSweep(pkt);
|
|
1338
|
+
process.nextTick(() => void processControlRequests(conn));
|
|
1339
|
+
}
|
|
1340
|
+
function removeConnection(name) {
|
|
1341
|
+
const conn = connections.get(name);
|
|
1342
|
+
if (!conn) return `no connection named "${name}"`;
|
|
1343
|
+
unregisterRoute(conn);
|
|
1344
|
+
try {
|
|
1345
|
+
host.removePacket(conn.pkt.cid);
|
|
1346
|
+
} catch (err) {
|
|
1347
|
+
log(`[${name}] remove_packet failed:`, String(err));
|
|
1348
|
+
}
|
|
1349
|
+
connections.delete(name);
|
|
1350
|
+
try {
|
|
1351
|
+
fs3.rmSync(conn.dir, { recursive: true, force: true });
|
|
1352
|
+
} catch (err) {
|
|
1353
|
+
return `deleting ${conn.dir} failed: ${String(err)}`;
|
|
1354
|
+
}
|
|
1355
|
+
return null;
|
|
1356
|
+
}
|
|
1357
|
+
function readBody(req) {
|
|
1358
|
+
return new Promise((resolve3, reject) => {
|
|
1359
|
+
let data = "";
|
|
1360
|
+
req.on("data", (chunk) => data += chunk);
|
|
1361
|
+
req.on("end", () => {
|
|
1362
|
+
if (!data) return resolve3({});
|
|
1363
|
+
try {
|
|
1364
|
+
resolve3(JSON.parse(data));
|
|
1365
|
+
} catch (e) {
|
|
1366
|
+
reject(e);
|
|
1367
|
+
}
|
|
1368
|
+
});
|
|
1369
|
+
req.on("error", reject);
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
function sendJson(res, status, body) {
|
|
1373
|
+
const text = JSON.stringify(body);
|
|
1374
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
1375
|
+
res.end(text);
|
|
1376
|
+
}
|
|
1377
|
+
function describeBot(bot) {
|
|
1378
|
+
const routes = [...bot.exact.values()].map((c) => c.cfg.name);
|
|
1379
|
+
if (bot.catchAll) routes.push(bot.catchAll.cfg.name);
|
|
1380
|
+
return {
|
|
1381
|
+
name: bot.name,
|
|
1382
|
+
username: bot.username || null,
|
|
1383
|
+
tokenMasked: `${bot.token.slice(0, 8)}\u2026`,
|
|
1384
|
+
routeCount: routes.length,
|
|
1385
|
+
routes,
|
|
1386
|
+
polling: bot.pollHandle !== null,
|
|
1387
|
+
createdAt: bot.createdAt
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
function describeConnection(conn) {
|
|
1391
|
+
const contacts = withScope((lt) => renderContacts(conn.pkt.readonlyTx("::a2a_messaging::list_contacts", lt)));
|
|
1392
|
+
const mon = monitoringStatus(conn.pkt);
|
|
1393
|
+
return {
|
|
1394
|
+
name: conn.cfg.name,
|
|
1395
|
+
cid: conn.pkt.cid,
|
|
1396
|
+
botName: conn.cfg.botName,
|
|
1397
|
+
botUsername: conn.bot.username || null,
|
|
1398
|
+
chatId: conn.cfg.chatId,
|
|
1399
|
+
threadId: conn.cfg.threadId || null,
|
|
1400
|
+
label: conn.cfg.label,
|
|
1401
|
+
bio: conn.cfg.bio || null,
|
|
1402
|
+
deniedMessage: conn.cfg.deniedMessage || DEFAULT_DENIED,
|
|
1403
|
+
peerCid: conn.cfg.peerCid || null,
|
|
1404
|
+
controlPlaneCid: mon.proxyCid || null,
|
|
1405
|
+
bound: mon.proxyCid !== "",
|
|
1406
|
+
contacts: contacts.map((c) => ({ name: c.name, cid: c.container_id })),
|
|
1407
|
+
createdAt: conn.cfg.createdAt
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
function startControlServer() {
|
|
1411
|
+
const server = createHttpServer(async (req, res) => {
|
|
1412
|
+
const url = new URL(req.url ?? "/", `http://127.0.0.1:${CONFIG.controlPort}`);
|
|
1413
|
+
try {
|
|
1414
|
+
if (req.method === "GET" && url.pathname === "/health") {
|
|
1415
|
+
return sendJson(res, 200, { ok: true, stateDir: STATE_DIR, connections: connections.size, bots: bots.size });
|
|
1416
|
+
}
|
|
1417
|
+
if (req.method === "GET" && url.pathname === "/connections") {
|
|
1418
|
+
return sendJson(res, 200, { ok: true, connections: [...connections.values()].map(describeConnection) });
|
|
1419
|
+
}
|
|
1420
|
+
if (req.method === "POST" && url.pathname === "/connections") {
|
|
1421
|
+
const body = await readBody(req);
|
|
1422
|
+
const name = String(body.name ?? "").trim();
|
|
1423
|
+
const botName = String(body.botName ?? "").trim();
|
|
1424
|
+
const chatId = String(body.chatId ?? "").trim();
|
|
1425
|
+
const threadId = String(body.threadId ?? "").trim();
|
|
1426
|
+
const label = String(body.label ?? "").trim();
|
|
1427
|
+
const bio = String(body.bio ?? "").trim();
|
|
1428
|
+
const bad = validateName(name);
|
|
1429
|
+
if (bad) return sendJson(res, 400, { ok: false, error: bad });
|
|
1430
|
+
if (!botName) return sendJson(res, 400, { ok: false, error: "botName is required (register a bot with add_bot first)" });
|
|
1431
|
+
if (!chatId) return sendJson(res, 400, { ok: false, error: "chatId is required (use 0 for a catch-all route)" });
|
|
1432
|
+
if (!bots.has(botName)) return sendJson(res, 404, { ok: false, error: `no bot named "${botName}" \u2014 register it with add_bot` });
|
|
1433
|
+
if (connections.has(name)) return sendJson(res, 409, { ok: false, error: `a connection named "${name}" already exists` });
|
|
1434
|
+
try {
|
|
1435
|
+
const out = await createConnection({ name, botName, chatId, threadId, label, bio });
|
|
1436
|
+
return sendJson(res, 201, { ok: true, ...out });
|
|
1437
|
+
} catch (err) {
|
|
1438
|
+
return sendJson(res, 500, { ok: false, error: String(err) });
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
if (req.method === "GET" && url.pathname === "/bots") {
|
|
1442
|
+
return sendJson(res, 200, { ok: true, bots: [...bots.values()].map(describeBot) });
|
|
1443
|
+
}
|
|
1444
|
+
if (req.method === "POST" && url.pathname === "/bots") {
|
|
1445
|
+
const body = await readBody(req);
|
|
1446
|
+
const name = String(body.name ?? "").trim();
|
|
1447
|
+
const botToken = String(body.botToken ?? "").trim();
|
|
1448
|
+
const bad = validateName(name);
|
|
1449
|
+
if (bad) return sendJson(res, 400, { ok: false, error: bad });
|
|
1450
|
+
if (!botToken) return sendJson(res, 400, { ok: false, error: "botToken is required" });
|
|
1451
|
+
try {
|
|
1452
|
+
const out = await addBot(name, botToken);
|
|
1453
|
+
return sendJson(res, 201, { ok: true, ...out });
|
|
1454
|
+
} catch (err) {
|
|
1455
|
+
const msg = String(err);
|
|
1456
|
+
return sendJson(res, /already exists|already registered/.test(msg) ? 409 : 400, { ok: false, error: msg });
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
const botDelMatch = url.pathname.match(/^\/bots\/(.+)$/);
|
|
1460
|
+
if (req.method === "DELETE" && botDelMatch) {
|
|
1461
|
+
const name = decodeURIComponent(botDelMatch[1]);
|
|
1462
|
+
const fail = removeBot(name);
|
|
1463
|
+
if (fail) return sendJson(res, fail.startsWith("no bot") ? 404 : 409, { ok: false, error: fail });
|
|
1464
|
+
return sendJson(res, 200, { ok: true, removed: name });
|
|
1465
|
+
}
|
|
1466
|
+
const inviteMatch = url.pathname.match(/^\/connections\/([^/]+)\/cp-invite$/);
|
|
1467
|
+
if (req.method === "POST" && inviteMatch) {
|
|
1468
|
+
const name = decodeURIComponent(inviteMatch[1]);
|
|
1469
|
+
const conn = connections.get(name);
|
|
1470
|
+
if (!conn) return sendJson(res, 404, { ok: false, error: `no connection named "${name}"` });
|
|
1471
|
+
try {
|
|
1472
|
+
const invite = await withScopeAsync(
|
|
1473
|
+
async (lt) => packInvite(Buffer.from((await conn.pkt.mutatingTx("::a2a_messaging::generate_invite", {}, lt)).Reduce("invite").GetBinary()))
|
|
1474
|
+
);
|
|
1475
|
+
return sendJson(res, 200, { ok: true, invite });
|
|
1476
|
+
} catch (err) {
|
|
1477
|
+
return sendJson(res, 500, { ok: false, error: String(err) });
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
const bindMatch = url.pathname.match(/^\/connections\/([^/]+)\/bind$/);
|
|
1481
|
+
if (req.method === "POST" && bindMatch) {
|
|
1482
|
+
const name = decodeURIComponent(bindMatch[1]);
|
|
1483
|
+
const conn = connections.get(name);
|
|
1484
|
+
if (!conn) return sendJson(res, 404, { ok: false, error: `no connection named "${name}"` });
|
|
1485
|
+
const body = await readBody(req);
|
|
1486
|
+
const contact = String(body.contact ?? "").trim();
|
|
1487
|
+
if (!contact) return sendJson(res, 400, { ok: false, error: "contact (name or container id) is required" });
|
|
1488
|
+
try {
|
|
1489
|
+
const code = await startBind(conn, contact);
|
|
1490
|
+
return sendJson(res, 200, { ok: true, code });
|
|
1491
|
+
} catch (err) {
|
|
1492
|
+
return sendJson(res, 500, { ok: false, error: String(err) });
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
const delMatch = url.pathname.match(/^\/connections\/(.+)$/);
|
|
1496
|
+
if (req.method === "DELETE" && delMatch) {
|
|
1497
|
+
const name = decodeURIComponent(delMatch[1]);
|
|
1498
|
+
const fail = removeConnection(name);
|
|
1499
|
+
if (fail) return sendJson(res, fail.startsWith("no connection") ? 404 : 500, { ok: false, error: fail });
|
|
1500
|
+
return sendJson(res, 200, { ok: true, removed: name });
|
|
1501
|
+
}
|
|
1502
|
+
sendJson(res, 404, { ok: false, error: "not found" });
|
|
1503
|
+
} catch (err) {
|
|
1504
|
+
log("control handler error:", String(err));
|
|
1505
|
+
if (!res.headersSent) sendJson(res, 500, { ok: false, error: "internal error" });
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
server.listen(CONFIG.controlPort, "127.0.0.1", () => {
|
|
1509
|
+
log(`control API on http://127.0.0.1:${CONFIG.controlPort} (POST/GET/DELETE /connections)`);
|
|
1510
|
+
});
|
|
1511
|
+
const shutdown = () => {
|
|
1512
|
+
log("shutting down\u2026");
|
|
1513
|
+
for (const bot of bots.values()) {
|
|
1514
|
+
try {
|
|
1515
|
+
bot.tg.stop();
|
|
1516
|
+
} catch {
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
for (const conn of connections.values()) saveState(conn.pkt, conn.dir);
|
|
1520
|
+
server.close();
|
|
1521
|
+
process.exit(0);
|
|
1522
|
+
};
|
|
1523
|
+
process.on("SIGINT", shutdown);
|
|
1524
|
+
process.on("SIGTERM", shutdown);
|
|
1525
|
+
}
|
|
1526
|
+
var RESTORE_SWEEP_INTERVAL_MS = 36e5;
|
|
1527
|
+
var restoreSweepRunning = false;
|
|
1528
|
+
function startRestoreSweepTimer() {
|
|
1529
|
+
setInterval(() => {
|
|
1530
|
+
if (restoreSweepRunning) return;
|
|
1531
|
+
restoreSweepRunning = true;
|
|
1532
|
+
void (async () => {
|
|
1533
|
+
try {
|
|
1534
|
+
for (const conn of connections.values()) {
|
|
1535
|
+
await contactRestoreSweep(conn.pkt);
|
|
1536
|
+
}
|
|
1537
|
+
} finally {
|
|
1538
|
+
restoreSweepRunning = false;
|
|
1539
|
+
}
|
|
1540
|
+
})();
|
|
1541
|
+
}, RESTORE_SWEEP_INTERVAL_MS).unref();
|
|
1542
|
+
log(`contact restore-retry timer armed (every ${RESTORE_SWEEP_INTERVAL_MS}ms)`);
|
|
1543
|
+
}
|
|
1544
|
+
async function main() {
|
|
1545
|
+
log(`booting (state ${STATE_DIR}, broker ${CONFIG.brokerUrl})`);
|
|
1546
|
+
await host.boot();
|
|
1547
|
+
const botRecs = loadBotRegistry();
|
|
1548
|
+
for (const rec of botRecs) instantiateBot(rec);
|
|
1549
|
+
if (botRecs.length) log(`loaded ${botRecs.length} bot(s): ${botRecs.map((b) => b.name).join(", ")}`);
|
|
1550
|
+
const names = listPersistedNames();
|
|
1551
|
+
if (names.length === 0) {
|
|
1552
|
+
log("no persisted routes \u2014 add a bot with `add_bot`, then a route with `add_new_connection`");
|
|
1553
|
+
} else {
|
|
1554
|
+
log(`restoring ${names.length} route(s): ${names.join(", ")}`);
|
|
1555
|
+
for (const name of names) {
|
|
1556
|
+
try {
|
|
1557
|
+
await restoreConnection(name);
|
|
1558
|
+
} catch (err) {
|
|
1559
|
+
log(`failed to restore "${name}":`, String(err));
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
for (const bot of bots.values()) {
|
|
1564
|
+
try {
|
|
1565
|
+
if (!bot.username) bot.username = (await bot.tg.getMe()).username;
|
|
1566
|
+
} catch (err) {
|
|
1567
|
+
log(`[bot ${botLabel(bot)}] getMe failed (polling anyway):`, String(err));
|
|
1568
|
+
}
|
|
1569
|
+
activateBot(bot);
|
|
1570
|
+
}
|
|
1571
|
+
startControlServer();
|
|
1572
|
+
startRestoreSweepTimer();
|
|
1573
|
+
log(`ready (bots=${bots.size}, routes=${connections.size})`);
|
|
1574
|
+
}
|
|
1575
|
+
main().catch((err) => {
|
|
1576
|
+
log(`fatal startup error: ${err?.stack ?? err}`);
|
|
1577
|
+
process.exit(1);
|
|
1578
|
+
});
|