@drisp/cli 0.5.28 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4148 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- loadOrCreateToken,
4
- requireTokenForBind,
5
- timingSafeTokenEqual
6
- } from "./chunk-MSPZOJMJ.js";
7
- import {
8
- CHANNEL_REQUEST_ID_REGEX,
9
- createUdsServerTransport,
10
- createWsServerTransport,
11
- generateChannelRequestId,
12
- isLoopbackHost,
13
- isValidChannelRequestId,
14
- openVersionedDb,
15
- refreshDashboardAccessToken,
16
- resolveGatewayPaths,
17
- resolveListenSpec,
18
- trackGatewayRuntimeExpired,
19
- trackGatewayRuntimeRebind,
20
- trackGatewayTransportConnect,
21
- trackGatewayTransportDisconnect,
22
- writeGatewayTrace
23
- } from "./chunk-VAFS446Y.js";
24
-
25
- // src/gateway/daemon.ts
26
- import fs4 from "fs";
27
-
28
- // src/gateway/channelManager.ts
29
- var DEFAULT_DEDUP_WINDOW = 1024;
30
- var DuplicateChannelError = class extends Error {
31
- constructor(id) {
32
- super(`channel ${id} already registered`);
33
- this.name = "DuplicateChannelError";
34
- }
35
- };
36
- var UnknownChannelError = class extends Error {
37
- constructor(id) {
38
- super(`channel ${id} not registered`);
39
- this.name = "UnknownChannelError";
40
- }
41
- };
42
- var ChannelManager = class {
43
- entries = /* @__PURE__ */ new Map();
44
- dedup = [];
45
- dedupSet = /* @__PURE__ */ new Set();
46
- dedupMax;
47
- log;
48
- inboundSink = null;
49
- healthSink = null;
50
- stopped = false;
51
- constructor(opts = {}) {
52
- this.dedupMax = opts.dedupWindow ?? DEFAULT_DEDUP_WINDOW;
53
- this.log = opts.log;
54
- }
55
- /** Register the single inbound dispatch target. M5 wires the router here. */
56
- setInboundSink(sink) {
57
- this.inboundSink = sink;
58
- }
59
- /**
60
- * Returns the attachmentId associated with `channelId` at registration
61
- * time, or undefined if the channel is unknown or registered without one.
62
- */
63
- getAttachmentId(channelId) {
64
- return this.entries.get(channelId)?.attachmentId;
65
- }
66
- setHealthSink(sink) {
67
- this.healthSink = sink;
68
- }
69
- listChannels() {
70
- return [...this.entries.values()].map((e) => ({
71
- id: e.adapter.id,
72
- health: e.lastHealth
73
- }));
74
- }
75
- /** Snapshot of currently registered adapters; used by the relay coordinator. */
76
- listAdapters() {
77
- return [...this.entries.values()].map((e) => e.adapter);
78
- }
79
- async register(adapter, opts = {}) {
80
- if (this.stopped) {
81
- throw new Error("channel manager already stopped");
82
- }
83
- if (this.entries.has(adapter.id)) {
84
- throw new DuplicateChannelError(adapter.id);
85
- }
86
- const abort = new AbortController();
87
- const inboundListener = (msg) => this.handleInbound(adapter.id, msg);
88
- const healthListener = (sample) => {
89
- const entry2 = this.entries.get(adapter.id);
90
- if (entry2) entry2.lastHealth = sample;
91
- this.healthSink?.(sample);
92
- };
93
- const startPromise = adapter.start({
94
- log: (level, msg) => this.log?.(level, `[${adapter.id}] ${msg}`),
95
- signal: abort.signal,
96
- emitInbound: inboundListener,
97
- emitHealth: healthListener
98
- });
99
- const entry = {
100
- adapter,
101
- abort,
102
- startPromise
103
- };
104
- if (opts.attachmentId !== void 0) entry.attachmentId = opts.attachmentId;
105
- this.entries.set(adapter.id, entry);
106
- try {
107
- await startPromise;
108
- } catch (err) {
109
- this.entries.delete(adapter.id);
110
- throw err;
111
- }
112
- }
113
- async unregister(id, reason) {
114
- const entry = this.entries.get(id);
115
- if (!entry) {
116
- throw new UnknownChannelError(id);
117
- }
118
- this.entries.delete(id);
119
- entry.abort.abort();
120
- await entry.adapter.stop(reason);
121
- }
122
- async send(channelId, msg) {
123
- const entry = this.entries.get(channelId);
124
- if (!entry) {
125
- throw new UnknownChannelError(channelId);
126
- }
127
- return entry.adapter.send(msg);
128
- }
129
- async probe(channelId) {
130
- const entry = this.entries.get(channelId);
131
- if (!entry) {
132
- throw new UnknownChannelError(channelId);
133
- }
134
- return entry.adapter.probe();
135
- }
136
- async stop(reason = "shutdown") {
137
- if (this.stopped) return;
138
- this.stopped = true;
139
- const ids = [...this.entries.keys()];
140
- for (const id of ids.reverse()) {
141
- try {
142
- await this.unregister(id, reason);
143
- } catch (err) {
144
- this.log?.(
145
- "warn",
146
- `channel ${id} stop failed: ${err instanceof Error ? err.message : String(err)}`
147
- );
148
- }
149
- }
150
- }
151
- handleInbound(channelId, msg) {
152
- if (this.dedupSet.has(msg.idempotencyKey)) {
153
- this.log?.("debug", `dropping duplicate inbound ${msg.idempotencyKey}`);
154
- return;
155
- }
156
- this.dedupSet.add(msg.idempotencyKey);
157
- this.dedup.push(msg.idempotencyKey);
158
- while (this.dedup.length > this.dedupMax) {
159
- const evicted = this.dedup.shift();
160
- if (evicted !== void 0) this.dedupSet.delete(evicted);
161
- }
162
- const sink = this.inboundSink;
163
- if (!sink) {
164
- this.log?.(
165
- "debug",
166
- `no inbound sink registered; dropping ${msg.idempotencyKey}`
167
- );
168
- return;
169
- }
170
- try {
171
- sink(msg, { attachmentId: this.entries.get(channelId)?.attachmentId });
172
- } catch (err) {
173
- this.log?.(
174
- "warn",
175
- `inbound sink threw: ${err instanceof Error ? err.message : String(err)}`
176
- );
177
- }
178
- }
179
- };
180
-
181
- // src/infra/config/channels.ts
182
- import fs from "fs";
183
- import os from "os";
184
- import path from "path";
185
- function channelSidecarDir(home = os.homedir()) {
186
- return path.join(home, ".config", "athena", "channels");
187
- }
188
- function loadChannelSidecars(home = os.homedir()) {
189
- const dir = channelSidecarDir(home);
190
- const sidecars = [];
191
- const errors = [];
192
- let entries;
193
- try {
194
- entries = fs.readdirSync(dir);
195
- } catch (err) {
196
- const code = err.code;
197
- if (code === "ENOENT") return { sidecars, errors };
198
- errors.push({
199
- path: dir,
200
- reason: `read dir failed: ${err instanceof Error ? err.message : String(err)}`
201
- });
202
- return { sidecars, errors };
203
- }
204
- for (const entry of entries) {
205
- if (!entry.endsWith(".json")) continue;
206
- const full = path.join(dir, entry);
207
- const name = entry.slice(0, -".json".length);
208
- const result = loadOne(name, full);
209
- if (result.ok) sidecars.push(result.sidecar);
210
- else errors.push({ path: full, reason: result.reason });
211
- }
212
- return { sidecars, errors };
213
- }
214
- function loadOne(name, filePath) {
215
- let raw;
216
- try {
217
- if (process.platform !== "win32") {
218
- const stat = fs.statSync(filePath);
219
- if ((stat.mode & 63) !== 0) {
220
- return {
221
- ok: false,
222
- reason: `file ${filePath} is too permissive (mode ${(stat.mode & 511).toString(8)}); chmod 600`
223
- };
224
- }
225
- }
226
- raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
227
- } catch (err) {
228
- return {
229
- ok: false,
230
- reason: err instanceof Error ? err.message : String(err)
231
- };
232
- }
233
- if (typeof raw !== "object" || raw === null) {
234
- return { ok: false, reason: "config root must be an object" };
235
- }
236
- const obj = raw;
237
- const userIdsRaw = obj["allowed_user_ids"];
238
- const allowedUserIds = [];
239
- if (userIdsRaw !== void 0) {
240
- if (!Array.isArray(userIdsRaw)) {
241
- return { ok: false, reason: "allowed_user_ids must be an array" };
242
- }
243
- for (const id of userIdsRaw) {
244
- if (typeof id === "string") allowedUserIds.push(id);
245
- else if (typeof id === "number") allowedUserIds.push(String(id));
246
- else
247
- return {
248
- ok: false,
249
- reason: "allowed_user_ids entries must be string or number"
250
- };
251
- }
252
- }
253
- const kindRaw = obj["kind"];
254
- if (kindRaw !== void 0 && (typeof kindRaw !== "string" || kindRaw.length === 0)) {
255
- return { ok: false, reason: "kind must be a non-empty string" };
256
- }
257
- const kind = kindRaw ?? name;
258
- const instanceIdRaw = obj["instance_id"];
259
- if (instanceIdRaw !== void 0 && (typeof instanceIdRaw !== "string" || instanceIdRaw.length === 0)) {
260
- return { ok: false, reason: "instance_id must be a non-empty string" };
261
- }
262
- const instanceId = instanceIdRaw ?? kind;
263
- const runnerIdRaw = obj["runner_id"];
264
- let attachmentId;
265
- if (runnerIdRaw !== void 0) {
266
- if (typeof runnerIdRaw !== "string" || runnerIdRaw.length === 0) {
267
- return { ok: false, reason: "runner_id must be a non-empty string" };
268
- }
269
- attachmentId = runnerIdRaw;
270
- }
271
- const options = {};
272
- for (const [key, value] of Object.entries(obj)) {
273
- if (key === "allowed_user_ids" || key === "kind" || key === "instance_id") {
274
- continue;
275
- }
276
- options[key] = value;
277
- }
278
- const sidecar = {
279
- name,
280
- path: filePath,
281
- kind,
282
- instanceId,
283
- allowedUserIds,
284
- options
285
- };
286
- if (attachmentId !== void 0) sidecar.attachmentId = attachmentId;
287
- return { ok: true, sidecar };
288
- }
289
-
290
- // src/gateway/adapters/console/adapter.ts
291
- import { readFileSync as readFileSync2 } from "fs";
292
-
293
- // src/gateway/adapters/console/client.ts
294
- import { readFileSync } from "fs";
295
- import { WebSocket } from "ws";
296
- var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
297
- var DEFAULT_INITIAL_RECONNECT_MS = 1e3;
298
- var DEFAULT_MAX_RECONNECT_MS = 3e4;
299
- var DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
300
- var DEFAULT_HEARTBEAT_TIMEOUT_MS = 9e4;
301
- function createConsoleBrokerClient(opts) {
302
- const hasStatic = typeof opts.pairingToken === "string" && opts.pairingToken.length > 0;
303
- const hasProvider = typeof opts.pairingTokenProvider === "function";
304
- if (hasStatic === hasProvider) {
305
- throw new Error(
306
- "console broker client: exactly one of pairingToken or pairingTokenProvider is required"
307
- );
308
- }
309
- const provider = hasStatic ? async () => opts.pairingToken : opts.pairingTokenProvider;
310
- const initialDelay = opts.reconnect?.initialDelayMs ?? DEFAULT_INITIAL_RECONNECT_MS;
311
- const maxDelay = opts.reconnect?.maxDelayMs ?? DEFAULT_MAX_RECONNECT_MS;
312
- const heartbeatInterval = opts.heartbeat?.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
313
- const heartbeatTimeout = opts.heartbeat?.timeoutMs ?? DEFAULT_HEARTBEAT_TIMEOUT_MS;
314
- let ws = null;
315
- let ready = null;
316
- let closeRequested = false;
317
- let reconnectAttempt = 0;
318
- let reconnectTimer = null;
319
- let lastHello = null;
320
- let currentToken = null;
321
- let heartbeatTimer = null;
322
- let lastPongAt = null;
323
- const frameHandlers = /* @__PURE__ */ new Set();
324
- const closeHandlers = /* @__PURE__ */ new Set();
325
- const readyHandlers = /* @__PURE__ */ new Set();
326
- const tokenRedacted = "<redacted>";
327
- function redact(message) {
328
- if (!currentToken) return message;
329
- return message.split(currentToken).join(tokenRedacted);
330
- }
331
- function stopHeartbeat() {
332
- if (heartbeatTimer) {
333
- clearInterval(heartbeatTimer);
334
- heartbeatTimer = null;
335
- }
336
- lastPongAt = null;
337
- }
338
- function startHeartbeat(currentWs) {
339
- stopHeartbeat();
340
- lastPongAt = Date.now();
341
- heartbeatTimer = setInterval(() => {
342
- if (currentWs !== ws || currentWs.readyState !== WebSocket.OPEN) {
343
- stopHeartbeat();
344
- return;
345
- }
346
- if (lastPongAt !== null && Date.now() - lastPongAt >= heartbeatTimeout) {
347
- opts.log(
348
- "warn",
349
- "console broker: heartbeat watchdog fired, no pong received \u2014 terminating"
350
- );
351
- stopHeartbeat();
352
- try {
353
- currentWs.terminate();
354
- } catch {
355
- }
356
- return;
357
- }
358
- const ping = {
359
- kind: "console.ping",
360
- frameId: makeFrameId(),
361
- sentAt: Date.now()
362
- };
363
- try {
364
- currentWs.send(JSON.stringify(ping));
365
- } catch {
366
- }
367
- }, heartbeatInterval);
368
- }
369
- function emitClose(reason) {
370
- for (const h of [...closeHandlers]) {
371
- try {
372
- h(reason);
373
- } catch {
374
- }
375
- }
376
- }
377
- function scheduleReconnect() {
378
- if (closeRequested || !lastHello) return;
379
- const exp = Math.min(maxDelay, initialDelay * 2 ** reconnectAttempt);
380
- const delay = Math.floor(Math.random() * exp);
381
- reconnectAttempt++;
382
- const hello = lastHello;
383
- reconnectTimer = setTimeout(() => {
384
- reconnectTimer = null;
385
- void attemptConnect(hello).then(
386
- () => {
387
- reconnectAttempt = 0;
388
- },
389
- (err) => {
390
- opts.log(
391
- "warn",
392
- `console broker reconnect failed: ${redact(err instanceof Error ? err.message : String(err))}`
393
- );
394
- scheduleReconnect();
395
- }
396
- );
397
- }, delay);
398
- }
399
- async function attemptConnect(hello) {
400
- const timeoutMs = opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
401
- let token;
402
- try {
403
- token = await provider();
404
- } catch (err) {
405
- throw new Error(
406
- `console broker connect failed: pairing token provider threw: ${err instanceof Error ? err.message : String(err)}`
407
- );
408
- }
409
- if (typeof token !== "string" || token.length === 0) {
410
- throw new Error(
411
- "console broker connect failed: pairing token provider returned empty token"
412
- );
413
- }
414
- currentToken = token;
415
- const headers = { Authorization: `Bearer ${token}` };
416
- const wsOpts = opts.tlsCaPath ? { headers, ca: readFileSync(opts.tlsCaPath) } : { headers };
417
- const next = new WebSocket(opts.brokerUrl, wsOpts);
418
- ws = next;
419
- ready = null;
420
- try {
421
- await new Promise((resolve, reject) => {
422
- let settled = false;
423
- const finishOk = () => {
424
- if (settled) return;
425
- settled = true;
426
- clearTimeout(timer);
427
- resolve();
428
- };
429
- const finishErr = (err) => {
430
- if (settled) return;
431
- settled = true;
432
- clearTimeout(timer);
433
- reject(err);
434
- };
435
- const timer = setTimeout(() => {
436
- finishErr(
437
- new Error(`console broker connect timed out after ${timeoutMs}ms`)
438
- );
439
- }, timeoutMs);
440
- next.once("open", () => {
441
- try {
442
- const helloFrame = {
443
- kind: "console.hello",
444
- frameId: makeFrameId(),
445
- sentAt: Date.now(),
446
- protocolVersion: 1,
447
- clientName: hello.clientName,
448
- clientVersion: hello.clientVersion,
449
- address: {
450
- runnerId: hello.runnerId,
451
- ...hello.workspaceId !== void 0 ? { workspaceId: hello.workspaceId } : {}
452
- }
453
- };
454
- next.send(JSON.stringify(helloFrame));
455
- } catch (err) {
456
- finishErr(err instanceof Error ? err : new Error(String(err)));
457
- }
458
- });
459
- next.once("error", (err) => {
460
- finishErr(
461
- new Error(`console broker connect failed: ${redact(err.message)}`)
462
- );
463
- });
464
- const earlyCloseListener = (code, reasonBuf) => {
465
- if (!ready) {
466
- const reason = reasonBuf.toString();
467
- finishErr(
468
- new Error(
469
- `console broker closed before ready (code=${code}${reason ? ` reason=${reason}` : ""})`
470
- )
471
- );
472
- }
473
- };
474
- next.once("close", earlyCloseListener);
475
- next.on("message", (data) => {
476
- let parsed;
477
- try {
478
- parsed = JSON.parse(String(data));
479
- } catch (err) {
480
- opts.log(
481
- "warn",
482
- `console broker frame parse failed: ${redact(String(err))}`
483
- );
484
- return;
485
- }
486
- if (!ready) {
487
- if (parsed.kind === "console.ready") {
488
- const claimedRunnerId = hello.runnerId;
489
- const readyRunnerId = parsed.address.runnerId;
490
- if (readyRunnerId !== claimedRunnerId) {
491
- finishErr(
492
- new Error(
493
- `console broker ready runnerId mismatch: claimed ${claimedRunnerId}, got ${readyRunnerId}`
494
- )
495
- );
496
- return;
497
- }
498
- ready = parsed;
499
- next.removeListener("close", earlyCloseListener);
500
- const address = parsed.address;
501
- for (const h of [...readyHandlers]) {
502
- try {
503
- h(address);
504
- } catch {
505
- }
506
- }
507
- finishOk();
508
- return;
509
- }
510
- if (parsed.kind === "console.error") {
511
- finishErr(
512
- new Error(
513
- `console broker rejected hello: ${parsed.code} ${parsed.message}`
514
- )
515
- );
516
- return;
517
- }
518
- opts.log(
519
- "warn",
520
- `console broker pre-ready frame ignored: ${parsed.kind}`
521
- );
522
- return;
523
- }
524
- if (parsed.kind === "console.pong") {
525
- lastPongAt = Date.now();
526
- return;
527
- }
528
- for (const h of [...frameHandlers]) {
529
- try {
530
- h(parsed);
531
- } catch (err) {
532
- opts.log(
533
- "warn",
534
- `console frame handler threw: ${redact(err instanceof Error ? err.message : String(err))}`
535
- );
536
- }
537
- }
538
- });
539
- });
540
- } catch (err) {
541
- try {
542
- next.terminate();
543
- } catch {
544
- }
545
- if (ws === next) {
546
- ws = null;
547
- ready = null;
548
- }
549
- throw err;
550
- }
551
- next.on("close", (_code, reasonBuf) => {
552
- stopHeartbeat();
553
- if (next !== ws) return;
554
- ws = null;
555
- ready = null;
556
- emitClose(reasonBuf.toString() || "closed");
557
- if (!closeRequested) scheduleReconnect();
558
- });
559
- startHeartbeat(next);
560
- }
561
- async function connect(hello) {
562
- if (ws) throw new Error("console broker client already connected");
563
- closeRequested = false;
564
- lastHello = hello;
565
- await attemptConnect(hello);
566
- }
567
- function close(reason) {
568
- closeRequested = true;
569
- stopHeartbeat();
570
- if (reconnectTimer) {
571
- clearTimeout(reconnectTimer);
572
- reconnectTimer = null;
573
- }
574
- if (ws) {
575
- try {
576
- ws.close(1e3, reason);
577
- } catch {
578
- ws.terminate();
579
- }
580
- }
581
- ws = null;
582
- ready = null;
583
- emitClose(reason);
584
- }
585
- function sendFrame(frame) {
586
- if (!ws || ws.readyState !== WebSocket.OPEN) {
587
- throw new Error("console broker client not connected");
588
- }
589
- ws.send(JSON.stringify(frame));
590
- }
591
- function onFrame(handler) {
592
- frameHandlers.add(handler);
593
- }
594
- function onClose(handler) {
595
- closeHandlers.add(handler);
596
- }
597
- function onReady(handler) {
598
- readyHandlers.add(handler);
599
- }
600
- return {
601
- connect,
602
- close,
603
- sendFrame,
604
- onFrame,
605
- onReady,
606
- onClose,
607
- getReadyAddress: () => ready?.address ?? null,
608
- isReady: () => ready !== null
609
- };
610
- }
611
- var frameCounter = 0;
612
- function makeFrameId() {
613
- frameCounter = (frameCounter + 1) % 1e6;
614
- return `f${Date.now().toString(36)}-${frameCounter.toString(36)}`;
615
- }
616
-
617
- // src/gateway/adapters/console/adapter.ts
618
- var CONSOLE_DEFAULT_ID = "console";
619
- var CLIENT_NAME = "athena-cli";
620
- var CLIENT_VERSION = "0.0.0";
621
- var ConsoleAdapter = class {
622
- id;
623
- capabilities = {
624
- chat: true,
625
- threads: true,
626
- relayPermission: true,
627
- relayQuestion: true
628
- };
629
- opts;
630
- client = null;
631
- ctx = null;
632
- pendingPermissions = /* @__PURE__ */ new Map();
633
- pendingQuestions = /* @__PURE__ */ new Map();
634
- constructor(opts, id = CONSOLE_DEFAULT_ID) {
635
- this.opts = opts;
636
- this.id = id;
637
- }
638
- async start(ctx) {
639
- if (this.client) {
640
- throw new Error("console adapter already started");
641
- }
642
- this.ctx = ctx;
643
- const tokenSource = resolvePairingTokenSource(this.opts);
644
- const factory = this.opts.brokerClientFactory ?? ((input) => createConsoleBrokerClient(input));
645
- const client = factory({
646
- brokerUrl: this.opts.brokerUrl,
647
- ...tokenSource.kind === "static" ? { pairingToken: tokenSource.token } : { pairingTokenProvider: tokenSource.provider },
648
- ...this.opts.tlsCaPath !== void 0 ? { tlsCaPath: this.opts.tlsCaPath } : {},
649
- log: ctx.log
650
- });
651
- client.onFrame((frame) => this.handleInboundFrame(frame));
652
- client.onReady(() => {
653
- ctx.emitHealth({ at: Date.now(), transportOk: true });
654
- });
655
- client.onClose((reason) => {
656
- this.disposePermissions("connection_lost");
657
- this.disposeQuestions("connection_lost");
658
- ctx.emitHealth({
659
- at: Date.now(),
660
- transportOk: false,
661
- note: `broker connection closed: ${reason}`
662
- });
663
- });
664
- await client.connect({
665
- runnerId: this.opts.runnerId,
666
- ...this.opts.workspaceId !== void 0 ? { workspaceId: this.opts.workspaceId } : {},
667
- clientName: CLIENT_NAME,
668
- clientVersion: CLIENT_VERSION
669
- });
670
- this.client = client;
671
- ctx.signal.addEventListener("abort", () => {
672
- this.client?.close("manager abort");
673
- });
674
- }
675
- async stop(_reason) {
676
- this.disposePermissions();
677
- this.disposeQuestions();
678
- this.client?.close("shutdown");
679
- this.client = null;
680
- this.ctx = null;
681
- }
682
- async send(msg) {
683
- const client = this.client;
684
- if (!client || !client.isReady()) {
685
- throw new Error("console adapter: send called before broker is ready");
686
- }
687
- const messageId = makeOutboundMessageId();
688
- const workspaceId = this.opts.workspaceId ?? msg.location.accountId;
689
- const frame = {
690
- kind: "console.message.out",
691
- frameId: makeFrameId2(),
692
- sentAt: Date.now(),
693
- address: {
694
- runnerId: this.opts.runnerId,
695
- ...workspaceId.length > 0 ? { workspaceId } : {},
696
- ...msg.location.peer?.id !== void 0 ? { userId: msg.location.peer.id } : {},
697
- ...msg.location.thread?.id !== void 0 ? { threadId: msg.location.thread.id } : {}
698
- },
699
- messageId,
700
- idempotencyKey: msg.idempotencyKey,
701
- text: msg.text
702
- };
703
- client.sendFrame(frame);
704
- return {
705
- providerMessageId: messageId,
706
- deliveredAt: Date.now()
707
- };
708
- }
709
- async probe() {
710
- const ok2 = this.client?.isReady() ?? false;
711
- return {
712
- ok: ok2,
713
- detail: ok2 ? "broker connected" : "broker not connected",
714
- checkedAt: Date.now()
715
- };
716
- }
717
- requestPermissionVerdict(req, signal) {
718
- const client = this.client;
719
- if (!client || !client.isReady()) {
720
- return Promise.resolve({ kind: "no_relay" });
721
- }
722
- if (signal.aborted) {
723
- return Promise.resolve({ kind: "cancelled", reason: "auto_resolved" });
724
- }
725
- client.sendFrame({
726
- kind: "console.permission.request",
727
- frameId: makeFrameId2(),
728
- sentAt: Date.now(),
729
- address: {
730
- runnerId: this.opts.runnerId,
731
- ...this.opts.workspaceId !== void 0 ? { workspaceId: this.opts.workspaceId } : {}
732
- },
733
- channelRequestId: req.channelRequestId,
734
- toolName: req.toolName,
735
- description: req.description,
736
- inputPreview: req.inputPreview
737
- });
738
- return new Promise((resolve) => {
739
- const abortListener = () => {
740
- const entry = this.pendingPermissions.get(req.channelRequestId);
741
- if (!entry) return;
742
- this.pendingPermissions.delete(req.channelRequestId);
743
- try {
744
- this.client?.sendFrame({
745
- kind: "console.permission.cancel",
746
- frameId: makeFrameId2(),
747
- sentAt: Date.now(),
748
- channelRequestId: req.channelRequestId,
749
- reason: "resolved_by_other_channel"
750
- });
751
- } catch {
752
- }
753
- resolve({ kind: "cancelled", reason: "resolved_by_other_channel" });
754
- };
755
- signal.addEventListener("abort", abortListener);
756
- this.pendingPermissions.set(req.channelRequestId, {
757
- resolve,
758
- abortListener,
759
- signal
760
- });
761
- });
762
- }
763
- settlePermissionResponse(channelRequestId, decision) {
764
- const entry = this.pendingPermissions.get(channelRequestId);
765
- if (!entry) return;
766
- this.pendingPermissions.delete(channelRequestId);
767
- entry.signal.removeEventListener("abort", entry.abortListener);
768
- entry.resolve({ kind: "verdict", behavior: decision, channelId: this.id });
769
- }
770
- disposePermissions(reason = "auto_resolved") {
771
- for (const [id, entry] of [...this.pendingPermissions.entries()]) {
772
- this.pendingPermissions.delete(id);
773
- entry.signal.removeEventListener("abort", entry.abortListener);
774
- entry.resolve({ kind: "cancelled", reason });
775
- }
776
- }
777
- requestQuestionAnswer(req, signal) {
778
- const client = this.client;
779
- if (!client || !client.isReady()) {
780
- return Promise.resolve({ kind: "no_relay" });
781
- }
782
- if (signal.aborted) {
783
- return Promise.resolve({ kind: "cancelled", reason: "auto_resolved" });
784
- }
785
- client.sendFrame({
786
- kind: "console.question.request",
787
- frameId: makeFrameId2(),
788
- sentAt: Date.now(),
789
- address: {
790
- runnerId: this.opts.runnerId,
791
- ...this.opts.workspaceId !== void 0 ? { workspaceId: this.opts.workspaceId } : {}
792
- },
793
- channelRequestId: req.channelRequestId,
794
- title: req.title,
795
- questions: req.questions
796
- });
797
- return new Promise((resolve) => {
798
- const abortListener = () => {
799
- const entry = this.pendingQuestions.get(req.channelRequestId);
800
- if (!entry) return;
801
- this.pendingQuestions.delete(req.channelRequestId);
802
- try {
803
- this.client?.sendFrame({
804
- kind: "console.question.cancel",
805
- frameId: makeFrameId2(),
806
- sentAt: Date.now(),
807
- channelRequestId: req.channelRequestId,
808
- reason: "resolved_by_other_channel"
809
- });
810
- } catch {
811
- }
812
- resolve({ kind: "cancelled", reason: "resolved_by_other_channel" });
813
- };
814
- signal.addEventListener("abort", abortListener);
815
- this.pendingQuestions.set(req.channelRequestId, {
816
- questionKeys: req.questions.map((q) => q.key),
817
- resolve,
818
- abortListener,
819
- signal
820
- });
821
- });
822
- }
823
- settleQuestionResponse(channelRequestId, answers) {
824
- const entry = this.pendingQuestions.get(channelRequestId);
825
- if (!entry) return;
826
- const filtered = {};
827
- for (const key of entry.questionKeys) {
828
- const value = answers[key];
829
- if (typeof value === "string") filtered[key] = value;
830
- }
831
- this.pendingQuestions.delete(channelRequestId);
832
- entry.signal.removeEventListener("abort", entry.abortListener);
833
- if (Object.keys(filtered).length === 0) {
834
- entry.resolve({ kind: "cancelled", reason: "auto_resolved" });
835
- return;
836
- }
837
- entry.resolve({ kind: "answer", answers: filtered, channelId: this.id });
838
- }
839
- disposeQuestions(reason = "auto_resolved") {
840
- for (const [id, entry] of [...this.pendingQuestions.entries()]) {
841
- this.pendingQuestions.delete(id);
842
- entry.signal.removeEventListener("abort", entry.abortListener);
843
- entry.resolve({ kind: "cancelled", reason });
844
- }
845
- }
846
- handleInboundFrame(frame) {
847
- switch (frame.kind) {
848
- case "console.message.in":
849
- this.handleInboundMessage(frame);
850
- return;
851
- case "console.permission.response":
852
- this.handlePermissionResponse(frame);
853
- return;
854
- case "console.question.response":
855
- this.handleQuestionResponse(frame);
856
- return;
857
- default:
858
- return;
859
- }
860
- }
861
- handleInboundMessage(frame) {
862
- if (frame.kind !== "console.message.in") return;
863
- if (!isValidConsoleAddress(frame.address)) {
864
- this.ctx?.log("warn", "console.message.in dropped: invalid address");
865
- return;
866
- }
867
- if (frame.address.runnerId !== this.opts.runnerId) {
868
- this.ctx?.log(
869
- "warn",
870
- `console.message.in dropped: runner mismatch (claimed ${frame.address.runnerId}, expected ${this.opts.runnerId})`
871
- );
872
- return;
873
- }
874
- if (typeof frame.messageId !== "string" || frame.messageId.length === 0) {
875
- this.ctx?.log("warn", "console.message.in dropped: missing messageId");
876
- return;
877
- }
878
- const inbound = normalizeInbound(frame, this.opts.runnerId, this.id);
879
- if (!inbound || !this.ctx) return;
880
- try {
881
- this.ctx.emitInbound(inbound);
882
- } catch (err) {
883
- this.ctx.log(
884
- "warn",
885
- `console emitInbound threw: ${err instanceof Error ? err.message : String(err)}`
886
- );
887
- }
888
- }
889
- handlePermissionResponse(frame) {
890
- if (frame.kind !== "console.permission.response") return;
891
- if (typeof frame.channelRequestId !== "string" || frame.channelRequestId.length === 0) {
892
- this.ctx?.log(
893
- "warn",
894
- "console.permission.response dropped: missing channelRequestId"
895
- );
896
- return;
897
- }
898
- if (frame.decision !== "allow" && frame.decision !== "deny") {
899
- this.ctx?.log(
900
- "warn",
901
- `console.permission.response dropped: invalid decision ${String(frame.decision)}`
902
- );
903
- return;
904
- }
905
- this.settlePermissionResponse(frame.channelRequestId, frame.decision);
906
- }
907
- handleQuestionResponse(frame) {
908
- if (frame.kind !== "console.question.response") return;
909
- if (typeof frame.channelRequestId !== "string" || frame.channelRequestId.length === 0) {
910
- this.ctx?.log(
911
- "warn",
912
- "console.question.response dropped: missing channelRequestId"
913
- );
914
- return;
915
- }
916
- if (typeof frame.answers !== "object" || frame.answers === null || Array.isArray(frame.answers)) {
917
- this.ctx?.log(
918
- "warn",
919
- "console.question.response dropped: answers must be a record"
920
- );
921
- return;
922
- }
923
- const cleaned = {};
924
- for (const [key, value] of Object.entries(frame.answers)) {
925
- if (typeof key !== "string" || key.length === 0) continue;
926
- if (typeof value !== "string") continue;
927
- cleaned[key] = value;
928
- }
929
- this.settleQuestionResponse(frame.channelRequestId, cleaned);
930
- }
931
- };
932
- function resolvePairingTokenSource(opts) {
933
- if (opts.dashboardConfig === true) {
934
- const provider = opts.pairingTokenProvider ?? (async () => {
935
- const result = await refreshDashboardAccessToken();
936
- return result.accessToken;
937
- });
938
- return { kind: "provider", provider };
939
- }
940
- if (opts.pairingToken !== void 0 && opts.pairingToken.length > 0) {
941
- return { kind: "static", token: opts.pairingToken };
942
- }
943
- if (opts.tokenPath !== void 0 && opts.tokenPath.length > 0) {
944
- try {
945
- const value = readFileSync2(opts.tokenPath, "utf-8").trim();
946
- if (value.length === 0) {
947
- throw new Error(
948
- `console adapter: token_path ${opts.tokenPath} is empty`
949
- );
950
- }
951
- return { kind: "static", token: value };
952
- } catch (err) {
953
- const code = err.code;
954
- throw new Error(
955
- `console adapter: failed to read token_path ${opts.tokenPath}` + (code ? ` (${code})` : "") + (err instanceof Error ? `: ${err.message}` : "")
956
- );
957
- }
958
- }
959
- throw new Error(
960
- "console adapter: no pairing_token, token_path, or dashboard_config configured"
961
- );
962
- }
963
- var outboundCounter = 0;
964
- function makeOutboundMessageId() {
965
- outboundCounter = (outboundCounter + 1) % 1e6;
966
- return `console-out-${Date.now().toString(36)}-${outboundCounter.toString(36)}`;
967
- }
968
- var frameCounter2 = 0;
969
- function makeFrameId2() {
970
- frameCounter2 = (frameCounter2 + 1) % 1e6;
971
- return `f${Date.now().toString(36)}-${frameCounter2.toString(36)}`;
972
- }
973
- function isValidConsoleAddress(value) {
974
- if (typeof value !== "object" || value === null) return false;
975
- const v = value;
976
- if (typeof v["runnerId"] !== "string" || v["runnerId"].length === 0) {
977
- return false;
978
- }
979
- for (const key of [
980
- "workspaceId",
981
- "conversationId",
982
- "threadId",
983
- "userId"
984
- ]) {
985
- if (v[key] !== void 0 && typeof v[key] !== "string") return false;
986
- }
987
- return true;
988
- }
989
- function normalizeInbound(frame, runnerId, channelId) {
990
- if (typeof frame.text !== "string" || frame.text.length === 0) return null;
991
- const userId = frame.address.userId ?? "console-user";
992
- const idempotencyKey = typeof frame.idempotencyKey === "string" && frame.idempotencyKey.length > 0 ? frame.idempotencyKey : `console:${runnerId}:${frame.messageId}`;
993
- return {
994
- location: {
995
- channelId,
996
- accountId: frame.address.workspaceId ?? runnerId,
997
- peer: { id: userId, kind: "user" },
998
- ...frame.address.threadId !== void 0 ? { thread: { id: frame.address.threadId } } : frame.address.conversationId !== void 0 ? { thread: { id: frame.address.conversationId } } : {}
999
- },
1000
- sender: { id: userId },
1001
- text: frame.text,
1002
- receivedAt: frame.sentAt,
1003
- idempotencyKey,
1004
- providerMessageId: frame.messageId
1005
- };
1006
- }
1007
-
1008
- // src/gateway/adapters/console/module.ts
1009
- var consoleModule = {
1010
- name: "console",
1011
- parseConfig({ options }) {
1012
- const brokerUrl = options["broker_url"];
1013
- if (typeof brokerUrl !== "string" || brokerUrl.length === 0) {
1014
- return { ok: false, reason: "broker_url missing" };
1015
- }
1016
- if (!/^wss?:\/\//.test(brokerUrl)) {
1017
- return { ok: false, reason: "broker_url must start with ws:// or wss://" };
1018
- }
1019
- if (brokerUrl.startsWith("ws://") && !isLoopbackUrl(brokerUrl)) {
1020
- return {
1021
- ok: false,
1022
- reason: "broker_url must use wss:// for non-loopback hosts"
1023
- };
1024
- }
1025
- const runnerId = options["runner_id"];
1026
- if (typeof runnerId !== "string" || runnerId.length === 0) {
1027
- return { ok: false, reason: "runner_id missing" };
1028
- }
1029
- const pairingToken = options["pairing_token"];
1030
- const tokenPath = options["token_path"];
1031
- const dashboardConfig = options["dashboard_config"];
1032
- if (dashboardConfig !== void 0 && typeof dashboardConfig !== "boolean") {
1033
- return { ok: false, reason: "dashboard_config must be a boolean" };
1034
- }
1035
- const useDashboardConfig = dashboardConfig === true;
1036
- const hasInline = typeof pairingToken === "string" && pairingToken.length > 0;
1037
- const hasTokenPath = typeof tokenPath === "string" && tokenPath.length > 0;
1038
- if (useDashboardConfig && (hasInline || hasTokenPath)) {
1039
- return {
1040
- ok: false,
1041
- reason: "dashboard_config is mutually exclusive with pairing_token and token_path"
1042
- };
1043
- }
1044
- if (!useDashboardConfig && !hasInline && !hasTokenPath) {
1045
- return {
1046
- ok: false,
1047
- reason: "either pairing_token, token_path, or dashboard_config is required"
1048
- };
1049
- }
1050
- if (pairingToken !== void 0 && typeof pairingToken !== "string") {
1051
- return { ok: false, reason: "pairing_token must be a string" };
1052
- }
1053
- if (tokenPath !== void 0 && typeof tokenPath !== "string") {
1054
- return { ok: false, reason: "token_path must be a string" };
1055
- }
1056
- const workspaceId = options["workspace_id"];
1057
- if (workspaceId !== void 0 && typeof workspaceId !== "string") {
1058
- return { ok: false, reason: "workspace_id must be a string" };
1059
- }
1060
- const tlsCaPath = options["tls_ca_path"];
1061
- if (tlsCaPath !== void 0 && typeof tlsCaPath !== "string") {
1062
- return { ok: false, reason: "tls_ca_path must be a string" };
1063
- }
1064
- const config = {
1065
- brokerUrl,
1066
- runnerId,
1067
- ...workspaceId !== void 0 ? { workspaceId } : {},
1068
- ...useDashboardConfig ? { dashboardConfig: true } : {
1069
- ...pairingToken !== void 0 ? { pairingToken } : {},
1070
- ...tokenPath !== void 0 ? { tokenPath } : {}
1071
- },
1072
- ...tlsCaPath !== void 0 ? { tlsCaPath } : {}
1073
- };
1074
- return { ok: true, config };
1075
- },
1076
- create(config, instanceId) {
1077
- return new ConsoleAdapter(config, instanceId);
1078
- }
1079
- };
1080
- function isLoopbackUrl(url) {
1081
- try {
1082
- const parsed = new URL(url);
1083
- const host = parsed.hostname;
1084
- return host === "localhost" || host === "127.0.0.1" || host === "::1";
1085
- } catch {
1086
- return false;
1087
- }
1088
- }
1089
-
1090
- // src/shared/utils/errorMessage.ts
1091
- function errorMessage(err) {
1092
- return err instanceof Error ? err.message : String(err);
1093
- }
1094
-
1095
- // src/shared/telegram/bot.ts
1096
- var TelegramApiError = class extends Error {
1097
- constructor(status, message, retryAfterMs) {
1098
- super(message);
1099
- this.status = status;
1100
- this.retryAfterMs = retryAfterMs;
1101
- this.name = "TelegramApiError";
1102
- }
1103
- };
1104
- var TelegramBot = class {
1105
- token;
1106
- apiBase;
1107
- pollTimeoutSec;
1108
- offset = 0;
1109
- stopped = false;
1110
- log;
1111
- consecutiveAuthFailures = 0;
1112
- consecutiveErrors = 0;
1113
- constructor(opts, log) {
1114
- this.token = opts.token;
1115
- this.apiBase = opts.apiBase ?? "https://api.telegram.org";
1116
- this.pollTimeoutSec = opts.pollTimeoutSec ?? 25;
1117
- this.log = log;
1118
- }
1119
- /** Strip the bot token from any string before logging or surfacing. */
1120
- redact(text) {
1121
- if (!this.token) return text;
1122
- return text.split(this.token).join("<redacted>");
1123
- }
1124
- stop() {
1125
- this.stopped = true;
1126
- }
1127
- isStopped() {
1128
- return this.stopped;
1129
- }
1130
- /** Current update offset; persist to skip already-seen updates on restart. */
1131
- getOffset() {
1132
- return this.offset;
1133
- }
1134
- setOffset(offset) {
1135
- if (offset > this.offset) this.offset = offset;
1136
- }
1137
- async *poll() {
1138
- while (!this.isStopped()) {
1139
- try {
1140
- const updates = await this.getUpdates();
1141
- this.consecutiveAuthFailures = 0;
1142
- this.consecutiveErrors = 0;
1143
- for (const update of updates) {
1144
- if (this.isStopped()) return;
1145
- if (update.update_id >= this.offset) {
1146
- this.offset = update.update_id + 1;
1147
- }
1148
- yield update;
1149
- }
1150
- } catch (err) {
1151
- const message = this.redact(errorMessage(err));
1152
- const apiErr = err instanceof TelegramApiError ? err : void 0;
1153
- const status = apiErr?.status;
1154
- const retryAfterMs = apiErr?.retryAfterMs;
1155
- if (status === 401 || status === 409) {
1156
- this.consecutiveAuthFailures++;
1157
- this.log(
1158
- "error",
1159
- `getUpdates failed (HTTP ${status}, attempt ${this.consecutiveAuthFailures}): ${message}`
1160
- );
1161
- if (this.consecutiveAuthFailures >= 3) {
1162
- this.stopped = true;
1163
- throw new Error(
1164
- `telegram channel: persistent HTTP ${status} from getUpdates after 3 attempts`
1165
- );
1166
- }
1167
- } else if (status === 429 && retryAfterMs) {
1168
- this.log(
1169
- "warn",
1170
- `getUpdates rate-limited; sleeping ${retryAfterMs}ms`
1171
- );
1172
- await sleep(retryAfterMs);
1173
- continue;
1174
- } else {
1175
- this.consecutiveErrors++;
1176
- this.log("warn", `getUpdates failed: ${message}`);
1177
- }
1178
- const backoffMs = Math.min(
1179
- 1500 * Math.pow(2, Math.max(0, this.consecutiveErrors - 1)),
1180
- 3e4
1181
- );
1182
- await sleep(backoffMs);
1183
- }
1184
- }
1185
- }
1186
- async sendMessage(chatId, text, options = {}) {
1187
- try {
1188
- const params = { chat_id: chatId, text };
1189
- if (options.parse_mode) params["parse_mode"] = options.parse_mode;
1190
- if (options.reply_markup) params["reply_markup"] = options.reply_markup;
1191
- if (options.message_thread_id !== void 0)
1192
- params["message_thread_id"] = options.message_thread_id;
1193
- const result = await this.call("sendMessage", params);
1194
- return result;
1195
- } catch (err) {
1196
- this.log("warn", `sendMessage failed: ${this.redact(errorMessage(err))}`);
1197
- return null;
1198
- }
1199
- }
1200
- async createForumTopic(chatId, name) {
1201
- try {
1202
- return await this.call("createForumTopic", {
1203
- chat_id: chatId,
1204
- name
1205
- });
1206
- } catch (err) {
1207
- this.log(
1208
- "warn",
1209
- `createForumTopic failed: ${this.redact(errorMessage(err))}`
1210
- );
1211
- return null;
1212
- }
1213
- }
1214
- async editForumTopic(chatId, messageThreadId, name) {
1215
- try {
1216
- await this.call("editForumTopic", {
1217
- chat_id: chatId,
1218
- message_thread_id: messageThreadId,
1219
- name
1220
- });
1221
- } catch (err) {
1222
- this.log(
1223
- "debug",
1224
- `editForumTopic failed: ${this.redact(errorMessage(err))}`
1225
- );
1226
- }
1227
- }
1228
- async closeForumTopic(chatId, messageThreadId) {
1229
- try {
1230
- await this.call("closeForumTopic", {
1231
- chat_id: chatId,
1232
- message_thread_id: messageThreadId
1233
- });
1234
- } catch (err) {
1235
- this.log(
1236
- "debug",
1237
- `closeForumTopic failed: ${this.redact(errorMessage(err))}`
1238
- );
1239
- }
1240
- }
1241
- async editMessageText(chatId, messageId, text, options = {}) {
1242
- try {
1243
- const params = {
1244
- chat_id: chatId,
1245
- message_id: messageId,
1246
- text
1247
- };
1248
- if (options.parse_mode) params["parse_mode"] = options.parse_mode;
1249
- if (options.reply_markup) params["reply_markup"] = options.reply_markup;
1250
- await this.call("editMessageText", params);
1251
- } catch (err) {
1252
- this.log(
1253
- "debug",
1254
- `editMessageText failed: ${this.redact(errorMessage(err))}`
1255
- );
1256
- }
1257
- }
1258
- async editMessageReplyMarkup(chatId, messageId, replyMarkup) {
1259
- try {
1260
- await this.call("editMessageReplyMarkup", {
1261
- chat_id: chatId,
1262
- message_id: messageId,
1263
- reply_markup: replyMarkup ?? { inline_keyboard: [] }
1264
- });
1265
- } catch (err) {
1266
- this.log(
1267
- "debug",
1268
- `editMessageReplyMarkup failed: ${this.redact(errorMessage(err))}`
1269
- );
1270
- }
1271
- }
1272
- async answerCallbackQuery(callbackQueryId, text) {
1273
- try {
1274
- const params = {
1275
- callback_query_id: callbackQueryId
1276
- };
1277
- if (text) params["text"] = text;
1278
- await this.call("answerCallbackQuery", params);
1279
- } catch (err) {
1280
- this.log(
1281
- "debug",
1282
- `answerCallbackQuery failed: ${this.redact(errorMessage(err))}`
1283
- );
1284
- }
1285
- }
1286
- async setMyCommands(commands) {
1287
- try {
1288
- await this.call("setMyCommands", { commands });
1289
- } catch (err) {
1290
- this.log(
1291
- "debug",
1292
- `setMyCommands failed: ${this.redact(errorMessage(err))}`
1293
- );
1294
- }
1295
- }
1296
- async getUpdates() {
1297
- const result = await this.call("getUpdates", {
1298
- offset: this.offset,
1299
- timeout: this.pollTimeoutSec,
1300
- allowed_updates: ["message", "callback_query"]
1301
- });
1302
- return result;
1303
- }
1304
- async call(method, params) {
1305
- const url = `${this.apiBase}/bot${this.token}/${method}`;
1306
- const ctrl = new AbortController();
1307
- const timeoutMs = (this.pollTimeoutSec + 5) * 1e3 * 2;
1308
- const timer = setTimeout(() => ctrl.abort(), timeoutMs);
1309
- let res;
1310
- try {
1311
- res = await fetch(url, {
1312
- method: "POST",
1313
- headers: { "Content-Type": "application/json" },
1314
- body: JSON.stringify(params),
1315
- signal: ctrl.signal
1316
- });
1317
- } finally {
1318
- clearTimeout(timer);
1319
- }
1320
- if (!res.ok) {
1321
- let retryAfterSec;
1322
- try {
1323
- const body = await res.json();
1324
- retryAfterSec = body.parameters?.retry_after;
1325
- } catch {
1326
- }
1327
- throw new TelegramApiError(
1328
- res.status,
1329
- `HTTP ${res.status}`,
1330
- typeof retryAfterSec === "number" ? retryAfterSec * 1e3 : void 0
1331
- );
1332
- }
1333
- const json = await res.json();
1334
- if (!json.ok) {
1335
- throw new Error(json.description ?? "telegram api returned ok=false");
1336
- }
1337
- return json.result;
1338
- }
1339
- };
1340
- function sleep(ms) {
1341
- return new Promise((resolve) => setTimeout(resolve, ms));
1342
- }
1343
-
1344
- // src/shared/telegram/markdown.ts
1345
- function escapeMarkdownV2(text) {
1346
- return text.replace(/([_*[\]()~`>#+\-=|{}.!\\])/g, "\\$1");
1347
- }
1348
- function escapeMarkdownV2CodeBlock(text) {
1349
- return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
1350
- }
1351
-
1352
- // src/gateway/adapters/telegram/verdict.ts
1353
- var CB_PERMISSION = "v";
1354
- var CB_QUESTION = "q";
1355
- var CB_ALLOW = "a";
1356
- var CB_DENY = "d";
1357
- var CB_VERDICT = {
1358
- allow: CB_ALLOW,
1359
- deny: CB_DENY
1360
- };
1361
- var ID_PATTERN = CHANNEL_REQUEST_ID_REGEX.source.replace(/^\^|\$$/g, "");
1362
- var VERDICT_RE = new RegExp(`^\\s*(y|yes|n|no)\\s+(${ID_PATTERN})\\s*$`, "i");
1363
- var ANSWER_RE = new RegExp(
1364
- `^\\s*(a|answer)\\s+(${ID_PATTERN})\\s+([\\s\\S]+?)\\s*$`,
1365
- "i"
1366
- );
1367
- var ANSWER_ID_RE = new RegExp(`^\\s*(a|answer)\\s+(${ID_PATTERN})\\s+`, "i");
1368
- var NON_NEG_INT_RE = /^\d+$/;
1369
- var MAX_JSON_ANSWER_BYTES = 8 * 1024;
1370
- function parseVerdict(text) {
1371
- const m = VERDICT_RE.exec(text);
1372
- if (!m) return null;
1373
- const verdictWord = m[1].toLowerCase();
1374
- const id = m[2].toLowerCase();
1375
- return {
1376
- channelRequestId: id,
1377
- behavior: verdictWord.startsWith("y") ? "allow" : "deny"
1378
- };
1379
- }
1380
- function parseQuestionAnswer(text, questionKeys) {
1381
- const m = ANSWER_RE.exec(text);
1382
- if (!m) return null;
1383
- const channelRequestId = m[2].toLowerCase();
1384
- const rawAnswer = m[3].trim();
1385
- if (rawAnswer.length === 0) return null;
1386
- if (rawAnswer.startsWith("{")) {
1387
- if (rawAnswer.length > MAX_JSON_ANSWER_BYTES) return null;
1388
- try {
1389
- const parsed = JSON.parse(rawAnswer);
1390
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1391
- return null;
1392
- }
1393
- const answers = {};
1394
- for (const [key, value] of Object.entries(parsed)) {
1395
- if (typeof value !== "string") return null;
1396
- answers[key] = value;
1397
- }
1398
- return { channelRequestId, answers };
1399
- } catch {
1400
- return null;
1401
- }
1402
- }
1403
- const firstKey = questionKeys[0];
1404
- if (!firstKey) return null;
1405
- return {
1406
- channelRequestId,
1407
- answers: { [firstKey]: rawAnswer }
1408
- };
1409
- }
1410
- function parseQuestionAnswerId(text) {
1411
- const m = ANSWER_ID_RE.exec(text);
1412
- return m ? m[2].toLowerCase() : null;
1413
- }
1414
- function buildPlainTextQuestionAnswer(channelRequestId, text, questionKeys) {
1415
- const answer = text.trim();
1416
- const firstKey = questionKeys[0];
1417
- if (!firstKey || answer.length === 0) return null;
1418
- return {
1419
- channelRequestId,
1420
- answers: { [firstKey]: answer }
1421
- };
1422
- }
1423
- function parseCallbackData(data) {
1424
- const parts = data.split(":");
1425
- const kind = parts[0];
1426
- const id = parts[1];
1427
- if (!id || !isValidChannelRequestId(id)) return null;
1428
- if (kind === CB_PERMISSION && parts.length === 3) {
1429
- const verb = parts[2];
1430
- if (verb !== CB_ALLOW && verb !== CB_DENY) return null;
1431
- return {
1432
- kind: "permission",
1433
- channelRequestId: id,
1434
- behavior: verb === CB_ALLOW ? "allow" : "deny"
1435
- };
1436
- }
1437
- if (kind === CB_QUESTION && parts.length === 3) {
1438
- const idxStr = parts[2];
1439
- if (!NON_NEG_INT_RE.test(idxStr)) return null;
1440
- const optionIndex = Number.parseInt(idxStr, 10);
1441
- return { kind: "question", channelRequestId: id, optionIndex };
1442
- }
1443
- return null;
1444
- }
1445
- function buildPermissionCallbackData(channelRequestId, behavior) {
1446
- return `${CB_PERMISSION}:${channelRequestId}:${CB_VERDICT[behavior]}`;
1447
- }
1448
- function buildQuestionCallbackData(channelRequestId, optionIndex) {
1449
- return `${CB_QUESTION}:${channelRequestId}:${optionIndex}`;
1450
- }
1451
-
1452
- // src/gateway/adapters/telegram/relay.ts
1453
- var MD_OPTIONS = {
1454
- parse_mode: "MarkdownV2"
1455
- };
1456
- var TELEGRAM_MAX_TEXT = 4096;
1457
- var TELEGRAM_TEXT_SAFE_MARGIN = 96;
1458
- var TelegramRelay = class {
1459
- pending = /* @__PURE__ */ new Map();
1460
- resolveTarget;
1461
- log;
1462
- bot = null;
1463
- constructor(opts) {
1464
- this.resolveTarget = opts.resolveTarget;
1465
- this.log = opts.log;
1466
- }
1467
- bindBot(bot) {
1468
- this.bot = bot;
1469
- }
1470
- async requestPermission(req, signal) {
1471
- const bot = this.bot;
1472
- const target = this.resolveTarget();
1473
- if (!bot || !target) {
1474
- return { kind: "no_relay" };
1475
- }
1476
- if (signal.aborted) {
1477
- return { kind: "cancelled", reason: "auto_resolved" };
1478
- }
1479
- const headline = `${req.toolName} \u2014 ${req.description}`;
1480
- const text = buildPromptMarkdown(
1481
- req.toolName,
1482
- req.description,
1483
- req.inputPreview,
1484
- req.channelRequestId
1485
- );
1486
- const reply_markup = buildPermissionKeyboard(req.channelRequestId);
1487
- const sent = await bot.sendMessage(target.chatId, text, {
1488
- ...MD_OPTIONS,
1489
- reply_markup,
1490
- ...target.threadId !== void 0 ? { message_thread_id: target.threadId } : {}
1491
- });
1492
- if (!sent) {
1493
- return { kind: "no_relay" };
1494
- }
1495
- return new Promise((resolve) => {
1496
- const abortListener = () => {
1497
- const entry = this.pending.get(req.channelRequestId);
1498
- if (!entry || entry.kind !== "permission") return;
1499
- this.pending.delete(req.channelRequestId);
1500
- void this.editToCancelled(entry);
1501
- resolve({ kind: "cancelled", reason: "resolved_by_other_channel" });
1502
- };
1503
- signal.addEventListener("abort", abortListener);
1504
- this.pending.set(req.channelRequestId, {
1505
- kind: "permission",
1506
- channelRequestId: req.channelRequestId,
1507
- chatId: sent.chat.id,
1508
- messageId: sent.message_id,
1509
- headline,
1510
- resolve,
1511
- abortListener,
1512
- signal
1513
- });
1514
- });
1515
- }
1516
- async requestQuestion(req, signal) {
1517
- const bot = this.bot;
1518
- const target = this.resolveTarget();
1519
- if (!bot || !target) {
1520
- return { kind: "no_relay" };
1521
- }
1522
- if (signal.aborted) {
1523
- return { kind: "cancelled", reason: "auto_resolved" };
1524
- }
1525
- const headline = req.title.trim() || "Question";
1526
- const keyboard = buildQuestionKeyboard(req.channelRequestId, req.questions);
1527
- const text = buildQuestionMarkdown(
1528
- headline,
1529
- req.questions,
1530
- req.channelRequestId,
1531
- keyboard !== null
1532
- );
1533
- const sent = await bot.sendMessage(target.chatId, text, {
1534
- ...MD_OPTIONS,
1535
- ...keyboard !== null ? { reply_markup: keyboard.markup } : {},
1536
- ...target.threadId !== void 0 ? { message_thread_id: target.threadId } : {}
1537
- });
1538
- if (!sent) {
1539
- return { kind: "no_relay" };
1540
- }
1541
- return new Promise((resolve) => {
1542
- const abortListener = () => {
1543
- const entry = this.pending.get(req.channelRequestId);
1544
- if (!entry || entry.kind !== "question") return;
1545
- this.pending.delete(req.channelRequestId);
1546
- void this.editToCancelled(entry);
1547
- resolve({ kind: "cancelled", reason: "resolved_by_other_channel" });
1548
- };
1549
- signal.addEventListener("abort", abortListener);
1550
- this.pending.set(req.channelRequestId, {
1551
- kind: "question",
1552
- channelRequestId: req.channelRequestId,
1553
- chatId: sent.chat.id,
1554
- messageId: sent.message_id,
1555
- headline,
1556
- questionKeys: req.questions.map((q) => q.key),
1557
- buttonOptions: keyboard?.options ?? null,
1558
- resolve,
1559
- abortListener,
1560
- signal
1561
- });
1562
- });
1563
- }
1564
- /** Returns true if the update was consumed by a relay (verdict/answer). */
1565
- handleUpdate(update) {
1566
- const bot = this.bot;
1567
- if (!bot) return false;
1568
- const cb = update.callback_query;
1569
- if (cb?.data) {
1570
- const parsed = parseCallbackData(cb.data);
1571
- if (!parsed) return false;
1572
- const entry = this.pending.get(parsed.channelRequestId);
1573
- if (!entry) {
1574
- void bot.answerCallbackQuery(cb.id, "request expired");
1575
- return true;
1576
- }
1577
- if (parsed.kind === "permission" && entry.kind === "permission") {
1578
- this.settlePermission(entry, parsed.behavior);
1579
- void bot.answerCallbackQuery(cb.id, parsed.behavior);
1580
- return true;
1581
- }
1582
- if (parsed.kind === "question" && entry.kind === "question") {
1583
- const opt = entry.buttonOptions?.[parsed.optionIndex];
1584
- if (!opt) {
1585
- void bot.answerCallbackQuery(cb.id, "unknown option");
1586
- return true;
1587
- }
1588
- this.settleQuestion(entry, { [opt.key]: opt.label });
1589
- void bot.answerCallbackQuery(cb.id, opt.label);
1590
- return true;
1591
- }
1592
- return false;
1593
- }
1594
- const message = update.message ?? update.edited_message;
1595
- const text = message?.text;
1596
- if (typeof text !== "string" || text.length === 0) return false;
1597
- const verdict = parseVerdict(text);
1598
- if (verdict) {
1599
- const entry = this.pending.get(verdict.channelRequestId);
1600
- if (entry?.kind === "permission") {
1601
- this.settlePermission(entry, verdict.behavior);
1602
- return true;
1603
- }
1604
- return false;
1605
- }
1606
- const answerId = parseQuestionAnswerId(text);
1607
- if (answerId) {
1608
- const entry = this.pending.get(answerId);
1609
- if (entry?.kind === "question") {
1610
- const parsed = parseQuestionAnswer(text, entry.questionKeys);
1611
- if (!parsed) return false;
1612
- this.settleQuestion(entry, parsed.answers);
1613
- return true;
1614
- }
1615
- return false;
1616
- }
1617
- if (message && "reply_to_message" in message && message.reply_to_message) {
1618
- const replyTo = message.reply_to_message.message_id;
1619
- for (const entry of this.pending.values()) {
1620
- if (entry.kind !== "question") continue;
1621
- if (entry.messageId !== replyTo) continue;
1622
- const parsed = buildPlainTextQuestionAnswer(
1623
- entry.channelRequestId,
1624
- text,
1625
- entry.questionKeys
1626
- );
1627
- if (!parsed) return false;
1628
- this.settleQuestion(entry, parsed.answers);
1629
- return true;
1630
- }
1631
- }
1632
- return false;
1633
- }
1634
- disposeAll() {
1635
- for (const entry of [...this.pending.values()]) {
1636
- this.pending.delete(entry.channelRequestId);
1637
- entry.signal.removeEventListener("abort", entry.abortListener);
1638
- if (entry.kind === "permission") {
1639
- entry.resolve({ kind: "cancelled", reason: "auto_resolved" });
1640
- } else {
1641
- entry.resolve({ kind: "cancelled", reason: "auto_resolved" });
1642
- }
1643
- }
1644
- }
1645
- settlePermission(entry, behavior) {
1646
- this.pending.delete(entry.channelRequestId);
1647
- entry.signal.removeEventListener("abort", entry.abortListener);
1648
- void this.editToResolved(
1649
- entry,
1650
- behavior === "allow" ? "Allowed" : "Denied"
1651
- );
1652
- entry.resolve({ kind: "verdict", behavior, channelId: "telegram" });
1653
- }
1654
- settleQuestion(entry, answers) {
1655
- this.pending.delete(entry.channelRequestId);
1656
- entry.signal.removeEventListener("abort", entry.abortListener);
1657
- const summary = Object.values(answers).join(", ").slice(0, 120);
1658
- void this.editToResolved(entry, summary || "Answered");
1659
- entry.resolve({ kind: "answer", answers, channelId: "telegram" });
1660
- }
1661
- async editToResolved(entry, label) {
1662
- const bot = this.bot;
1663
- if (!bot) return;
1664
- try {
1665
- await bot.editMessageText(
1666
- entry.chatId,
1667
- entry.messageId,
1668
- buildResolvedText(entry.headline, label),
1669
- MD_OPTIONS
1670
- );
1671
- } catch (err) {
1672
- this.log(
1673
- "debug",
1674
- `telegram relay: edit-to-resolved failed: ${err instanceof Error ? err.message : String(err)}`
1675
- );
1676
- }
1677
- }
1678
- async editToCancelled(entry) {
1679
- const bot = this.bot;
1680
- if (!bot) return;
1681
- try {
1682
- await bot.editMessageText(
1683
- entry.chatId,
1684
- entry.messageId,
1685
- buildCancelText("resolved elsewhere"),
1686
- MD_OPTIONS
1687
- );
1688
- } catch (err) {
1689
- this.log(
1690
- "debug",
1691
- `telegram relay: edit-to-cancelled failed: ${err instanceof Error ? err.message : String(err)}`
1692
- );
1693
- }
1694
- }
1695
- };
1696
- function clampToTelegramLimit(text) {
1697
- if (text.length <= TELEGRAM_MAX_TEXT) return text;
1698
- return text.slice(0, TELEGRAM_MAX_TEXT - 1) + "\u2026";
1699
- }
1700
- function buildPromptMarkdown(toolName, description, inputPreview, channelRequestId) {
1701
- const trimmedPreview = inputPreview.trim();
1702
- const render = (preview) => {
1703
- const lines = [
1704
- `*${escapeMarkdownV2(toolName)}* \u2014 ${escapeMarkdownV2(description)}`
1705
- ];
1706
- if (preview.length > 0) {
1707
- lines.push("", "```", escapeMarkdownV2CodeBlock(preview), "```");
1708
- }
1709
- lines.push(
1710
- "",
1711
- escapeMarkdownV2(
1712
- `Tap a button below, or reply "yes ${channelRequestId}" / "no ${channelRequestId}".`
1713
- )
1714
- );
1715
- return lines.join("\n");
1716
- };
1717
- const first = render(trimmedPreview);
1718
- const budget = TELEGRAM_MAX_TEXT - TELEGRAM_TEXT_SAFE_MARGIN;
1719
- if (first.length <= budget) return first;
1720
- const overflow = first.length - budget;
1721
- const safePreview = trimmedPreview.length > overflow ? trimmedPreview.slice(0, Math.max(0, trimmedPreview.length - overflow)) + "\u2026" : "";
1722
- return clampToTelegramLimit(render(safePreview));
1723
- }
1724
- function buildPermissionKeyboard(channelRequestId) {
1725
- return {
1726
- inline_keyboard: [
1727
- [
1728
- {
1729
- text: "\u2705 Allow",
1730
- callback_data: buildPermissionCallbackData(channelRequestId, "allow")
1731
- },
1732
- {
1733
- text: "\u274C Deny",
1734
- callback_data: buildPermissionCallbackData(channelRequestId, "deny")
1735
- }
1736
- ]
1737
- ]
1738
- };
1739
- }
1740
- function buildQuestionMarkdown(title, questions, channelRequestId, hasButtons) {
1741
- const lines = [`*${escapeMarkdownV2(title)}*`];
1742
- for (const [index, q] of questions.entries()) {
1743
- lines.push("");
1744
- lines.push(
1745
- `${index + 1}\\. *${escapeMarkdownV2(q.header)}*: ${escapeMarkdownV2(q.question)}`
1746
- );
1747
- if (q.options.length > 0 && !hasButtons) {
1748
- for (const option of q.options) {
1749
- const suffix = option.description ? ` \u2014 ${option.description}` : "";
1750
- lines.push(` \u2022 ${escapeMarkdownV2(option.label + suffix)}`);
1751
- }
1752
- }
1753
- }
1754
- const trailer = hasButtons ? escapeMarkdownV2("Tap an option below.") : questions.length <= 1 ? escapeMarkdownV2(
1755
- `Reply with your answer, or "answer ${channelRequestId} your response".`
1756
- ) : escapeMarkdownV2(
1757
- `Reply 'answer ${channelRequestId} {"Question":"Answer"}' to respond.`
1758
- );
1759
- lines.push("", trailer);
1760
- return clampToTelegramLimit(lines.join("\n"));
1761
- }
1762
- function buildQuestionKeyboard(channelRequestId, questions) {
1763
- if (questions.length !== 1) return null;
1764
- const q = questions[0];
1765
- if (q.multi_select || q.options.length === 0) return null;
1766
- const rows = [];
1767
- const options = [];
1768
- for (const [optIdx, option] of q.options.entries()) {
1769
- const data = buildQuestionCallbackData(channelRequestId, optIdx);
1770
- if (Buffer.byteLength(data, "utf8") > 64) return null;
1771
- rows.push([{ text: option.label, callback_data: data }]);
1772
- options.push({ key: q.key, label: option.label });
1773
- }
1774
- return { markup: { inline_keyboard: rows }, options };
1775
- }
1776
- function buildResolvedText(headline, label) {
1777
- return `*${escapeMarkdownV2(headline)}*
1778
-
1779
- ${escapeMarkdownV2(`\u2713 ${label}`)}`;
1780
- }
1781
- function buildCancelText(reason) {
1782
- return escapeMarkdownV2(`~ resolved (${reason}) ~`);
1783
- }
1784
-
1785
- // src/gateway/adapters/telegram/adapter.ts
1786
- var TELEGRAM_DEFAULT_ID = "telegram";
1787
- var TelegramAdapter = class {
1788
- id;
1789
- capabilities = {
1790
- chat: true,
1791
- threads: true,
1792
- relayPermission: true,
1793
- relayQuestion: true,
1794
- // Telegram caps text at 4096 chars; we leave chunking to the manager.
1795
- maxMessageBytes: 4096
1796
- };
1797
- bot = null;
1798
- opts;
1799
- relay;
1800
- pollTask = null;
1801
- lastInboundAt;
1802
- lastTransportOk = true;
1803
- ctx = null;
1804
- constructor(opts, id = TELEGRAM_DEFAULT_ID) {
1805
- this.opts = opts;
1806
- this.id = id;
1807
- this.relay = new TelegramRelay({
1808
- resolveTarget: () => {
1809
- if (this.opts.defaultChatId === void 0) return null;
1810
- return {
1811
- chatId: this.opts.defaultChatId,
1812
- ...this.opts.defaultThreadId !== void 0 ? { threadId: this.opts.defaultThreadId } : {}
1813
- };
1814
- },
1815
- log: (level, msg) => this.ctx?.log(level, msg)
1816
- });
1817
- }
1818
- requestPermissionVerdict(req, signal) {
1819
- return this.relay.requestPermission(req, signal);
1820
- }
1821
- requestQuestionAnswer(req, signal) {
1822
- return this.relay.requestQuestion(req, signal);
1823
- }
1824
- async start(ctx) {
1825
- if (this.bot) {
1826
- throw new Error("telegram adapter already started");
1827
- }
1828
- this.ctx = ctx;
1829
- const factory = this.opts.botFactory ?? ((o) => new TelegramBot(
1830
- {
1831
- token: o.token,
1832
- apiBase: o.apiBase,
1833
- pollTimeoutSec: o.pollTimeoutSec
1834
- },
1835
- o.log
1836
- ));
1837
- this.bot = factory({
1838
- token: this.opts.token,
1839
- apiBase: this.opts.apiBase,
1840
- pollTimeoutSec: this.opts.pollTimeoutSec,
1841
- log: ctx.log
1842
- });
1843
- this.relay.bindBot(this.bot);
1844
- this.pollTask = this.runPollLoop();
1845
- ctx.signal.addEventListener("abort", () => {
1846
- this.bot?.stop();
1847
- });
1848
- }
1849
- async stop(_reason) {
1850
- this.relay.disposeAll();
1851
- this.bot?.stop();
1852
- const task = this.pollTask;
1853
- this.pollTask = null;
1854
- if (task) {
1855
- try {
1856
- await task;
1857
- } catch {
1858
- }
1859
- }
1860
- this.relay.bindBot(null);
1861
- this.bot = null;
1862
- this.ctx = null;
1863
- }
1864
- async send(msg) {
1865
- const bot = this.bot;
1866
- if (!bot) {
1867
- throw new Error("telegram adapter: send called before start");
1868
- }
1869
- const chatId = msg.location.peer?.id ?? msg.location.room?.id;
1870
- if (!chatId) {
1871
- throw new Error(
1872
- "telegram adapter: outbound location has no peer or room"
1873
- );
1874
- }
1875
- const threadId = msg.location.thread?.id ? Number(msg.location.thread.id) : void 0;
1876
- const result = await bot.sendMessage(chatId, msg.text, {
1877
- ...threadId !== void 0 && Number.isFinite(threadId) ? { message_thread_id: threadId } : {}
1878
- });
1879
- if (!result) {
1880
- throw new Error("telegram adapter: sendMessage returned null");
1881
- }
1882
- return {
1883
- providerMessageId: String(result.message_id),
1884
- deliveredAt: Date.now()
1885
- };
1886
- }
1887
- async probe() {
1888
- return {
1889
- ok: this.lastTransportOk,
1890
- detail: this.lastTransportOk ? "long-poll healthy" : "long-poll erroring",
1891
- checkedAt: Date.now()
1892
- };
1893
- }
1894
- async runPollLoop() {
1895
- const bot = this.bot;
1896
- const ctx = this.ctx;
1897
- if (!bot || !ctx) return;
1898
- const allow = this.opts.allowedUserIds.length === 0 ? null : new Set(this.opts.allowedUserIds.map(String));
1899
- try {
1900
- for await (const update of bot.poll()) {
1901
- if (this.relay.handleUpdate(update)) {
1902
- this.markHealth(true);
1903
- continue;
1904
- }
1905
- const inbound = normalizeInbound2(update, allow, this.id);
1906
- if (!inbound) continue;
1907
- this.lastInboundAt = inbound.receivedAt;
1908
- this.markHealth(true);
1909
- try {
1910
- ctx.emitInbound(inbound);
1911
- } catch (err) {
1912
- ctx.log(
1913
- "warn",
1914
- `telegram emitInbound threw: ${err instanceof Error ? err.message : String(err)}`
1915
- );
1916
- }
1917
- }
1918
- } catch (err) {
1919
- this.markHealth(false, err instanceof Error ? err.message : String(err));
1920
- ctx.log(
1921
- "error",
1922
- `telegram poll loop terminated: ${err instanceof Error ? err.message : String(err)}`
1923
- );
1924
- throw err;
1925
- }
1926
- }
1927
- markHealth(ok2, note) {
1928
- this.lastTransportOk = ok2;
1929
- const ctx = this.ctx;
1930
- if (!ctx) return;
1931
- const sample = {
1932
- at: Date.now(),
1933
- transportOk: ok2,
1934
- ...this.lastInboundAt !== void 0 ? { lastInboundAt: this.lastInboundAt } : {},
1935
- ...note !== void 0 ? { note } : {}
1936
- };
1937
- try {
1938
- ctx.emitHealth(sample);
1939
- } catch {
1940
- }
1941
- }
1942
- };
1943
- function normalizeInbound2(update, allow, channelId) {
1944
- const message = update.message ?? update.edited_message;
1945
- if (!message) return null;
1946
- const text = message.text;
1947
- if (typeof text !== "string" || text.length === 0) return null;
1948
- const sender = message.from;
1949
- if (!sender) return null;
1950
- const senderId = String(sender.id);
1951
- if (allow && !allow.has(senderId)) return null;
1952
- const accountId = String(sender.is_bot ? `bot:${sender.id}` : "user");
1953
- const chatId = String(message.chat.id);
1954
- const isPrivate = message.chat.type === "private";
1955
- const threadId = typeof message.message_thread_id === "number" ? String(message.message_thread_id) : void 0;
1956
- return {
1957
- location: {
1958
- channelId,
1959
- accountId,
1960
- ...isPrivate ? { peer: { id: chatId, kind: "user" } } : {
1961
- room: {
1962
- id: chatId,
1963
- kind: message.chat.type === "channel" ? "channel" : "group"
1964
- }
1965
- },
1966
- ...threadId !== void 0 ? { thread: { id: threadId } } : {}
1967
- },
1968
- sender: {
1969
- id: senderId,
1970
- ...sender.username !== void 0 ? { displayName: sender.username } : sender.first_name !== void 0 ? { displayName: sender.first_name } : {}
1971
- },
1972
- text,
1973
- receivedAt: Date.now(),
1974
- idempotencyKey: `tg:${update.update_id}`,
1975
- providerMessageId: String(message.message_id)
1976
- };
1977
- }
1978
-
1979
- // src/gateway/adapters/telegram/module.ts
1980
- var telegramModule = {
1981
- name: "telegram",
1982
- parseConfig({ options, allowedUserIds }) {
1983
- const token = options["bot_token"];
1984
- if (typeof token !== "string" || token.length === 0) {
1985
- return { ok: false, reason: "bot_token missing" };
1986
- }
1987
- const defaultChatRaw = options["default_chat_id"];
1988
- const defaultThreadRaw = options["default_thread_id"];
1989
- const apiBaseRaw = options["api_base"];
1990
- const pollTimeoutRaw = options["poll_timeout_sec"];
1991
- if (defaultChatRaw !== void 0 && typeof defaultChatRaw !== "string" && typeof defaultChatRaw !== "number") {
1992
- return { ok: false, reason: "default_chat_id must be string or number" };
1993
- }
1994
- if (defaultThreadRaw !== void 0 && typeof defaultThreadRaw !== "number") {
1995
- return { ok: false, reason: "default_thread_id must be number" };
1996
- }
1997
- if (apiBaseRaw !== void 0 && typeof apiBaseRaw !== "string") {
1998
- return { ok: false, reason: "api_base must be string" };
1999
- }
2000
- if (pollTimeoutRaw !== void 0 && typeof pollTimeoutRaw !== "number") {
2001
- return { ok: false, reason: "poll_timeout_sec must be number" };
2002
- }
2003
- const config = {
2004
- token,
2005
- allowedUserIds,
2006
- ...defaultChatRaw !== void 0 ? { defaultChatId: defaultChatRaw } : {},
2007
- ...defaultThreadRaw !== void 0 ? { defaultThreadId: defaultThreadRaw } : {},
2008
- ...apiBaseRaw !== void 0 ? { apiBase: apiBaseRaw } : {},
2009
- ...pollTimeoutRaw !== void 0 ? { pollTimeoutSec: pollTimeoutRaw } : {}
2010
- };
2011
- return { ok: true, config };
2012
- },
2013
- create(config, instanceId) {
2014
- return new TelegramAdapter(config, instanceId);
2015
- }
2016
- };
2017
-
2018
- // src/gateway/adapters/registry.ts
2019
- var BUILTIN_MODULES = [
2020
- telegramModule,
2021
- consoleModule
2022
- ];
2023
- function findAdapterModule(name) {
2024
- return BUILTIN_MODULES.find((m) => m.name === name);
2025
- }
2026
-
2027
- // src/gateway/adapters/factory.ts
2028
- function instantiateAdapter(sidecar) {
2029
- const module = findAdapterModule(sidecar.kind);
2030
- if (!module) {
2031
- return { ok: false, reason: `unknown channel kind: ${sidecar.kind}` };
2032
- }
2033
- const parsed = module.parseConfig({
2034
- options: sidecar.options,
2035
- allowedUserIds: sidecar.allowedUserIds
2036
- });
2037
- if (!parsed.ok) {
2038
- return { ok: false, reason: `${sidecar.instanceId}: ${parsed.reason}` };
2039
- }
2040
- return { ok: true, adapter: module.create(parsed.config, sidecar.instanceId) };
2041
- }
2042
-
2043
- // src/gateway/channelReconcilePlan.ts
2044
- function planChannelReconciliation(input) {
2045
- const actions = [];
2046
- for (const error2 of input.loadErrors) {
2047
- actions.push({
2048
- kind: "load-error",
2049
- id: pathIdFromSidecarPath(error2.path),
2050
- path: error2.path,
2051
- reason: error2.reason
2052
- });
2053
- }
2054
- if (input.unregisterStale) {
2055
- const desiredIds = new Set(
2056
- input.desired.map((sidecar) => sidecar.instanceId)
2057
- );
2058
- for (const id of input.currentChannelIds) {
2059
- if (desiredIds.has(id)) continue;
2060
- actions.push({ kind: "unregister-stale", id });
2061
- }
2062
- }
2063
- const currentIds = new Set(input.currentChannelIds);
2064
- for (const sidecar of input.desired) {
2065
- actions.push(
2066
- currentIds.has(sidecar.instanceId) ? { kind: "replace", sidecar } : { kind: "register", sidecar }
2067
- );
2068
- }
2069
- return { actions };
2070
- }
2071
- function pathIdFromSidecarPath(filePath) {
2072
- const base = filePath.split(/[\\/]/).pop() ?? filePath;
2073
- return base.endsWith(".json") ? base.slice(0, -".json".length) : base;
2074
- }
2075
-
2076
- // src/gateway/channelSidecarReconciler.ts
2077
- var ChannelSidecarReconciler = class {
2078
- channelManager;
2079
- home;
2080
- loadSidecars;
2081
- instantiateAdapter;
2082
- stdout;
2083
- stderr;
2084
- constructor(opts) {
2085
- this.channelManager = opts.channelManager;
2086
- this.home = opts.home;
2087
- this.loadSidecars = opts.loadSidecars ?? loadChannelSidecars;
2088
- this.instantiateAdapter = opts.instantiateAdapter ?? instantiateAdapter;
2089
- this.stdout = opts.stdout ?? ((message) => process.stdout.write(message));
2090
- this.stderr = opts.stderr ?? ((message) => process.stderr.write(message));
2091
- }
2092
- async reconcile(opts) {
2093
- const { sidecars, errors } = this.loadSidecars(this.home);
2094
- const plan = planChannelReconciliation({
2095
- desired: sidecars,
2096
- currentChannelIds: this.channelManager.listChannels().map((channel) => channel.id),
2097
- loadErrors: errors,
2098
- unregisterStale: opts.unregisterStale
2099
- });
2100
- const outcomes = [];
2101
- for (const action of plan.actions) {
2102
- outcomes.push(await this.executeAction(action));
2103
- }
2104
- for (const outcome of outcomes) {
2105
- if (!outcome.log) continue;
2106
- const enabled = outcome.log.stream === "err" ? opts.logFailures : opts.logRegistrations;
2107
- if (!enabled) continue;
2108
- const write = outcome.log.stream === "err" ? this.stderr : this.stdout;
2109
- write(outcome.log.message);
2110
- }
2111
- return { results: outcomes.map((outcome) => outcome.result) };
2112
- }
2113
- async executeAction(action) {
2114
- switch (action.kind) {
2115
- case "load-error":
2116
- return {
2117
- result: {
2118
- id: action.id,
2119
- ok: false,
2120
- action: "failed",
2121
- reason: action.reason
2122
- },
2123
- log: {
2124
- stream: "err",
2125
- message: `athena-gateway: skipping ${action.path}: ${action.reason}
2126
- `
2127
- }
2128
- };
2129
- case "unregister-stale":
2130
- return this.executeUnregisterStale(action.id);
2131
- case "replace":
2132
- return this.executeApply(action.sidecar, true);
2133
- case "register":
2134
- return this.executeApply(action.sidecar, false);
2135
- }
2136
- }
2137
- async executeUnregisterStale(id) {
2138
- try {
2139
- await this.channelManager.unregister(id, "shutdown");
2140
- return { result: { id, ok: true, action: "unregistered" } };
2141
- } catch (err) {
2142
- const reason = errorReason(err);
2143
- return {
2144
- result: { id, ok: false, action: "failed", reason },
2145
- log: {
2146
- stream: "err",
2147
- message: `athena-gateway: unregister ${id} failed: ${reason}
2148
- `
2149
- }
2150
- };
2151
- }
2152
- }
2153
- async executeApply(sidecar, existed) {
2154
- const id = sidecar.instanceId;
2155
- if (existed) {
2156
- try {
2157
- await this.channelManager.unregister(id, "shutdown");
2158
- } catch (err) {
2159
- const reason = errorReason(err);
2160
- return {
2161
- result: { id, ok: false, action: "failed", reason },
2162
- log: {
2163
- stream: "err",
2164
- message: `athena-gateway: unregister ${id} failed: ${reason}
2165
- `
2166
- }
2167
- };
2168
- }
2169
- }
2170
- const built = this.instantiateAdapter(sidecar);
2171
- if (!built.ok) {
2172
- return {
2173
- result: { id, ok: false, action: "failed", reason: built.reason },
2174
- log: {
2175
- stream: "err",
2176
- message: `athena-gateway: ${id}: ${built.reason}
2177
- `
2178
- }
2179
- };
2180
- }
2181
- try {
2182
- await this.channelManager.register(
2183
- built.adapter,
2184
- sidecar.attachmentId !== void 0 ? { attachmentId: sidecar.attachmentId } : {}
2185
- );
2186
- return {
2187
- result: { id, ok: true, action: existed ? "replaced" : "registered" },
2188
- log: {
2189
- stream: "out",
2190
- message: `athena-gateway: registered ${id}
2191
- `
2192
- }
2193
- };
2194
- } catch (err) {
2195
- const reason = errorReason(err);
2196
- return {
2197
- result: { id, ok: false, action: "failed", reason },
2198
- log: {
2199
- stream: "err",
2200
- message: `athena-gateway: register ${id} failed: ${reason}
2201
- `
2202
- }
2203
- };
2204
- }
2205
- }
2206
- };
2207
- function errorReason(err) {
2208
- return err instanceof Error ? err.message : String(err);
2209
- }
2210
-
2211
- // src/gateway/control/handlers.ts
2212
- import { createRequire } from "module";
2213
-
2214
- // src/gateway/runtimeBindingStore.ts
2215
- var AlreadyRegisteredError = class extends Error {
2216
- code = "already_registered";
2217
- constructor(existing) {
2218
- super(
2219
- `gateway already has a registered runtime (pid=${existing.pid}, runtimeId=${existing.runtimeId})`
2220
- );
2221
- this.name = "AlreadyRegisteredError";
2222
- }
2223
- };
2224
- var NotRegisteredError = class extends Error {
2225
- code = "not_registered";
2226
- constructor() {
2227
- super("no runtime registered with gateway");
2228
- this.name = "NotRegisteredError";
2229
- }
2230
- };
2231
- function maybeLastRebindAt(value) {
2232
- return value !== void 0 ? { lastRebindAt: value } : {};
2233
- }
2234
- var RuntimeBindingStore = class {
2235
- slots = /* @__PURE__ */ new Map();
2236
- gracePeriodMs;
2237
- observers;
2238
- now;
2239
- constructor(opts = {}) {
2240
- this.gracePeriodMs = opts.gracePeriodMs ?? 0;
2241
- this.observers = opts.observers ?? {};
2242
- this.now = opts.now ?? Date.now;
2243
- }
2244
- // ── lifecycle ─────────────────────────────────────────────
2245
- /** Register a runtime and bind its connection in one atomic step. */
2246
- bind(input) {
2247
- const key = input.attachmentId;
2248
- const existing = this.slots.get(key);
2249
- const previousBinding = existing?.binding ?? null;
2250
- const wasStale = previousBinding?.state === "stale";
2251
- const staleSince = wasStale ? previousBinding.staleSince : null;
2252
- let runtime;
2253
- if (!existing) {
2254
- runtime = {
2255
- runtimeId: input.runtimeId,
2256
- defaultAgentId: input.defaultAgentId,
2257
- pid: input.pid,
2258
- registeredAt: this.now(),
2259
- ...input.attachmentId !== void 0 ? { attachmentId: input.attachmentId } : {}
2260
- };
2261
- } else if (existing.runtime.runtimeId === input.runtimeId) {
2262
- runtime = {
2263
- ...existing.runtime,
2264
- defaultAgentId: input.defaultAgentId,
2265
- pid: input.pid
2266
- };
2267
- } else {
2268
- throw new AlreadyRegisteredError(existing.runtime);
2269
- }
2270
- const now = this.now();
2271
- const isRebind = previousBinding !== null && (previousBinding.state === "stale" || previousBinding.connectionId !== input.connectionId);
2272
- const lastRebindAt = isRebind ? now : previousBinding?.lastRebindAt;
2273
- const epoch = previousBinding ? previousBinding.epoch + (isRebind ? 1 : 0) : 1;
2274
- const newBinding = {
2275
- state: "active",
2276
- connectionId: input.connectionId,
2277
- boundAt: now,
2278
- epoch,
2279
- ...maybeLastRebindAt(lastRebindAt)
2280
- };
2281
- const push = input.push ?? existing?.push ?? null;
2282
- const slot = existing ? { ...existing, runtime, binding: newBinding, push } : {
2283
- runtime,
2284
- binding: newBinding,
2285
- push,
2286
- staleTimer: null,
2287
- staleSince: null
2288
- };
2289
- this.clearStaleTimerForSlot(slot);
2290
- this.slots.set(key, slot);
2291
- if (wasStale && staleSince !== null) {
2292
- this.observers.onRuntimeRebind?.({
2293
- runtimeId: input.runtimeId,
2294
- gapMs: now - staleSince,
2295
- epoch: newBinding.epoch
2296
- });
2297
- }
2298
- return { registeredAt: runtime.registeredAt };
2299
- }
2300
- /** Fully unregister a runtime. Throws NotRegisteredError if id does not match. */
2301
- unbind(runtimeId) {
2302
- const entry = this.findSlotByRuntimeId(runtimeId);
2303
- if (!entry) {
2304
- throw new NotRegisteredError();
2305
- }
2306
- this.clearStaleTimerForSlot(entry.slot);
2307
- this.slots.delete(entry.key);
2308
- this.observers.onRuntimeConnectionLost?.({ runtimeId, graceful: true });
2309
- }
2310
- /**
2311
- * Called when the transport connection closes. Drops the slot's push handle
2312
- * (immediately deleting the slot when no grace period is configured, otherwise
2313
- * marking it stale). Returns the runtimeId if the close matched a current
2314
- * binding; returns null if the connectionId was not recognised.
2315
- */
2316
- notifyConnectionClosed(connectionId) {
2317
- const entry = this.findSlotByConnectionId(connectionId);
2318
- if (!entry) return null;
2319
- const { key, slot } = entry;
2320
- const runtimeId = slot.runtime.runtimeId;
2321
- const now = this.now();
2322
- const previousBinding = slot.binding;
2323
- slot.binding = {
2324
- state: "stale",
2325
- connectionId,
2326
- staleSince: now,
2327
- epoch: previousBinding.epoch,
2328
- ...maybeLastRebindAt(previousBinding.lastRebindAt)
2329
- };
2330
- if (this.gracePeriodMs <= 0) {
2331
- this.slots.delete(key);
2332
- this.observers.onRuntimeConnectionLost?.({ runtimeId, graceful: false });
2333
- return runtimeId;
2334
- }
2335
- slot.push = null;
2336
- slot.staleSince = now;
2337
- slot.staleTimer = setTimeout(() => {
2338
- this.expireStaleBinding(key, runtimeId);
2339
- }, this.gracePeriodMs);
2340
- return runtimeId;
2341
- }
2342
- stop() {
2343
- for (const slot of this.slots.values()) {
2344
- this.clearStaleTimerForSlot(slot);
2345
- }
2346
- }
2347
- // ── reads ─────────────────────────────────────────────────
2348
- hasActiveBinding(runtimeId) {
2349
- const slot = this.slots.get(void 0);
2350
- if (!slot || !slot.binding || slot.binding.state !== "active") return false;
2351
- return runtimeId === void 0 || slot.runtime.runtimeId === runtimeId;
2352
- }
2353
- hasActiveBindingForAttachment(key) {
2354
- const slot = this.slots.get(key);
2355
- return !!slot && !!slot.binding && slot.binding.state === "active";
2356
- }
2357
- getCurrent() {
2358
- return this.slots.get(void 0)?.runtime ?? null;
2359
- }
2360
- getCurrentByAttachment(attachmentId) {
2361
- return this.slots.get(attachmentId)?.runtime ?? null;
2362
- }
2363
- getBinding() {
2364
- return this.slots.get(void 0)?.binding ?? null;
2365
- }
2366
- getRuntimeIdByConnection(connectionId) {
2367
- const entry = this.findSlotByConnectionId(connectionId);
2368
- return entry ? entry.slot.runtime.runtimeId : null;
2369
- }
2370
- /**
2371
- * Deliver a control-push envelope to the runtime occupying `key`. Returns
2372
- * false (and pushes nothing) when the slot is empty or its connection has
2373
- * already been lost.
2374
- */
2375
- pushTo(key, env) {
2376
- const slot = this.slots.get(key);
2377
- if (!slot || !slot.push) return false;
2378
- slot.push(env);
2379
- return true;
2380
- }
2381
- /**
2382
- * Reportable state for every slot — both attachment-keyed and the legacy
2383
- * fallback — so status reporting sees all registered runtimes.
2384
- */
2385
- snapshot() {
2386
- const entries = [];
2387
- for (const [key, slot] of this.slots) {
2388
- entries.push({ key, runtime: slot.runtime, binding: slot.binding });
2389
- }
2390
- return entries;
2391
- }
2392
- /**
2393
- * Returns the attachment slot key (or `undefined` for the legacy slot) that
2394
- * holds the given runtime, or `null` if no slot does. Lets callers
2395
- * route per-attachment side-state (like push handles) keyed the same way
2396
- * as the binding map.
2397
- */
2398
- getAttachmentKeyByRuntimeId(runtimeId) {
2399
- const entry = this.findSlotByRuntimeId(runtimeId);
2400
- return entry ? { key: entry.key, runtime: entry.slot.runtime } : null;
2401
- }
2402
- // ── private ───────────────────────────────────────────────
2403
- expireStaleBinding(key, runtimeId) {
2404
- const slot = this.slots.get(key);
2405
- if (!slot) return;
2406
- slot.staleTimer = null;
2407
- const since = slot.staleSince;
2408
- slot.staleSince = null;
2409
- if (slot.runtime.runtimeId !== runtimeId) return;
2410
- if (slot.binding?.state === "active") return;
2411
- this.slots.delete(key);
2412
- this.observers.onRuntimeConnectionLost?.({ runtimeId, graceful: false });
2413
- if (since !== null) {
2414
- this.observers.onRuntimeExpired?.({ runtimeId, gapMs: this.now() - since });
2415
- }
2416
- }
2417
- clearStaleTimerForSlot(slot) {
2418
- if (slot.staleTimer) {
2419
- clearTimeout(slot.staleTimer);
2420
- slot.staleTimer = null;
2421
- }
2422
- slot.staleSince = null;
2423
- }
2424
- findSlotByRuntimeId(runtimeId) {
2425
- for (const [key, slot] of this.slots) {
2426
- if (slot.runtime.runtimeId === runtimeId) return { key, slot };
2427
- }
2428
- return null;
2429
- }
2430
- findSlotByConnectionId(connectionId) {
2431
- for (const [key, slot] of this.slots) {
2432
- if (slot.binding?.connectionId === connectionId) return { key, slot };
2433
- }
2434
- return null;
2435
- }
2436
- };
2437
-
2438
- // src/gateway/control/handlers.ts
2439
- var require_ = createRequire(import.meta.url);
2440
- var cachedVersion = null;
2441
- function readVersion() {
2442
- if (cachedVersion !== null) return cachedVersion;
2443
- try {
2444
- const injected = "0.5.28";
2445
- if (typeof injected === "string" && injected.length > 0) {
2446
- cachedVersion = injected;
2447
- return cachedVersion;
2448
- }
2449
- } catch {
2450
- }
2451
- try {
2452
- const pkg = require_("../../../package.json");
2453
- cachedVersion = pkg.version ?? "0.0.0";
2454
- } catch {
2455
- cachedVersion = "0.0.0";
2456
- }
2457
- return cachedVersion;
2458
- }
2459
- var PING = {
2460
- kind: "ping",
2461
- handle: (_envelope, { ts, deps }) => {
2462
- const payload = {
2463
- pong: true,
2464
- daemonPid: process.pid,
2465
- uptimeMs: ts - deps.startedAt
2466
- };
2467
- return payload;
2468
- }
2469
- };
2470
- var STATUS = {
2471
- kind: "status",
2472
- handle: (_envelope, { ts, deps }) => {
2473
- const channels = (deps.channelManager?.listChannels() ?? []).map((c) => ({
2474
- id: c.id,
2475
- state: c.health?.transportOk === false ? "degraded" : "running",
2476
- ...c.health?.at !== void 0 ? { lastHealthAt: c.health.at } : {},
2477
- ...c.health?.note !== void 0 ? { note: c.health.note } : {}
2478
- }));
2479
- const payload = {
2480
- daemonPid: process.pid,
2481
- startedAt: deps.startedAt,
2482
- uptimeMs: ts - deps.startedAt,
2483
- version: readVersion(),
2484
- listener: deps.getListener?.() ?? {
2485
- kind: "uds",
2486
- socketPath: "<unknown>"
2487
- },
2488
- channels,
2489
- runtimes: runtimeStatusEntries(deps.pipeline)
2490
- };
2491
- return payload;
2492
- }
2493
- };
2494
- var CHANNELS_RELOAD = {
2495
- kind: "channels.reload",
2496
- requires: ["reloadChannels"],
2497
- unsupportedMessage: "channel reload not configured",
2498
- handle: async (_envelope, { deps }) => {
2499
- const payload = await deps.reloadChannels();
2500
- return payload;
2501
- }
2502
- };
2503
- var SESSION_REGISTER = {
2504
- kind: "session.register",
2505
- requires: ["pipeline"],
2506
- unsupportedMessage: "session.register not configured",
2507
- handle: (envelope, { deps, connection }) => {
2508
- const req = envelope.payload;
2509
- const reg = deps.pipeline.registerRuntime({
2510
- runtimeId: req.runtimeId,
2511
- defaultAgentId: req.defaultAgentId,
2512
- pid: req.pid,
2513
- connectionId: connection.connectionId,
2514
- push: connection.push,
2515
- ...req.attachmentId !== void 0 ? { attachmentId: req.attachmentId } : {}
2516
- });
2517
- const payload = {
2518
- registeredAt: reg.registeredAt,
2519
- gatewayStartedAt: deps.startedAt
2520
- };
2521
- return payload;
2522
- }
2523
- };
2524
- var SESSION_UNREGISTER = {
2525
- kind: "session.unregister",
2526
- requires: ["pipeline"],
2527
- unsupportedMessage: "session.unregister not configured",
2528
- handle: (envelope, { deps, ts }) => {
2529
- const req = envelope.payload;
2530
- deps.pipeline.unregisterRuntime(req.runtimeId);
2531
- const payload = {
2532
- unregisteredAt: ts
2533
- };
2534
- return payload;
2535
- }
2536
- };
2537
- var SESSION_TURN_COMPLETE = {
2538
- kind: "session.turn.complete",
2539
- requires: ["pipeline"],
2540
- unsupportedMessage: "pipeline not configured",
2541
- handle: async (envelope, { deps }) => {
2542
- const req = envelope.payload;
2543
- return await deps.pipeline.handleTurnComplete(req);
2544
- }
2545
- };
2546
- var SESSION_RUN_EVENT = {
2547
- kind: "session.run.event",
2548
- requires: ["pipeline"],
2549
- unsupportedMessage: "pipeline not configured",
2550
- handle: async (envelope, { deps }) => {
2551
- const req = envelope.payload;
2552
- return await deps.pipeline.handleRunEvent(req);
2553
- }
2554
- };
2555
- var CHANNEL_SEND = {
2556
- kind: "channel.send",
2557
- requires: ["channelManager"],
2558
- unsupportedMessage: "channel manager not configured",
2559
- handle: async (envelope, { deps }) => {
2560
- const req = envelope.payload;
2561
- const result = await deps.channelManager.send(
2562
- req.message.location.channelId,
2563
- req.message
2564
- );
2565
- const payload = {
2566
- providerMessageId: result.providerMessageId,
2567
- deliveredAt: result.deliveredAt
2568
- };
2569
- return payload;
2570
- }
2571
- };
2572
- var RELAY_PERMISSION_REQUEST = {
2573
- kind: "relay.permission.request",
2574
- requires: ["relayCoordinator"],
2575
- unsupportedMessage: "relay coordinator not configured",
2576
- requireRegisteredRuntime: true,
2577
- handle: async (envelope, { deps, callerRuntimeId }) => {
2578
- const req = envelope.payload;
2579
- const broadcast = deps.relayCoordinator.requestPermission({
2580
- ...req.channelRequestId !== void 0 ? { channelRequestId: req.channelRequestId } : {},
2581
- toolName: req.toolName,
2582
- description: req.description,
2583
- inputPreview: req.inputPreview,
2584
- ...req.ttlMs !== void 0 ? { ttlMs: req.ttlMs } : {},
2585
- ...callerRuntimeId !== void 0 ? { runtimeId: callerRuntimeId } : {}
2586
- });
2587
- const result = await broadcast.result;
2588
- const payload = {
2589
- channelRequestId: broadcast.channelRequestId,
2590
- result
2591
- };
2592
- return payload;
2593
- }
2594
- };
2595
- var RELAY_PERMISSION_CANCEL = {
2596
- kind: "relay.permission.cancel",
2597
- requires: ["relayCoordinator"],
2598
- unsupportedMessage: "relay coordinator not configured",
2599
- requireRegisteredRuntime: true,
2600
- handle: (envelope, { deps, callerRuntimeId }) => {
2601
- const req = envelope.payload;
2602
- const cancelled = deps.relayCoordinator.cancel(
2603
- req.channelRequestId,
2604
- req.reason,
2605
- callerRuntimeId
2606
- );
2607
- const payload = { cancelled };
2608
- return payload;
2609
- }
2610
- };
2611
- var RELAY_QUESTION_REQUEST = {
2612
- kind: "relay.question.request",
2613
- requires: ["relayCoordinator"],
2614
- unsupportedMessage: "relay coordinator not configured",
2615
- requireRegisteredRuntime: true,
2616
- handle: async (envelope, { deps, callerRuntimeId }) => {
2617
- const req = envelope.payload;
2618
- const broadcast = deps.relayCoordinator.requestQuestion({
2619
- ...req.channelRequestId !== void 0 ? { channelRequestId: req.channelRequestId } : {},
2620
- title: req.title,
2621
- questions: req.questions,
2622
- ...req.ttlMs !== void 0 ? { ttlMs: req.ttlMs } : {},
2623
- ...callerRuntimeId !== void 0 ? { runtimeId: callerRuntimeId } : {}
2624
- });
2625
- const result = await broadcast.result;
2626
- const payload = {
2627
- channelRequestId: broadcast.channelRequestId,
2628
- result
2629
- };
2630
- return payload;
2631
- }
2632
- };
2633
- var RELAY_QUESTION_CANCEL = {
2634
- kind: "relay.question.cancel",
2635
- requires: ["relayCoordinator"],
2636
- unsupportedMessage: "relay coordinator not configured",
2637
- requireRegisteredRuntime: true,
2638
- handle: (envelope, { deps, callerRuntimeId }) => {
2639
- const req = envelope.payload;
2640
- const cancelled = deps.relayCoordinator.cancel(
2641
- req.channelRequestId,
2642
- req.reason,
2643
- callerRuntimeId
2644
- );
2645
- const payload = { cancelled };
2646
- return payload;
2647
- }
2648
- };
2649
- var HANDLERS = new Map(
2650
- [
2651
- PING,
2652
- STATUS,
2653
- CHANNELS_RELOAD,
2654
- SESSION_REGISTER,
2655
- SESSION_UNREGISTER,
2656
- SESSION_TURN_COMPLETE,
2657
- SESSION_RUN_EVENT,
2658
- CHANNEL_SEND,
2659
- RELAY_PERMISSION_REQUEST,
2660
- RELAY_PERMISSION_CANCEL,
2661
- RELAY_QUESTION_REQUEST,
2662
- RELAY_QUESTION_CANCEL
2663
- ].map((spec) => [spec.kind, spec])
2664
- );
2665
- function createDispatcher(deps) {
2666
- const handle = async (envelope, connection) => {
2667
- const ts = Date.now();
2668
- const spec = HANDLERS.get(envelope.kind);
2669
- if (!spec) {
2670
- return error(
2671
- envelope,
2672
- ts,
2673
- "unknown_kind",
2674
- `unknown kind: ${envelope.kind}`
2675
- );
2676
- }
2677
- if (spec.requires) {
2678
- for (const name of spec.requires) {
2679
- if (deps[name] === void 0) {
2680
- return error(
2681
- envelope,
2682
- ts,
2683
- "unsupported",
2684
- spec.unsupportedMessage ?? `${spec.kind} not configured`
2685
- );
2686
- }
2687
- }
2688
- }
2689
- let callerRuntimeId;
2690
- if (spec.requireRegisteredRuntime) {
2691
- callerRuntimeId = deps.pipeline?.getRuntimeIdByConnection(connection.connectionId) ?? void 0;
2692
- if (deps.pipeline && callerRuntimeId === void 0) {
2693
- return error(
2694
- envelope,
2695
- ts,
2696
- "not_registered",
2697
- `${spec.kind} requires a registered runtime connection`
2698
- );
2699
- }
2700
- }
2701
- try {
2702
- const payload = await spec.handle(envelope, {
2703
- deps,
2704
- connection,
2705
- callerRuntimeId,
2706
- ts
2707
- });
2708
- return ok(envelope, Date.now(), payload);
2709
- } catch (err) {
2710
- if (err instanceof AlreadyRegisteredError || err instanceof NotRegisteredError) {
2711
- return error(envelope, ts, err.code, err.message);
2712
- }
2713
- throw err;
2714
- }
2715
- };
2716
- return handle;
2717
- }
2718
- function runtimeStatusEntries(pipeline) {
2719
- if (!pipeline) return [];
2720
- return pipeline.snapshotRuntimes().map(({ runtime, binding }) => ({
2721
- runtimeId: runtime.runtimeId,
2722
- defaultAgentId: runtime.defaultAgentId,
2723
- pid: runtime.pid,
2724
- registeredAt: runtime.registeredAt,
2725
- binding: binding?.state === "active" ? {
2726
- state: "active",
2727
- boundAt: binding.boundAt,
2728
- epoch: binding.epoch,
2729
- ...maybeLastRebindAt(binding.lastRebindAt)
2730
- } : binding?.state === "stale" ? {
2731
- state: "stale",
2732
- staleSince: binding.staleSince,
2733
- epoch: binding.epoch,
2734
- ...maybeLastRebindAt(binding.lastRebindAt)
2735
- } : { state: "none" },
2736
- pendingDispatchCount: pipeline.pendingDispatchCountFor(runtime.runtimeId)
2737
- }));
2738
- }
2739
- function ok(envelope, ts, payload) {
2740
- return { request_id: envelope.request_id, ts, ok: true, payload };
2741
- }
2742
- function error(envelope, ts, code, message) {
2743
- return {
2744
- request_id: envelope.request_id,
2745
- ts,
2746
- ok: false,
2747
- error: { code, message }
2748
- };
2749
- }
2750
-
2751
- // src/gateway/control/server.ts
2752
- var CONNECT_TIMEOUT_MS = 2e3;
2753
- function isStringRecord(v) {
2754
- return typeof v === "object" && v !== null && !Array.isArray(v);
2755
- }
2756
- function nowError(requestId, code, message) {
2757
- return {
2758
- request_id: requestId,
2759
- ts: Date.now(),
2760
- ok: false,
2761
- error: { code, message }
2762
- };
2763
- }
2764
- var connectionCounter = 0;
2765
- function nextConnectionId() {
2766
- connectionCounter = connectionCounter + 1 >>> 0;
2767
- return `c${connectionCounter}-${process.pid}`;
2768
- }
2769
- async function startControlServer(opts) {
2770
- const { socketPath, token, startedAt, handler } = opts;
2771
- const logError = opts.logError ?? ((m) => process.stderr.write(m + "\n"));
2772
- const transport = opts.transport ?? createUdsServerTransport({
2773
- socketPath,
2774
- logError
2775
- });
2776
- const listener = await transport.listen((connection) => {
2777
- handleConnection(
2778
- connection,
2779
- token,
2780
- startedAt,
2781
- handler,
2782
- logError,
2783
- opts.onConnect,
2784
- opts.onDisconnect
2785
- );
2786
- });
2787
- return {
2788
- close: () => listener.close()
2789
- };
2790
- }
2791
- function handleConnection(connection, expectedToken, startedAt, handler, logError, onConnect, onDisconnect) {
2792
- let authed = false;
2793
- const connectTimer = setTimeout(() => {
2794
- connection.close();
2795
- }, CONNECT_TIMEOUT_MS);
2796
- const ctx = {
2797
- connectionId: nextConnectionId(),
2798
- push: (env) => connection.send(env),
2799
- disconnect: () => connection.close()
2800
- };
2801
- connection.onFrame((parsed) => {
2802
- if (!isStringRecord(parsed)) {
2803
- connection.close();
2804
- return;
2805
- }
2806
- if (!authed) {
2807
- if (parsed["kind"] !== "connect") {
2808
- connection.close();
2809
- return;
2810
- }
2811
- const tok = parsed["token"];
2812
- if (typeof tok !== "string" || !timingSafeTokenEqual(tok, expectedToken)) {
2813
- connection.send({
2814
- ok: false,
2815
- error: { code: "unauthorized", message: "invalid token" }
2816
- });
2817
- connection.close();
2818
- return;
2819
- }
2820
- authed = true;
2821
- clearTimeout(connectTimer);
2822
- connection.send({
2823
- ok: true,
2824
- hello: { daemonPid: process.pid, startedAt }
2825
- });
2826
- onConnect?.(ctx);
2827
- return;
2828
- }
2829
- const requestId = typeof parsed["request_id"] === "string" ? parsed["request_id"] : "";
2830
- if (typeof parsed["kind"] !== "string" || typeof parsed["ts"] !== "number" || !("payload" in parsed) || requestId.length === 0) {
2831
- connection.send(nowError(requestId, "bad_request", "malformed envelope"));
2832
- return;
2833
- }
2834
- void Promise.resolve().then(() => handler(parsed, ctx)).then((res) => connection.send(res)).catch(
2835
- (err) => connection.send(
2836
- nowError(
2837
- requestId,
2838
- "handler_error",
2839
- err instanceof Error ? err.message : String(err)
2840
- )
2841
- )
2842
- );
2843
- });
2844
- connection.onError((err) => {
2845
- const code = err.code;
2846
- if (code !== "EPIPE" && code !== "ECONNRESET") {
2847
- logError(`gateway: socket error: ${err.message}`);
2848
- }
2849
- });
2850
- connection.onClose(() => {
2851
- clearTimeout(connectTimer);
2852
- if (authed) {
2853
- onDisconnect?.(ctx);
2854
- }
2855
- });
2856
- }
2857
-
2858
- // src/gateway/dispatchPipeline.ts
2859
- import crypto from "crypto";
2860
-
2861
- // src/gateway/outboundDispatcher.ts
2862
- var DEFAULT_BACKOFF = [
2863
- 1e3,
2864
- // 1s
2865
- 2e3,
2866
- // 2s
2867
- 4e3,
2868
- // 4s
2869
- 8e3,
2870
- // 8s
2871
- 16e3,
2872
- // 16s
2873
- 3e4
2874
- // 30s
2875
- ];
2876
- var DEFAULT_MAX_ATTEMPTS = 10;
2877
- var DEFAULT_TICK_MS = 1e3;
2878
- var DEFAULT_BATCH = 16;
2879
- var OutboundDispatcher = class {
2880
- outbox;
2881
- send;
2882
- backoff;
2883
- maxAttempts;
2884
- tickMs;
2885
- batchSize;
2886
- now;
2887
- log;
2888
- timer = null;
2889
- draining = false;
2890
- stopped = false;
2891
- constructor(opts) {
2892
- this.outbox = opts.outbox;
2893
- this.send = opts.send;
2894
- this.backoff = opts.backoffSchedule ?? DEFAULT_BACKOFF;
2895
- this.maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
2896
- this.tickMs = opts.tickIntervalMs ?? DEFAULT_TICK_MS;
2897
- this.batchSize = opts.drainBatchSize ?? DEFAULT_BATCH;
2898
- this.now = opts.now ?? Date.now;
2899
- this.log = opts.log;
2900
- }
2901
- start() {
2902
- if (this.timer) return;
2903
- this.timer = setInterval(() => {
2904
- void this.drain();
2905
- }, this.tickMs);
2906
- this.timer.unref();
2907
- }
2908
- stop() {
2909
- this.stopped = true;
2910
- if (this.timer) {
2911
- clearInterval(this.timer);
2912
- this.timer = null;
2913
- }
2914
- }
2915
- async dispatch(channelId, msg) {
2916
- try {
2917
- const result = await this.send(channelId, msg);
2918
- return { kind: "sent", result };
2919
- } catch (err) {
2920
- const error2 = err instanceof Error ? err.message : String(err);
2921
- const nextAttemptAt = this.now() + this.backoffFor(0);
2922
- const id = this.outbox.enqueue({
2923
- channelId,
2924
- message: msg,
2925
- nextAttemptAt,
2926
- lastError: error2
2927
- });
2928
- this.log?.(
2929
- "warn",
2930
- `send to ${channelId} failed; parked as outbox#${id}: ${error2}`
2931
- );
2932
- return { kind: "queued", outboxId: id, error: error2 };
2933
- }
2934
- }
2935
- /**
2936
- * Drain due entries. Exposed for tests; the timer also calls this. Safe
2937
- * to call concurrently — a re-entry guard short-circuits.
2938
- */
2939
- async drain() {
2940
- if (this.draining || this.stopped) {
2941
- return { retried: 0, succeeded: 0, dropped: 0 };
2942
- }
2943
- this.draining = true;
2944
- let retried = 0;
2945
- let succeeded = 0;
2946
- let dropped = 0;
2947
- try {
2948
- const due = this.outbox.peekDue(this.now(), this.batchSize);
2949
- for (const row of due) {
2950
- retried += 1;
2951
- const outcome = await this.attempt(row);
2952
- if (outcome === "succeeded") succeeded += 1;
2953
- else if (outcome === "dropped") dropped += 1;
2954
- }
2955
- } finally {
2956
- this.draining = false;
2957
- }
2958
- return { retried, succeeded, dropped };
2959
- }
2960
- async attempt(row) {
2961
- try {
2962
- await this.send(row.channelId, row.message);
2963
- this.outbox.delete(row.id);
2964
- this.log?.(
2965
- "info",
2966
- `outbox#${row.id} delivered to ${row.channelId} on attempt ${row.attempt + 1}`
2967
- );
2968
- return "succeeded";
2969
- } catch (err) {
2970
- const error2 = err instanceof Error ? err.message : String(err);
2971
- const nextAttempt = row.attempt + 1;
2972
- if (nextAttempt >= this.maxAttempts) {
2973
- this.outbox.delete(row.id);
2974
- this.log?.(
2975
- "error",
2976
- `outbox#${row.id} dropped after ${nextAttempt} attempts: ${error2}`
2977
- );
2978
- return "dropped";
2979
- }
2980
- const nextAttemptAt = this.now() + this.backoffFor(nextAttempt);
2981
- this.outbox.recordFailure({
2982
- id: row.id,
2983
- nextAttemptAt,
2984
- lastError: error2
2985
- });
2986
- return "requeued";
2987
- }
2988
- }
2989
- backoffFor(attempt) {
2990
- if (this.backoff.length === 0) return 1e3;
2991
- const idx = Math.min(attempt, this.backoff.length - 1);
2992
- return this.backoff[idx];
2993
- }
2994
- };
2995
-
2996
- // src/gateway/router/sessionKey.ts
2997
- function deriveSessionKey(loc) {
2998
- const c = loc.channelId;
2999
- const a = loc.accountId;
3000
- if (loc.peer?.id) {
3001
- const peer = loc.peer.id;
3002
- if (loc.thread?.id) {
3003
- return `peer:${c}:${a}:${peer}:${loc.thread.id}`;
3004
- }
3005
- return `peer:${c}:${a}:${peer}`;
3006
- }
3007
- if (loc.room?.id) {
3008
- const room = loc.room.id;
3009
- if (loc.thread?.id) {
3010
- return `room:${c}:${a}:${room}:${loc.thread.id}`;
3011
- }
3012
- return `room:${c}:${a}:${room}`;
3013
- }
3014
- return `default:${c}:${a}`;
3015
- }
3016
-
3017
- // src/gateway/sessionRegistry.ts
3018
- import { randomUUID } from "crypto";
3019
- var SessionRegistry = class {
3020
- dispatches = /* @__PURE__ */ new Map();
3021
- idFactory;
3022
- now;
3023
- constructor(opts = {}) {
3024
- this.idFactory = opts.idFactory ?? randomUUID;
3025
- this.now = opts.now ?? Date.now;
3026
- }
3027
- beginDispatch(input) {
3028
- const dispatchId = this.idFactory();
3029
- const entry = {
3030
- dispatchId,
3031
- sessionKey: input.sessionKey,
3032
- agentId: input.agentId,
3033
- runtimeId: input.runtimeId,
3034
- ...input.attachmentKey !== void 0 ? { attachmentKey: input.attachmentKey } : {},
3035
- location: input.location,
3036
- createdAt: this.now()
3037
- };
3038
- this.dispatches.set(dispatchId, entry);
3039
- return entry;
3040
- }
3041
- /**
3042
- * Resolve a parked turn for the runtime claiming to complete it. The entry is
3043
- * consumed only when the claiming runtime matches the one the turn was
3044
- * dispatched to — a mismatched runtime cannot cancel or steal another
3045
- * runtime's turn, and an unknown id is reported rather than thrown.
3046
- */
3047
- completeDispatch(dispatchId, by) {
3048
- const entry = this.dispatches.get(dispatchId);
3049
- if (!entry) {
3050
- return { kind: "unknown" };
3051
- }
3052
- if (entry.runtimeId !== by.runtimeId) {
3053
- return { kind: "runtime_mismatch", entry };
3054
- }
3055
- this.dispatches.delete(dispatchId);
3056
- return { kind: "completed", entry };
3057
- }
3058
- pendingDispatchCount() {
3059
- return this.dispatches.size;
3060
- }
3061
- /** Number of parked turns owned by the given runtime. */
3062
- pendingDispatchCountFor(runtimeId) {
3063
- let count = 0;
3064
- for (const entry of this.dispatches.values()) {
3065
- if (entry.runtimeId === runtimeId) count += 1;
3066
- }
3067
- return count;
3068
- }
3069
- /**
3070
- * Remove only the parked turns owned by the given runtime, leaving every other
3071
- * runtime's in-flight dispatches intact. Used when a single Registered runtime
3072
- * unregisters or its connection is lost — clearing the correct slot's turns
3073
- * without a global wipe.
3074
- */
3075
- clearDispatchesFor(runtimeId) {
3076
- for (const [dispatchId, entry] of this.dispatches) {
3077
- if (entry.runtimeId === runtimeId) {
3078
- this.dispatches.delete(dispatchId);
3079
- }
3080
- }
3081
- }
3082
- };
3083
-
3084
- // src/gateway/state/inboundQueue.ts
3085
- var DEFAULT_MAX_ENTRIES = 1e3;
3086
- var InboundQueue = class {
3087
- db;
3088
- maxEntries;
3089
- constructor(db, opts = {}) {
3090
- this.db = db;
3091
- this.maxEntries = opts.maxEntries ?? DEFAULT_MAX_ENTRIES;
3092
- }
3093
- size() {
3094
- const row = this.db.prepare("SELECT COUNT(*) as n FROM inbound_queue").get();
3095
- return row.n;
3096
- }
3097
- enqueue(inbound, key) {
3098
- if (this.size() >= this.maxEntries) {
3099
- return { kind: "rejected", reason: "queue_full" };
3100
- }
3101
- const stmt = this.db.prepare(
3102
- `INSERT INTO inbound_queue
3103
- (attachment_id, channel_id, account_id, idempotency_key, payload_json, created_at)
3104
- VALUES (?, ?, ?, ?, ?, ?)
3105
- ON CONFLICT(channel_id, account_id, idempotency_key) DO NOTHING`
3106
- );
3107
- const result = stmt.run(
3108
- key ?? null,
3109
- inbound.location.channelId,
3110
- inbound.location.accountId,
3111
- inbound.idempotencyKey,
3112
- JSON.stringify(inbound),
3113
- Date.now()
3114
- );
3115
- if (result.changes === 0) {
3116
- return { kind: "duplicate" };
3117
- }
3118
- return { kind: "queued", id: Number(result.lastInsertRowid) };
3119
- }
3120
- /** Atomically read and remove parked entries for one attachment slot. */
3121
- drain(key) {
3122
- return this.db.transaction(() => {
3123
- const rows = this.db.prepare(
3124
- `SELECT id, payload_json
3125
- FROM inbound_queue
3126
- WHERE attachment_id IS ?
3127
- ORDER BY id ASC`
3128
- ).all(key ?? null);
3129
- if (rows.length > 0) {
3130
- this.db.prepare("DELETE FROM inbound_queue WHERE attachment_id IS ?").run(key ?? null);
3131
- }
3132
- return rows.map((r) => ({
3133
- id: r.id,
3134
- inbound: JSON.parse(r.payload_json)
3135
- }));
3136
- })();
3137
- }
3138
- };
3139
-
3140
- // src/gateway/state/outbox.ts
3141
- var Outbox = class {
3142
- db;
3143
- constructor(db) {
3144
- this.db = db;
3145
- }
3146
- size() {
3147
- const row = this.db.prepare("SELECT COUNT(*) as n FROM channel_outbox").get();
3148
- return row.n;
3149
- }
3150
- enqueue(input) {
3151
- const result = this.db.prepare(
3152
- `INSERT INTO channel_outbox
3153
- (channel_id, payload_json, attempt, next_attempt_at, last_error, created_at)
3154
- VALUES (?, ?, 0, ?, ?, ?)`
3155
- ).run(
3156
- input.channelId,
3157
- JSON.stringify(input.message),
3158
- input.nextAttemptAt,
3159
- input.lastError ?? null,
3160
- Date.now()
3161
- );
3162
- return Number(result.lastInsertRowid);
3163
- }
3164
- /** Rows whose `next_attempt_at` is at or before `now`, oldest first. */
3165
- peekDue(now, limit) {
3166
- const rows = this.db.prepare(
3167
- `SELECT id, channel_id, payload_json, attempt, next_attempt_at, last_error
3168
- FROM channel_outbox
3169
- WHERE next_attempt_at <= ?
3170
- ORDER BY next_attempt_at ASC, id ASC
3171
- LIMIT ?`
3172
- ).all(now, limit);
3173
- return rows.map((r) => ({
3174
- id: r.id,
3175
- channelId: r.channel_id,
3176
- message: JSON.parse(r.payload_json),
3177
- attempt: r.attempt,
3178
- nextAttemptAt: r.next_attempt_at,
3179
- lastError: r.last_error
3180
- }));
3181
- }
3182
- delete(id) {
3183
- this.db.prepare("DELETE FROM channel_outbox WHERE id = ?").run(id);
3184
- }
3185
- recordFailure(input) {
3186
- this.db.prepare(
3187
- `UPDATE channel_outbox
3188
- SET attempt = attempt + 1,
3189
- next_attempt_at = ?,
3190
- last_error = ?
3191
- WHERE id = ?`
3192
- ).run(input.nextAttemptAt, input.lastError, input.id);
3193
- }
3194
- };
3195
-
3196
- // src/gateway/dispatchPipeline.ts
3197
- var DispatchPipeline = class {
3198
- bindingStore;
3199
- registry;
3200
- inboundQueue;
3201
- outbox;
3202
- outboundDispatcher;
3203
- resolveAgent;
3204
- log;
3205
- now;
3206
- idFactory;
3207
- constructor(opts) {
3208
- this.bindingStore = new RuntimeBindingStore({
3209
- gracePeriodMs: opts.gracePeriodMs,
3210
- observers: opts.observers,
3211
- now: opts.now
3212
- });
3213
- this.registry = new SessionRegistry({
3214
- now: opts.now ?? Date.now,
3215
- ...opts.idFactory ? { idFactory: opts.idFactory } : {}
3216
- });
3217
- this.inboundQueue = new InboundQueue(opts.stateDb, opts.inboundQueue ?? {});
3218
- this.outbox = new Outbox(opts.stateDb);
3219
- this.outboundDispatcher = new OutboundDispatcher({
3220
- outbox: this.outbox,
3221
- send: opts.send,
3222
- ...opts.outbox?.backoffSchedule ? { backoffSchedule: opts.outbox.backoffSchedule } : {},
3223
- ...opts.outbox?.maxAttempts !== void 0 ? { maxAttempts: opts.outbox.maxAttempts } : {},
3224
- ...opts.outbox?.tickIntervalMs !== void 0 ? { tickIntervalMs: opts.outbox.tickIntervalMs } : {},
3225
- ...opts.outbox?.drainBatchSize !== void 0 ? { drainBatchSize: opts.outbox.drainBatchSize } : {},
3226
- ...opts.now ? { now: opts.now } : {},
3227
- ...opts.log ? { log: opts.log } : {}
3228
- });
3229
- this.resolveAgent = opts.resolveAgent ?? ((input) => input.defaultAgentId);
3230
- this.log = opts.log;
3231
- this.now = opts.now ?? Date.now;
3232
- this.idFactory = opts.idFactory ?? crypto.randomUUID;
3233
- }
3234
- // ── lifecycle ────────────────────────────────────────────
3235
- start() {
3236
- this.outboundDispatcher.start();
3237
- }
3238
- async stop() {
3239
- this.outboundDispatcher.stop();
3240
- this.bindingStore.stop();
3241
- }
3242
- // ── inbound (channel side) ───────────────────────────────
3243
- handleInbound(inbound, options = {}) {
3244
- const key = options.attachmentId;
3245
- const current = this.bindingStore.getCurrentByAttachment(key);
3246
- if (!current || !this.bindingStore.hasActiveBindingForAttachment(key)) {
3247
- const result = this.inboundQueue.enqueue(inbound, key);
3248
- if (result.kind === "queued") {
3249
- this.log?.(
3250
- "info",
3251
- `no runtime registered; parked inbound ${inbound.idempotencyKey} as queue#${result.id}`
3252
- );
3253
- return { kind: "queued", queueId: result.id };
3254
- }
3255
- if (result.kind === "duplicate") {
3256
- this.log?.(
3257
- "debug",
3258
- `inbound ${inbound.idempotencyKey} already parked; ignoring duplicate`
3259
- );
3260
- return { kind: "dropped", reason: "no_runtime" };
3261
- }
3262
- this.log?.(
3263
- "warn",
3264
- `inbound queue full (>=${this.inboundQueue.size()}); dropping ${inbound.idempotencyKey}`
3265
- );
3266
- return { kind: "dropped", reason: "queue_full" };
3267
- }
3268
- return this.dispatchInboundToRuntime(inbound, current, key);
3269
- }
3270
- dispatchInboundToRuntime(inbound, current, key) {
3271
- const sessionKey = deriveSessionKey(inbound.location);
3272
- const agentId = this.resolveAgent({
3273
- sessionKey,
3274
- channelId: inbound.location.channelId,
3275
- defaultAgentId: current.defaultAgentId
3276
- });
3277
- if (!agentId) {
3278
- this.log?.(
3279
- "warn",
3280
- `agent resolution returned empty for sessionKey=${sessionKey}`
3281
- );
3282
- return { kind: "dropped", reason: "no_default_agent" };
3283
- }
3284
- const entry = this.registry.beginDispatch({
3285
- sessionKey,
3286
- agentId,
3287
- runtimeId: current.runtimeId,
3288
- ...key !== void 0 ? { attachmentKey: key } : {},
3289
- location: inbound.location
3290
- });
3291
- this.pushDispatch(key, {
3292
- dispatchId: entry.dispatchId,
3293
- sessionKey,
3294
- agentId,
3295
- inbound
3296
- });
3297
- return { kind: "dispatched", dispatchId: entry.dispatchId, sessionKey };
3298
- }
3299
- pushDispatch(key, payload) {
3300
- this.bindingStore.pushTo(key, {
3301
- push_id: this.idFactory(),
3302
- ts: this.now(),
3303
- kind: "session.dispatch.turn",
3304
- payload
3305
- });
3306
- }
3307
- // ── runtime side ─────────────────────────────────────────
3308
- registerRuntime(input) {
3309
- const key = input.attachmentId;
3310
- const result = this.bindingStore.bind({
3311
- runtimeId: input.runtimeId,
3312
- defaultAgentId: input.defaultAgentId,
3313
- pid: input.pid,
3314
- connectionId: input.connectionId,
3315
- push: input.push,
3316
- ...input.attachmentId !== void 0 ? { attachmentId: input.attachmentId } : {}
3317
- });
3318
- writeGatewayTrace(
3319
- `pipeline registered runtime runtimeId=${input.runtimeId} connectionId=${input.connectionId}`
3320
- );
3321
- this.drainPending(key);
3322
- return { registeredAt: result.registeredAt };
3323
- }
3324
- unregisterRuntime(runtimeId) {
3325
- this.bindingStore.unbind(runtimeId);
3326
- this.registry.clearDispatchesFor(runtimeId);
3327
- writeGatewayTrace(`pipeline unregistered runtime runtimeId=${runtimeId}`);
3328
- }
3329
- notifyConnectionClosed(connectionId) {
3330
- const runtimeId = this.bindingStore.notifyConnectionClosed(connectionId);
3331
- if (runtimeId === null) return;
3332
- writeGatewayTrace(
3333
- `pipeline runtime connection closed runtimeId=${runtimeId} connectionId=${connectionId}`
3334
- );
3335
- }
3336
- /**
3337
- * Streaming run-event from a registered runtime to its outbound channel
3338
- * adapter. Independent of dispatch state: `runId`/`seq` are the caller's
3339
- * own correlation, not the gateway's `dispatchId`.
3340
- */
3341
- async handleRunEvent(payload) {
3342
- const slot = this.findSlotByRuntimeId(payload.runtimeId);
3343
- if (!slot) {
3344
- throw new Error("runtime mismatch on session.run.event");
3345
- }
3346
- const envelopeText = JSON.stringify({
3347
- kind: "run_event",
3348
- runId: payload.runId,
3349
- seq: payload.seq,
3350
- ts: payload.ts,
3351
- eventKind: payload.kind,
3352
- ...payload.payload !== void 0 ? { payload: payload.payload } : {}
3353
- });
3354
- const out = {
3355
- location: payload.location,
3356
- text: envelopeText,
3357
- idempotencyKey: `run_event:${payload.runId}:${payload.seq}`
3358
- };
3359
- try {
3360
- await this.outboundDispatcher.dispatch(payload.location.channelId, out);
3361
- } catch {
3362
- return { delivered: false };
3363
- }
3364
- return { delivered: true };
3365
- }
3366
- async handleTurnComplete(payload) {
3367
- const slot = this.findSlotByRuntimeId(payload.runtimeId);
3368
- writeGatewayTrace(
3369
- `pipeline turn.complete received runtimeId=${payload.runtimeId} dispatchId=${payload.dispatchId} channel=${payload.location.channelId} account=${payload.location.accountId} thread=${payload.location.thread?.id ?? ""} textLength=${payload.text.length}`
3370
- );
3371
- if (!slot) {
3372
- throw new Error("runtime mismatch on session.turn.complete");
3373
- }
3374
- const completion = this.registry.completeDispatch(payload.dispatchId, {
3375
- runtimeId: payload.runtimeId
3376
- });
3377
- if (completion.kind === "unknown") {
3378
- writeGatewayTrace(
3379
- `pipeline turn.complete unknown dispatchId=${payload.dispatchId}`
3380
- );
3381
- return { delivered: false };
3382
- }
3383
- if (completion.kind === "runtime_mismatch") {
3384
- writeGatewayTrace(
3385
- `pipeline turn.complete runtime mismatch dispatchId=${payload.dispatchId} authorized=${completion.entry.runtimeId} claimed=${payload.runtimeId}`
3386
- );
3387
- return { delivered: false };
3388
- }
3389
- const result = await this.sendOutbound(completion.entry.location, payload);
3390
- writeGatewayTrace(
3391
- `pipeline sendOutbound delivered dispatchId=${payload.dispatchId} providerMessageId=${result.providerMessageId}`
3392
- );
3393
- return { delivered: true, providerMessageId: result.providerMessageId };
3394
- }
3395
- async sendOutbound(parkedLocation, payload) {
3396
- const out = {
3397
- location: parkedLocation,
3398
- text: payload.text,
3399
- idempotencyKey: payload.idempotencyKey
3400
- };
3401
- const result = await this.outboundDispatcher.dispatch(
3402
- parkedLocation.channelId,
3403
- out
3404
- );
3405
- if (result.kind === "sent") return result.result;
3406
- return {
3407
- providerMessageId: `outbox:${result.outboxId}`,
3408
- deliveredAt: this.now()
3409
- };
3410
- }
3411
- findSlotByRuntimeId(runtimeId) {
3412
- return this.bindingStore.getAttachmentKeyByRuntimeId(runtimeId);
3413
- }
3414
- drainPending(key) {
3415
- const current = this.bindingStore.getCurrentByAttachment(key);
3416
- if (!current || !this.bindingStore.hasActiveBindingForAttachment(key))
3417
- return;
3418
- const parked = this.inboundQueue.drain(key);
3419
- let dispatched = 0;
3420
- let dropped = 0;
3421
- for (const { inbound } of parked) {
3422
- const result = this.dispatchInboundToRuntime(inbound, current, key);
3423
- if (result.kind === "dispatched") dispatched += 1;
3424
- else dropped += 1;
3425
- }
3426
- if (dispatched > 0 || dropped > 0) {
3427
- this.log?.(
3428
- "info",
3429
- `drainPending: dispatched=${dispatched} dropped=${dropped}`
3430
- );
3431
- }
3432
- }
3433
- // ── reads ────────────────────────────────────────────────
3434
- getCurrentRuntime() {
3435
- return this.bindingStore.getCurrent();
3436
- }
3437
- /** Reportable state for every registered-runtime slot (legacy + attachment-keyed). */
3438
- snapshotRuntimes() {
3439
- return this.bindingStore.snapshot();
3440
- }
3441
- getCurrentRuntimeByAttachment(attachmentId) {
3442
- return this.bindingStore.getCurrentByAttachment(attachmentId);
3443
- }
3444
- getBinding() {
3445
- return this.bindingStore.getBinding();
3446
- }
3447
- hasActiveBinding(runtimeId) {
3448
- return this.bindingStore.hasActiveBinding(runtimeId);
3449
- }
3450
- getRuntimeIdByConnection(connectionId) {
3451
- return this.bindingStore.getRuntimeIdByConnection(connectionId);
3452
- }
3453
- pendingDispatchCount() {
3454
- return this.registry.pendingDispatchCount();
3455
- }
3456
- pendingDispatchCountFor(runtimeId) {
3457
- return this.registry.pendingDispatchCountFor(runtimeId);
3458
- }
3459
- pendingInboundCount() {
3460
- return this.inboundQueue.size();
3461
- }
3462
- pendingOutboxCount() {
3463
- return this.outbox.size();
3464
- }
3465
- };
3466
-
3467
- // src/gateway/listenerPlan.ts
3468
- function planListener(spec, token) {
3469
- requireTokenForBind(spec, token);
3470
- if (spec.kind === "uds") {
3471
- return {
3472
- transport: { kind: "uds", socketPath: spec.socketPath },
3473
- warnings: []
3474
- };
3475
- }
3476
- const warnings = [];
3477
- if (spec.insecure && !spec.tls && !isLoopbackHost(spec.host)) {
3478
- warnings.push(
3479
- `athena-gateway: WARNING --insecure is set on a non-loopback bind (${spec.host}:${spec.port}); token travels in plaintext. Use only behind TLS-terminating reverse proxy or Tailscale/WireGuard tunnel.`
3480
- );
3481
- }
3482
- return {
3483
- transport: {
3484
- kind: "tcp",
3485
- host: spec.host,
3486
- port: spec.port,
3487
- allowNonLoopback: spec.insecure || Boolean(spec.tls),
3488
- ...spec.tls ? { tls: spec.tls } : {}
3489
- },
3490
- warnings
3491
- };
3492
- }
3493
-
3494
- // src/gateway/lock.ts
3495
- import fs2 from "fs";
3496
- import path2 from "path";
3497
- var GatewayAlreadyRunningError = class extends Error {
3498
- otherPid;
3499
- constructor(otherPid) {
3500
- super(`gateway already running (pid=${otherPid})`);
3501
- this.name = "GatewayAlreadyRunningError";
3502
- this.otherPid = otherPid;
3503
- }
3504
- };
3505
- function isProcessAlive(pid) {
3506
- try {
3507
- process.kill(pid, 0);
3508
- return true;
3509
- } catch (err) {
3510
- const code = err.code;
3511
- return code === "EPERM";
3512
- }
3513
- }
3514
- function readPidFile(p) {
3515
- try {
3516
- const text = fs2.readFileSync(p, "utf-8").trim();
3517
- const pid = Number.parseInt(text, 10);
3518
- return Number.isInteger(pid) && pid > 0 ? pid : null;
3519
- } catch {
3520
- return null;
3521
- }
3522
- }
3523
- function acquireLock(lockPath) {
3524
- fs2.mkdirSync(path2.dirname(lockPath), { recursive: true, mode: 448 });
3525
- for (let attempt = 0; attempt < 2; attempt++) {
3526
- try {
3527
- const fd = fs2.openSync(lockPath, "wx", 384);
3528
- fs2.writeSync(fd, String(process.pid) + "\n");
3529
- fs2.closeSync(fd);
3530
- return {
3531
- path: lockPath,
3532
- pid: process.pid,
3533
- release: () => {
3534
- try {
3535
- const pidNow = readPidFile(lockPath);
3536
- if (pidNow === process.pid) {
3537
- fs2.unlinkSync(lockPath);
3538
- }
3539
- } catch {
3540
- }
3541
- }
3542
- };
3543
- } catch (err) {
3544
- const code = err.code;
3545
- if (code !== "EEXIST") throw err;
3546
- const otherPid = readPidFile(lockPath);
3547
- if (otherPid !== null && isProcessAlive(otherPid)) {
3548
- throw new GatewayAlreadyRunningError(otherPid);
3549
- }
3550
- try {
3551
- fs2.unlinkSync(lockPath);
3552
- } catch {
3553
- }
3554
- }
3555
- }
3556
- throw new Error(`failed to acquire gateway lock at ${lockPath}`);
3557
- }
3558
-
3559
- // src/gateway/relay/pendingRegistry.ts
3560
- var PendingRegistry = class {
3561
- entries = /* @__PURE__ */ new Map();
3562
- inspect(channelRequestId, kind, fingerprint, runtimeId) {
3563
- const existing = this.entries.get(channelRequestId);
3564
- if (!existing) return { kind: "absent" };
3565
- if (existing.kind !== kind) return { kind: "collision", reason: "kind" };
3566
- if (existing.fingerprint !== fingerprint) {
3567
- return { kind: "collision", reason: "payload" };
3568
- }
3569
- if (existing.runtimeId !== runtimeId) {
3570
- return { kind: "collision", reason: "owner" };
3571
- }
3572
- return { kind: "attach", entry: existing };
3573
- }
3574
- register(entry) {
3575
- this.entries.set(entry.channelRequestId, entry);
3576
- }
3577
- settle(channelRequestId, result) {
3578
- const entry = this.entries.get(channelRequestId);
3579
- if (!entry || entry.settled) return false;
3580
- entry.settled = true;
3581
- this.entries.delete(channelRequestId);
3582
- clearTimeout(entry.timer);
3583
- for (const ctrl of entry.controllers) {
3584
- if (!ctrl.signal.aborted) ctrl.abort();
3585
- }
3586
- entry.resolve(result);
3587
- return true;
3588
- }
3589
- cancel(channelRequestId, reason, expectedRuntimeId) {
3590
- const entry = this.entries.get(channelRequestId);
3591
- if (!entry) return false;
3592
- if (expectedRuntimeId !== void 0 && entry.runtimeId !== void 0 && entry.runtimeId !== expectedRuntimeId) {
3593
- return false;
3594
- }
3595
- return this.settle(channelRequestId, { kind: "cancelled", reason });
3596
- }
3597
- disposeAll(reason) {
3598
- for (const id of [...this.entries.keys()]) {
3599
- this.cancel(id, reason, void 0);
3600
- }
3601
- }
3602
- count() {
3603
- return this.entries.size;
3604
- }
3605
- };
3606
- function collisionMessage(channelRequestId, reason, newKind) {
3607
- if (reason === "owner") {
3608
- return `channel_request_owner_mismatch: ${channelRequestId} owned by a different runtime`;
3609
- }
3610
- if (reason === "kind") {
3611
- const otherKind = newKind === "permission" ? "question" : "permission";
3612
- return `channel_request_id_collision: ${channelRequestId} is bound to a ${otherKind} relay`;
3613
- }
3614
- return `channel_request_id_collision: ${channelRequestId} payload mismatch`;
3615
- }
3616
-
3617
- // src/gateway/relay/coordinator.ts
3618
- var DEFAULT_RELAY_TTL_MS = 5 * 6e4;
3619
- var RelayCoordinator = class {
3620
- adapters;
3621
- defaultTtlMs;
3622
- idFactory;
3623
- log;
3624
- registry = new PendingRegistry();
3625
- constructor(opts) {
3626
- this.adapters = opts.adapters;
3627
- this.defaultTtlMs = opts.defaultTtlMs ?? DEFAULT_RELAY_TTL_MS;
3628
- this.idFactory = opts.idFactory ?? generateChannelRequestId;
3629
- this.log = opts.log;
3630
- }
3631
- requestPermission(req) {
3632
- const channelRequestId = req.channelRequestId ?? this.idFactory();
3633
- const targets = this.adapters().filter(
3634
- (a) => a.capabilities.relayPermission && typeof a.requestPermissionVerdict === "function"
3635
- );
3636
- if (targets.length === 0) {
3637
- return { channelRequestId, result: Promise.resolve({ kind: "no_relay" }) };
3638
- }
3639
- const fingerprint = permissionFingerprint(req);
3640
- const inspect = this.registry.inspect(
3641
- channelRequestId,
3642
- "permission",
3643
- fingerprint,
3644
- req.runtimeId
3645
- );
3646
- if (inspect.kind === "collision") {
3647
- throw new Error(
3648
- collisionMessage(channelRequestId, inspect.reason, "permission")
3649
- );
3650
- }
3651
- if (inspect.kind === "attach") {
3652
- return {
3653
- channelRequestId,
3654
- result: inspect.entry.result
3655
- };
3656
- }
3657
- const fullReq = {
3658
- channelRequestId,
3659
- toolName: req.toolName,
3660
- description: req.description,
3661
- inputPreview: req.inputPreview
3662
- };
3663
- const result = this.broadcast({
3664
- kind: "permission",
3665
- channelRequestId,
3666
- ttlMs: req.ttlMs === null ? null : req.ttlMs ?? this.defaultTtlMs,
3667
- runtimeId: req.runtimeId,
3668
- fingerprint,
3669
- targets,
3670
- perAdapter: async (adapter, signal) => {
3671
- const res = await adapter.requestPermissionVerdict(fullReq, signal);
3672
- return res.kind === "verdict" ? { ...res, channelId: adapter.id } : null;
3673
- }
3674
- });
3675
- return { channelRequestId, result };
3676
- }
3677
- requestQuestion(req) {
3678
- const channelRequestId = req.channelRequestId ?? this.idFactory();
3679
- const targets = this.adapters().filter(
3680
- (a) => a.capabilities.relayQuestion && typeof a.requestQuestionAnswer === "function"
3681
- );
3682
- if (targets.length === 0) {
3683
- return { channelRequestId, result: Promise.resolve({ kind: "no_relay" }) };
3684
- }
3685
- const fingerprint = questionFingerprint(req);
3686
- const inspect = this.registry.inspect(
3687
- channelRequestId,
3688
- "question",
3689
- fingerprint,
3690
- req.runtimeId
3691
- );
3692
- if (inspect.kind === "collision") {
3693
- throw new Error(
3694
- collisionMessage(channelRequestId, inspect.reason, "question")
3695
- );
3696
- }
3697
- if (inspect.kind === "attach") {
3698
- return {
3699
- channelRequestId,
3700
- result: inspect.entry.result
3701
- };
3702
- }
3703
- const fullReq = {
3704
- channelRequestId,
3705
- title: req.title,
3706
- questions: req.questions
3707
- };
3708
- const result = this.broadcast({
3709
- kind: "question",
3710
- channelRequestId,
3711
- ttlMs: req.ttlMs === null ? null : req.ttlMs ?? this.defaultTtlMs,
3712
- runtimeId: req.runtimeId,
3713
- fingerprint,
3714
- targets,
3715
- perAdapter: async (adapter, signal) => {
3716
- const res = await adapter.requestQuestionAnswer(fullReq, signal);
3717
- return res.kind === "answer" ? { ...res, channelId: adapter.id } : null;
3718
- }
3719
- });
3720
- return { channelRequestId, result };
3721
- }
3722
- cancel(channelRequestId, reason, expectedRuntimeId) {
3723
- return this.registry.cancel(channelRequestId, reason, expectedRuntimeId);
3724
- }
3725
- pendingCount() {
3726
- return this.registry.count();
3727
- }
3728
- disposeAll(reason = "auto_resolved") {
3729
- this.registry.disposeAll(reason);
3730
- }
3731
- broadcast(args) {
3732
- const {
3733
- kind,
3734
- channelRequestId,
3735
- ttlMs,
3736
- runtimeId,
3737
- fingerprint,
3738
- targets,
3739
- perAdapter
3740
- } = args;
3741
- const controllers = targets.map(() => new AbortController());
3742
- let resolveFn;
3743
- const result = new Promise((resolve) => {
3744
- resolveFn = resolve;
3745
- });
3746
- const timer = ttlMs === null ? void 0 : setTimeout(() => {
3747
- this.registry.settle(channelRequestId, {
3748
- kind: "cancelled",
3749
- reason: "timeout"
3750
- });
3751
- }, ttlMs);
3752
- if (timer && typeof timer.unref === "function") timer.unref();
3753
- this.registry.register({
3754
- kind,
3755
- channelRequestId,
3756
- fingerprint,
3757
- runtimeId,
3758
- controllers,
3759
- timer,
3760
- resolve: resolveFn,
3761
- result,
3762
- settled: false
3763
- });
3764
- targets.forEach((adapter, idx) => {
3765
- const ctrl = controllers[idx];
3766
- Promise.resolve().then(() => perAdapter(adapter, ctrl.signal)).then((res) => {
3767
- if (res !== null) {
3768
- this.registry.settle(channelRequestId, res);
3769
- }
3770
- }).catch((err) => {
3771
- this.log?.(
3772
- "warn",
3773
- `adapter ${adapter.id} ${kind} relay failed: ${err instanceof Error ? err.message : String(err)}`
3774
- );
3775
- });
3776
- });
3777
- return result;
3778
- }
3779
- };
3780
- function permissionFingerprint(req) {
3781
- return JSON.stringify([req.toolName, req.description, req.inputPreview]);
3782
- }
3783
- function questionFingerprint(req) {
3784
- return JSON.stringify([req.title, req.questions]);
3785
- }
3786
-
3787
- // src/gateway/state/db.ts
3788
- import fs3 from "fs";
3789
- var GATEWAY_STATE_VERSION = 2;
3790
- var migrateGatewayState = (db, fromVersion) => {
3791
- db.exec(`
3792
- -- Inbound chat messages parked while no runtime is registered. Drained
3793
- -- in FIFO id order on session.register. Idempotency key prevents the
3794
- -- same provider message from being parked twice if an adapter retries.
3795
- CREATE TABLE IF NOT EXISTS inbound_queue (
3796
- id INTEGER PRIMARY KEY AUTOINCREMENT,
3797
- attachment_id TEXT,
3798
- channel_id TEXT NOT NULL,
3799
- account_id TEXT NOT NULL,
3800
- idempotency_key TEXT NOT NULL,
3801
- payload_json TEXT NOT NULL,
3802
- created_at INTEGER NOT NULL
3803
- );
3804
- CREATE UNIQUE INDEX IF NOT EXISTS ix_inbound_queue_idem
3805
- ON inbound_queue(channel_id, account_id, idempotency_key);
3806
-
3807
- -- Outbound messages whose adapter send() failed transiently. Drained
3808
- -- by a periodic retry loop with exponential backoff. Idempotency key
3809
- -- on the OutboundMessage prevents double-delivery if the adapter
3810
- -- partially succeeded before throwing.
3811
- CREATE TABLE IF NOT EXISTS channel_outbox (
3812
- id INTEGER PRIMARY KEY AUTOINCREMENT,
3813
- channel_id TEXT NOT NULL,
3814
- payload_json TEXT NOT NULL,
3815
- attempt INTEGER NOT NULL DEFAULT 0,
3816
- next_attempt_at INTEGER NOT NULL,
3817
- last_error TEXT,
3818
- created_at INTEGER NOT NULL
3819
- );
3820
- CREATE INDEX IF NOT EXISTS ix_channel_outbox_due
3821
- ON channel_outbox(next_attempt_at);
3822
- `);
3823
- if (fromVersion === void 0) return;
3824
- const inboundColumns = db.prepare("PRAGMA table_info(inbound_queue)").all();
3825
- if (!inboundColumns.some((column) => column.name === "attachment_id")) {
3826
- db.prepare("ALTER TABLE inbound_queue ADD COLUMN attachment_id TEXT").run();
3827
- }
3828
- if (fromVersion < GATEWAY_STATE_VERSION) {
3829
- db.prepare("UPDATE schema_version SET version = ?").run(
3830
- GATEWAY_STATE_VERSION
3831
- );
3832
- }
3833
- };
3834
- function openGatewayState(dbPath) {
3835
- const db = openVersionedDb(dbPath, {
3836
- version: GATEWAY_STATE_VERSION,
3837
- migrate: migrateGatewayState,
3838
- foreignKeys: true,
3839
- ensureDir: true,
3840
- dirMode: 448,
3841
- onNewerVersion: (found, expected) => new Error(
3842
- `Gateway state DB has newer schema version ${found} (expected <= ${expected}). Update athena-cli.`
3843
- )
3844
- });
3845
- if (dbPath !== ":memory:" && process.platform !== "win32") {
3846
- try {
3847
- fs3.chmodSync(dbPath, 384);
3848
- } catch {
3849
- }
3850
- }
3851
- return db;
3852
- }
3853
-
3854
- // src/gateway/daemon.ts
3855
- function describeToStatus(desc, spec) {
3856
- if (desc.kind === "uds") {
3857
- return { kind: "uds", socketPath: desc.socketPath };
3858
- }
3859
- return {
3860
- kind: "tcp",
3861
- host: desc.host,
3862
- port: desc.port,
3863
- url: desc.url,
3864
- tls: desc.tls,
3865
- insecure: spec.kind === "tcp" ? spec.insecure : false,
3866
- loopback: isLoopbackHost(desc.host)
3867
- };
3868
- }
3869
- async function startDaemon(opts) {
3870
- const startedAt = Date.now();
3871
- const pid = process.pid;
3872
- const paths = opts.paths ?? resolveGatewayPaths(opts.env);
3873
- fs4.mkdirSync(paths.runDir, { recursive: true, mode: 448 });
3874
- fs4.mkdirSync(paths.configDir, { recursive: true, mode: 448 });
3875
- if (process.platform !== "win32") {
3876
- try {
3877
- fs4.chmodSync(paths.runDir, 448);
3878
- fs4.chmodSync(paths.configDir, 448);
3879
- } catch {
3880
- }
3881
- }
3882
- const lock = acquireLock(paths.lockPath);
3883
- const token = loadOrCreateToken(paths.tokenPath);
3884
- const listenSpec = opts.listenSpec ?? resolveListenSpec({ paths });
3885
- const listenerPlan = planListener(listenSpec, token);
3886
- const listenerHints = {
3887
- transport: listenSpec.kind === "tcp" ? "ws" : "uds",
3888
- tls: listenSpec.kind === "tcp" && Boolean(listenSpec.tls),
3889
- loopback: listenSpec.kind === "uds" || isLoopbackHost(listenSpec.host)
3890
- };
3891
- const stateDb = openGatewayState(paths.statePath);
3892
- const channelManager = new ChannelManager();
3893
- const relayCoordinator = new RelayCoordinator({
3894
- adapters: () => channelManager.listAdapters()
3895
- });
3896
- const connectionOpenedAt = /* @__PURE__ */ new Map();
3897
- const disconnectGracePeriodMs = opts.disconnectGracePeriodMs ?? 0;
3898
- let listenerStatus = null;
3899
- const log = (level, message) => {
3900
- if (opts.silent) return;
3901
- const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
3902
- process[stream].write(`athena-gateway: [${level}] ${message}
3903
- `);
3904
- };
3905
- const pipeline = new DispatchPipeline({
3906
- stateDb,
3907
- send: (channelId, msg) => channelManager.send(channelId, msg),
3908
- gracePeriodMs: disconnectGracePeriodMs,
3909
- log,
3910
- observers: {
3911
- onRuntimeRebind: ({ gapMs, epoch }) => trackGatewayRuntimeRebind({ gapMs, epoch }),
3912
- onRuntimeExpired: ({ gapMs }) => trackGatewayRuntimeExpired({ gapMs }),
3913
- // Single-runtime v1: blanket dispose is safe. Multi-runtime must
3914
- // scope to the disconnecting runtime via disposeAllForRuntime.
3915
- onRuntimeConnectionLost: () => relayCoordinator.disposeAll("connection_lost")
3916
- }
3917
- });
3918
- pipeline.start();
3919
- channelManager.setInboundSink((inbound, ctx) => {
3920
- pipeline.handleInbound(inbound, ctx);
3921
- });
3922
- const channelSidecarReconciler = new ChannelSidecarReconciler({
3923
- channelManager,
3924
- home: opts.env?.HOME
3925
- });
3926
- const reloadChannels = async () => channelSidecarReconciler.reconcile({
3927
- unregisterStale: true,
3928
- logRegistrations: !opts.silent
3929
- });
3930
- if (!opts.skipChannelLoad) {
3931
- await channelSidecarReconciler.reconcile({
3932
- unregisterStale: false,
3933
- logFailures: true,
3934
- logRegistrations: !opts.silent
3935
- });
3936
- }
3937
- let transport;
3938
- const handler = createDispatcher({
3939
- startedAt,
3940
- pipeline,
3941
- channelManager,
3942
- relayCoordinator,
3943
- getListener: () => listenerStatus ?? describeToStatus(transport.describe(), listenSpec),
3944
- reloadChannels
3945
- });
3946
- let server;
3947
- let listener;
3948
- try {
3949
- const tcpPlan = listenerPlan.transport.kind === "tcp" ? listenerPlan.transport : null;
3950
- transport = tcpPlan ? createWsServerTransport({
3951
- host: tcpPlan.host,
3952
- port: tcpPlan.port,
3953
- allowNonLoopback: tcpPlan.allowNonLoopback,
3954
- ...tcpPlan.tls ? { tls: tcpPlan.tls } : {}
3955
- }) : createUdsServerTransport({ socketPath: paths.socketPath });
3956
- server = await startControlServer({
3957
- socketPath: paths.socketPath,
3958
- token,
3959
- startedAt,
3960
- handler,
3961
- transport,
3962
- onConnect: (ctx) => {
3963
- connectionOpenedAt.set(ctx.connectionId, Date.now());
3964
- trackGatewayTransportConnect({
3965
- transport: listenerHints.transport,
3966
- tls: listenerHints.tls,
3967
- loopback: listenerHints.loopback
3968
- });
3969
- },
3970
- onDisconnect: (ctx) => {
3971
- const openedAt = connectionOpenedAt.get(ctx.connectionId);
3972
- connectionOpenedAt.delete(ctx.connectionId);
3973
- const durationMs = openedAt !== void 0 ? Date.now() - openedAt : 0;
3974
- trackGatewayTransportDisconnect({
3975
- transport: listenerHints.transport,
3976
- reason: "closed",
3977
- durationMs
3978
- });
3979
- pipeline.notifyConnectionClosed(ctx.connectionId);
3980
- }
3981
- });
3982
- const description = transport.describe();
3983
- listenerStatus = describeToStatus(description, listenSpec);
3984
- listener = description.kind === "uds" ? { kind: "uds", socketPath: description.socketPath } : {
3985
- kind: "tcp",
3986
- host: description.host,
3987
- port: description.port,
3988
- url: description.url
3989
- };
3990
- } catch (err) {
3991
- lock.release();
3992
- throw err;
3993
- }
3994
- if (!opts.silent) {
3995
- const target = listener.kind === "tcp" ? listener.url : `socket=${paths.socketPath}`;
3996
- process.stdout.write(`athena-gateway: ok pid=${pid} ${target}
3997
- `);
3998
- }
3999
- for (const warning of listenerPlan.warnings) {
4000
- process.stderr.write(warning + "\n");
4001
- }
4002
- let stopping = false;
4003
- const stop = async () => {
4004
- if (stopping) return;
4005
- stopping = true;
4006
- try {
4007
- await pipeline.stop();
4008
- relayCoordinator.disposeAll("auto_resolved");
4009
- await channelManager.stop();
4010
- await server.close();
4011
- } finally {
4012
- try {
4013
- stateDb.close();
4014
- } catch {
4015
- }
4016
- lock.release();
4017
- }
4018
- };
4019
- if (!opts.skipSignalHandlers) {
4020
- const onSignal = (signal) => {
4021
- process.stderr.write(`athena-gateway: received ${signal}, stopping
4022
- `);
4023
- void stop().then(() => process.exit(0));
4024
- };
4025
- process.once("SIGINT", onSignal);
4026
- process.once("SIGTERM", onSignal);
4027
- }
4028
- return {
4029
- startedAt,
4030
- pid,
4031
- paths,
4032
- pipeline,
4033
- channelManager,
4034
- relayCoordinator,
4035
- listener,
4036
- stop
4037
- };
4038
- }
4039
-
4040
- // src/gateway/entryArgs.ts
4041
- function parseGatewayDaemonArgs(argv) {
4042
- const parsed = { silent: false, insecure: false };
4043
- for (let i = 0; i < argv.length; i += 1) {
4044
- const arg = argv[i];
4045
- if (arg === "--silent") {
4046
- parsed.silent = true;
4047
- continue;
4048
- }
4049
- if (arg === "--insecure") {
4050
- parsed.insecure = true;
4051
- continue;
4052
- }
4053
- if (arg === "--bind") {
4054
- parsed.bind = requireValue(argv, i, "--bind");
4055
- i += 1;
4056
- continue;
4057
- }
4058
- if (arg.startsWith("--bind=")) {
4059
- parsed.bind = arg.slice("--bind=".length);
4060
- continue;
4061
- }
4062
- if (arg === "--grace-period-ms") {
4063
- parsed.gracePeriodMs = parseGracePeriod(
4064
- requireValue(argv, i, "--grace-period-ms")
4065
- );
4066
- i += 1;
4067
- continue;
4068
- }
4069
- if (arg.startsWith("--grace-period-ms=")) {
4070
- parsed.gracePeriodMs = parseGracePeriod(
4071
- arg.slice("--grace-period-ms=".length)
4072
- );
4073
- continue;
4074
- }
4075
- const tls = matchPathFlag(arg, argv, i, [
4076
- ["--tls-cert", "tlsCertPath"],
4077
- ["--tls-key", "tlsKeyPath"]
4078
- ]);
4079
- if (tls) {
4080
- parsed[tls.key] = tls.value;
4081
- i += tls.consumed;
4082
- continue;
4083
- }
4084
- throw new Error(`gateway: unknown daemon option ${arg}`);
4085
- }
4086
- if (parsed.tlsCertPath && !parsed.tlsKeyPath || !parsed.tlsCertPath && parsed.tlsKeyPath) {
4087
- throw new Error("gateway: --tls-cert and --tls-key must be used together");
4088
- }
4089
- return parsed;
4090
- }
4091
- function matchPathFlag(arg, argv, index, specs) {
4092
- for (const [flag, key] of specs) {
4093
- if (arg === flag) {
4094
- return { key, value: requireValue(argv, index, flag), consumed: 1 };
4095
- }
4096
- const prefix = `${flag}=`;
4097
- if (arg.startsWith(prefix)) {
4098
- return { key, value: arg.slice(prefix.length), consumed: 0 };
4099
- }
4100
- }
4101
- return null;
4102
- }
4103
- function requireValue(argv, index, flag) {
4104
- const value = argv[index + 1];
4105
- if (!value || value.startsWith("--")) {
4106
- throw new Error(`gateway: ${flag} requires a value`);
4107
- }
4108
- return value;
4109
- }
4110
- function parseGracePeriod(value) {
4111
- const n = Number(value);
4112
- if (!Number.isInteger(n) || n < 0) {
4113
- throw new Error(
4114
- `gateway: --grace-period-ms must be a non-negative integer`
4115
- );
4116
- }
4117
- return n;
4118
- }
4119
-
4120
- // src/gateway/entry.ts
4121
- async function main() {
4122
- const args = parseGatewayDaemonArgs(process.argv.slice(2));
4123
- const paths = resolveGatewayPaths();
4124
- const tls = args.tlsCertPath && args.tlsKeyPath ? { certPath: args.tlsCertPath, keyPath: args.tlsKeyPath } : void 0;
4125
- const listenSpec = resolveListenSpec({
4126
- paths,
4127
- ...args.bind !== void 0 ? { bind: args.bind } : {},
4128
- insecure: args.insecure,
4129
- ...tls ? { tls } : {}
4130
- });
4131
- await startDaemon({
4132
- foreground: true,
4133
- silent: args.silent,
4134
- paths,
4135
- listenSpec,
4136
- disconnectGracePeriodMs: args.gracePeriodMs ?? (listenSpec.kind === "tcp" ? 6e4 : void 0)
4137
- });
4138
- setInterval(() => {
4139
- }, 1 << 30);
4140
- }
4141
- main().catch((err) => {
4142
- process.stderr.write(
4143
- `athena-gateway: startup failed: ${err instanceof Error ? err.message : String(err)}
4144
- `
4145
- );
4146
- process.exit(1);
4147
- });
4148
- //# sourceMappingURL=athena-gateway.js.map