my-durable 0.0.43 → 0.0.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/dpi-backend/src/main.ts +1 -0
- package/apps/dpi-backend/src/store.ts +47 -1
- package/apps/dpi-backend/src/telegram-cli.ts +286 -0
- package/apps/dpi-backend/src/telegram.ts +789 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BDY9dgTQ.js +81 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-EulngMVY.css → index-CraiQho0.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +3 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +49 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +47 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +239 -0
- package/apps/dpi-sdk/src/api.ts +2 -2
- package/bin/dpi.mjs +8 -0
- package/docs/host-project-checklist.md +3 -3
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BgKiQEMm.js +0 -81
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device-side Telegram channel bridge — "Telegram channel bridge", Wave 3
|
|
3
|
+
* (SHOULD) of docs/host-project-checklist.md.
|
|
4
|
+
*
|
|
5
|
+
* A Telegram chat bound to a device session: plain text the operator types
|
|
6
|
+
* becomes a submission to that session's main agent, and the agent's answer
|
|
7
|
+
* comes back as a Telegram reply. Modelled on zcode's
|
|
8
|
+
* `packages/services/src/bots/telegramChannelRuntime.ts` (a channel message
|
|
9
|
+
* routed into an existing session-submission surface). The adaptation is the
|
|
10
|
+
* binding itself — zcode's channel knows its session by configuration, while a
|
|
11
|
+
* dpi device has many sessions, so a chat is bound to one at a time with a
|
|
12
|
+
* single-use `/start <code>` (minted by `dpi telegram bind`, 10-minute expiry)
|
|
13
|
+
* and can switch with `/session <id-prefix>`.
|
|
14
|
+
*
|
|
15
|
+
* Discipline, in the order the checklist cares about it:
|
|
16
|
+
* - **Acknowledge before handle.** The update offset is advanced and persisted
|
|
17
|
+
* *before* an update is handled, so a crash re-delivers at worst one update
|
|
18
|
+
* and never re-runs a turn. If that persist fails, the update is skipped and
|
|
19
|
+
* re-delivered by the next poll rather than handled on an unadvanced offset.
|
|
20
|
+
* - **A stranger learns nothing.** Plain text from an unbound chat is dropped
|
|
21
|
+
* silently — no usage hint, no error, no ack — because the only thing a
|
|
22
|
+
* random person who found the bot should take away is that it says nothing.
|
|
23
|
+
* - **Nothing here can kill a session turn or the loop.** Every update handler
|
|
24
|
+
* runs inside a catch-all, replies are best-effort (`sendMessage` failures
|
|
25
|
+
* are warned, never thrown), and a rejected token (401/404) stops the loop
|
|
26
|
+
* instead of spinning it against a wall of 4xx.
|
|
27
|
+
* - **The registry file is the truth.** Same handling as `notify-sinks.ts`:
|
|
28
|
+
* versioned JSON, 0600, `.bak` rolling backup, an unreadable file moved
|
|
29
|
+
* aside with a warning instead of overwritten, serialized mutations.
|
|
30
|
+
*
|
|
31
|
+
* Everything that touches a session goes through `TelegramBroker` — the daemon
|
|
32
|
+
* wires that to the Store; this module never imports it. Everything that
|
|
33
|
+
* touches the world (fs, clock, fetch, timers) goes through `TelegramIo`, so
|
|
34
|
+
* the tests run against fakes with zero sockets and zero real time.
|
|
35
|
+
*/
|
|
36
|
+
import { randomBytes } from "node:crypto";
|
|
37
|
+
import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
38
|
+
import { dirname, resolve } from "node:path";
|
|
39
|
+
|
|
40
|
+
/** Bumped only when the on-disk shape changes; `coerceRegistry` owns the upgrade path. */
|
|
41
|
+
export const TELEGRAM_REGISTRY_VERSION = 1;
|
|
42
|
+
|
|
43
|
+
/** A bind code is typed by a human on a phone; ten minutes is generous and still bounded. */
|
|
44
|
+
export const CODE_TTL_MS = 10 * 60_000;
|
|
45
|
+
/** How long the bridge waits for a turn to settle before answering "no answer". */
|
|
46
|
+
export const ANSWER_TIMEOUT_MS = 120_000;
|
|
47
|
+
/** The agent's failure text is a Telegram message; past this it is a pasted stack trace. */
|
|
48
|
+
export const MAX_REPLY_ERROR_LENGTH = 200;
|
|
49
|
+
/** First retry gap after a failed poll; doubles from there. */
|
|
50
|
+
export const BACKOFF_FIRST_MS = 5_000;
|
|
51
|
+
/** Backoff ceiling — an hour-long outage should not mean hour-long silence either. */
|
|
52
|
+
export const BACKOFF_MAX_MS = 60_000;
|
|
53
|
+
|
|
54
|
+
/** Telegram's own long-poll window, in seconds, echoed into the request URL. */
|
|
55
|
+
const POLL_TIMEOUT_S = 25;
|
|
56
|
+
/** Long poll holds ~25s; the fetch deadline must be comfortably past it. */
|
|
57
|
+
const POLL_FETCH_TIMEOUT_MS = 35_000;
|
|
58
|
+
/** A reply is one small POST. */
|
|
59
|
+
const SEND_TIMEOUT_MS = 10_000;
|
|
60
|
+
/** Gap between two *successful* polls: the long poll paces itself, this only stops a hot spin against a broken proxy. */
|
|
61
|
+
const POLL_PACE_MS = 250;
|
|
62
|
+
|
|
63
|
+
/** Codes are minted as 8 lowercase hex characters. */
|
|
64
|
+
const CODE_PATTERN = /^[0-9a-f]{8}$/;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* One Telegram update, flattened from the wire shape (`update_id`,
|
|
68
|
+
* `message.chat.id`, `message.text`, `message.from.username`). Non-message and
|
|
69
|
+
* non-text updates arrive with `message` absent: they are acknowledged (offset
|
|
70
|
+
* advanced) and otherwise ignored.
|
|
71
|
+
*/
|
|
72
|
+
export interface TelegramUpdate {
|
|
73
|
+
updateId: number;
|
|
74
|
+
message?: { chatId: number; text: string; from?: string };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The sliver of the world this module touches. `writeFile` is the atomic-write
|
|
79
|
+
* seam: the default io writes temp (0600) → rename, so a reader sees the old
|
|
80
|
+
* bytes or the complete new ones, and creates missing parent dirs 0700 (the
|
|
81
|
+
* private-dir rule) — which keeps the whole module fake-able with a `Map`.
|
|
82
|
+
*/
|
|
83
|
+
export interface TelegramIo {
|
|
84
|
+
fetch(
|
|
85
|
+
url: string,
|
|
86
|
+
init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },
|
|
87
|
+
): Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;
|
|
88
|
+
readFile(path: string): Promise<string>;
|
|
89
|
+
writeFile(path: string, data: string): Promise<void>;
|
|
90
|
+
chmod(path: string, mode: number): Promise<void>;
|
|
91
|
+
exists(path: string): Promise<boolean>;
|
|
92
|
+
now(): number;
|
|
93
|
+
/** Returns an unref-able handle, so the bridge never holds the event loop open. */
|
|
94
|
+
setTimeout(cb: () => void, ms: number): { unref(): void };
|
|
95
|
+
clearTimeout(t: { unref(): void }): void;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export const defaultTelegramIo = (): TelegramIo => ({
|
|
99
|
+
fetch: async (url, init) => fetch(url, init as RequestInit | undefined),
|
|
100
|
+
readFile: (path) => readFile(path, "utf8"),
|
|
101
|
+
writeFile: async (path, data) => {
|
|
102
|
+
// 0600, temp+rename (atomic within the directory), parents 0700.
|
|
103
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
104
|
+
const temp = `${path}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
105
|
+
try {
|
|
106
|
+
await writeFile(temp, data, { encoding: "utf8", mode: 0o600 });
|
|
107
|
+
await chmod(temp, 0o600); // umask can only make this stricter, but be explicit
|
|
108
|
+
await rename(temp, path);
|
|
109
|
+
await chmod(path, 0o600);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
await unlink(temp).catch(() => undefined);
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
chmod: (path, mode) => chmod(path, mode),
|
|
116
|
+
exists: async (path) => {
|
|
117
|
+
try {
|
|
118
|
+
await stat(path);
|
|
119
|
+
return true;
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
now: () => Date.now(),
|
|
125
|
+
setTimeout: (cb, ms) => setTimeout(cb, ms),
|
|
126
|
+
clearTimeout: (t) => clearTimeout(t as NodeJS.Timeout),
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Everything that touches a session goes through this seam — the daemon wires it
|
|
131
|
+
* to the Store. The bridge never learns how a submission becomes an answer; it
|
|
132
|
+
* only submits, waits (bounded), and replies.
|
|
133
|
+
*/
|
|
134
|
+
export interface TelegramBroker {
|
|
135
|
+
/** Sessions the `/session` command may switch to, and `bind`'s default target. */
|
|
136
|
+
listSessions(): Array<{ id: string; name: string }>;
|
|
137
|
+
/** Submit text to the bound session's main agent. Throws only on an invalid session. */
|
|
138
|
+
sendToSession(sessionId: string, text: string): Promise<{ submissionId: number }>;
|
|
139
|
+
/**
|
|
140
|
+
* Wait for a turn to settle and return the agent's answer text (or undefined
|
|
141
|
+
* when it did not settle inside `timeoutMs`). The broker implements the
|
|
142
|
+
* polling; the bridge only calls it with a bounded timeout.
|
|
143
|
+
*/
|
|
144
|
+
awaitAnswer(sessionId: string, submissionId: number, timeoutMs: number): Promise<string | undefined>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** One chat bound to one session. */
|
|
148
|
+
export interface TelegramChatBinding {
|
|
149
|
+
chatId: number;
|
|
150
|
+
sessionId: string;
|
|
151
|
+
/** ISO. When this binding was made. */
|
|
152
|
+
createdAt: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** One minted `/start` code. `sessionId` is the session the code grants (the CLI's default is the first session). */
|
|
156
|
+
export interface TelegramBindCode {
|
|
157
|
+
code: string;
|
|
158
|
+
sessionId?: string;
|
|
159
|
+
/** ISO. */
|
|
160
|
+
createdAt: string;
|
|
161
|
+
/** ISO; after this the code is refused and pruned. */
|
|
162
|
+
expiresAt: string;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The on-disk document. `version` exists so a future shape can be migrated, not discarded. */
|
|
166
|
+
export interface TelegramRegistryFile {
|
|
167
|
+
version: number;
|
|
168
|
+
/** The next `offset` for getUpdates — Telegram's acknowledgement cursor. */
|
|
169
|
+
offset: number;
|
|
170
|
+
chats: TelegramChatBinding[];
|
|
171
|
+
codes: TelegramBindCode[];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export type TelegramBridgeErrorCode = "invalid";
|
|
175
|
+
|
|
176
|
+
/** Typed failure for the mutation paths (`bind`) so a UI can answer without string matching. */
|
|
177
|
+
export class TelegramBridgeError extends Error {
|
|
178
|
+
readonly code: TelegramBridgeErrorCode;
|
|
179
|
+
|
|
180
|
+
constructor(code: TelegramBridgeErrorCode, message: string) {
|
|
181
|
+
super(message);
|
|
182
|
+
this.name = "TelegramBridgeError";
|
|
183
|
+
this.code = code;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface TelegramBridgeOptions {
|
|
188
|
+
/** Where recovery / poll / delivery notices go. Defaults to `console.warn`. */
|
|
189
|
+
warn?: (message: string, error?: unknown) => void;
|
|
190
|
+
/** Injectable clock (epoch ms) — tests pin code expiry instead of sleeping. */
|
|
191
|
+
now?: () => number;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const defaultWarn = (message: string, error?: unknown): void =>
|
|
195
|
+
console.warn(`[telegram] ${message}`, error === undefined ? "" : describeError(error));
|
|
196
|
+
|
|
197
|
+
const describeError = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
|
198
|
+
|
|
199
|
+
const truncate = (text: string, max: number): string => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
200
|
+
|
|
201
|
+
/** What `/help` sends. Commands only — no session names, no device details. */
|
|
202
|
+
const CHAT_HELP = `dpi telegram commands:
|
|
203
|
+
/start <code> bind this chat to a session (code from "dpi telegram bind")
|
|
204
|
+
/stop unbind this chat
|
|
205
|
+
/status which session this chat is bound to
|
|
206
|
+
/session <prefix> switch to another session by id prefix
|
|
207
|
+
/help this list
|
|
208
|
+
|
|
209
|
+
Anything else you type goes to the bound session's agent.`;
|
|
210
|
+
|
|
211
|
+
/** 8 lowercase hex: short enough to type on a phone, wide enough not to be guessable. */
|
|
212
|
+
export function mintCode(): string {
|
|
213
|
+
return randomBytes(4).toString("hex");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const isoTime = (epochMs: number): string => new Date(epochMs).toISOString();
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Telegram's `result` array → flattened updates. Rows without a usable
|
|
220
|
+
* `update_id` are dropped (they cannot be acknowledged, so they must not be
|
|
221
|
+
* handled either); messages without text (photos, stickers) flatten to a bare
|
|
222
|
+
* update and are ignored downstream.
|
|
223
|
+
*/
|
|
224
|
+
export function flattenUpdates(rows: readonly unknown[]): TelegramUpdate[] {
|
|
225
|
+
const out: TelegramUpdate[] = [];
|
|
226
|
+
for (const row of rows) {
|
|
227
|
+
if (row === null || typeof row !== "object") continue;
|
|
228
|
+
const source = row as Record<string, unknown>;
|
|
229
|
+
const updateId = source.update_id;
|
|
230
|
+
if (typeof updateId !== "number" || !Number.isFinite(updateId)) continue;
|
|
231
|
+
let message: TelegramUpdate["message"];
|
|
232
|
+
const raw = source.message;
|
|
233
|
+
if (raw !== null && typeof raw === "object") {
|
|
234
|
+
const msg = raw as Record<string, unknown>;
|
|
235
|
+
const chat = msg.chat;
|
|
236
|
+
const chatId = chat !== null && typeof chat === "object" ? (chat as Record<string, unknown>).id : undefined;
|
|
237
|
+
if (typeof msg.text === "string" && typeof chatId === "number" && Number.isFinite(chatId)) {
|
|
238
|
+
const from = msg.from;
|
|
239
|
+
let fromName: string | undefined;
|
|
240
|
+
if (from !== null && typeof from === "object") {
|
|
241
|
+
const f = from as Record<string, unknown>;
|
|
242
|
+
fromName =
|
|
243
|
+
typeof f.username === "string" && f.username
|
|
244
|
+
? f.username
|
|
245
|
+
: typeof f.first_name === "string" && f.first_name
|
|
246
|
+
? f.first_name
|
|
247
|
+
: undefined;
|
|
248
|
+
}
|
|
249
|
+
message = { chatId: Math.trunc(chatId), text: msg.text, ...(fromName ? { from: fromName } : {}) };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
out.push({ updateId: Math.trunc(updateId), ...(message ? { message } : {}) });
|
|
253
|
+
}
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Strict enough to refuse a newer build's file, lenient enough to keep a hand-edited row's siblings. */
|
|
258
|
+
function coerceRegistry(raw: unknown, now: number): TelegramRegistryFile {
|
|
259
|
+
if (raw === null || raw === undefined || typeof raw !== "object") throw new Error("registry is not a JSON object");
|
|
260
|
+
const file = raw as Record<string, unknown>;
|
|
261
|
+
const version = file.version;
|
|
262
|
+
if (version !== undefined && version !== null && version !== TELEGRAM_REGISTRY_VERSION) {
|
|
263
|
+
throw new Error(`unsupported telegram registry version ${String(version)}`);
|
|
264
|
+
}
|
|
265
|
+
const offset =
|
|
266
|
+
typeof file.offset === "number" && Number.isFinite(file.offset) && file.offset >= 0 ? Math.floor(file.offset) : 0;
|
|
267
|
+
|
|
268
|
+
const chats: TelegramChatBinding[] = [];
|
|
269
|
+
if (file.chats !== undefined && file.chats !== null) {
|
|
270
|
+
if (!Array.isArray(file.chats)) throw new Error("registry `chats` is not a list");
|
|
271
|
+
for (const row of file.chats) {
|
|
272
|
+
if (row === null || typeof row !== "object") continue;
|
|
273
|
+
const source = row as Record<string, unknown>;
|
|
274
|
+
if (typeof source.chatId !== "number" || !Number.isFinite(source.chatId)) continue;
|
|
275
|
+
if (typeof source.sessionId !== "string" || !source.sessionId.trim()) continue;
|
|
276
|
+
const createdAt =
|
|
277
|
+
typeof source.createdAt === "string" && Number.isFinite(Date.parse(source.createdAt))
|
|
278
|
+
? source.createdAt
|
|
279
|
+
: isoTime(now);
|
|
280
|
+
chats.push({ chatId: Math.trunc(source.chatId), sessionId: source.sessionId, createdAt });
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const codes: TelegramBindCode[] = [];
|
|
285
|
+
if (file.codes !== undefined && file.codes !== null) {
|
|
286
|
+
if (!Array.isArray(file.codes)) throw new Error("registry `codes` is not a list");
|
|
287
|
+
for (const row of file.codes) {
|
|
288
|
+
if (row === null || typeof row !== "object") continue;
|
|
289
|
+
const source = row as Record<string, unknown>;
|
|
290
|
+
if (typeof source.code !== "string" || !CODE_PATTERN.test(source.code.toLowerCase())) continue;
|
|
291
|
+
if (typeof source.expiresAt !== "string" || !Number.isFinite(Date.parse(source.expiresAt))) continue;
|
|
292
|
+
const sessionId = typeof source.sessionId === "string" && source.sessionId.trim() ? source.sessionId : undefined;
|
|
293
|
+
const createdAt =
|
|
294
|
+
typeof source.createdAt === "string" && Number.isFinite(Date.parse(source.createdAt))
|
|
295
|
+
? source.createdAt
|
|
296
|
+
: isoTime(now);
|
|
297
|
+
codes.push({
|
|
298
|
+
code: source.code.toLowerCase(),
|
|
299
|
+
...(sessionId ? { sessionId } : {}),
|
|
300
|
+
createdAt,
|
|
301
|
+
expiresAt: source.expiresAt,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
return { version: TELEGRAM_REGISTRY_VERSION, offset, chats, codes };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The Telegram side of the bridge: one registry file, one long-poll loop, one
|
|
311
|
+
* chat-to-session binding at a time.
|
|
312
|
+
*
|
|
313
|
+
* The loop is started with `start(token)` and stopped with `stop()` or by
|
|
314
|
+
* Telegram rejecting the token; timers are unref'd, so a running bridge never
|
|
315
|
+
* keeps the process alive on its own. `open` never throws — an unreadable
|
|
316
|
+
* registry is recovered from `.bak` or started empty, with a warning either way.
|
|
317
|
+
* Mutations are serialized (notify-sinks' `run` queue) so the poll's offset
|
|
318
|
+
* write cannot interleave with a CLI `bind`.
|
|
319
|
+
*/
|
|
320
|
+
export class TelegramBridge {
|
|
321
|
+
/** Absolute path of the main JSON file. */
|
|
322
|
+
readonly filePath: string;
|
|
323
|
+
/** The rolling backup restored by `open` when `filePath` is unusable. */
|
|
324
|
+
readonly backupPath: string;
|
|
325
|
+
|
|
326
|
+
private readonly io: TelegramIo;
|
|
327
|
+
private readonly broker: TelegramBroker;
|
|
328
|
+
private readonly warn: (message: string, error?: unknown) => void;
|
|
329
|
+
private readonly now: () => number;
|
|
330
|
+
private offset = 0;
|
|
331
|
+
private chats: TelegramChatBinding[] = [];
|
|
332
|
+
private codes: TelegramBindCode[] = [];
|
|
333
|
+
/** False until a good file is read or written: while false, `.bak` must not be refreshed from a bad main. */
|
|
334
|
+
private mainIsGood = false;
|
|
335
|
+
private runningValue = false;
|
|
336
|
+
private token?: string;
|
|
337
|
+
private timer?: { unref(): void };
|
|
338
|
+
private backoffMs = 0;
|
|
339
|
+
private queue: Promise<unknown> = Promise.resolve();
|
|
340
|
+
|
|
341
|
+
private constructor(filePath: string, io: TelegramIo, broker: TelegramBroker, options: TelegramBridgeOptions) {
|
|
342
|
+
this.filePath = resolve(filePath);
|
|
343
|
+
this.backupPath = `${this.filePath}.bak`;
|
|
344
|
+
this.io = io;
|
|
345
|
+
this.broker = broker;
|
|
346
|
+
this.warn = options.warn ?? defaultWarn;
|
|
347
|
+
this.now = options.now ?? (() => this.io.now());
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Load the registry (or recover), never throwing: a broken file must not break the device. */
|
|
351
|
+
static async open(
|
|
352
|
+
filePath: string,
|
|
353
|
+
io: TelegramIo,
|
|
354
|
+
broker: TelegramBroker,
|
|
355
|
+
options: TelegramBridgeOptions = {},
|
|
356
|
+
): Promise<TelegramBridge> {
|
|
357
|
+
const bridge = new TelegramBridge(filePath, io, broker, options);
|
|
358
|
+
try {
|
|
359
|
+
await bridge.load();
|
|
360
|
+
} catch (error) {
|
|
361
|
+
bridge.warn(`could not load ${bridge.filePath}: ${describeError(error)}`, error);
|
|
362
|
+
}
|
|
363
|
+
return bridge;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** True while the poll loop is scheduled or in flight. */
|
|
367
|
+
get running(): boolean {
|
|
368
|
+
return this.runningValue;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Begin polling if not already; a second `start` (even with a new token) changes nothing. */
|
|
372
|
+
start(token: string): void {
|
|
373
|
+
if (this.runningValue) return;
|
|
374
|
+
this.token = token;
|
|
375
|
+
this.runningValue = true;
|
|
376
|
+
this.backoffMs = 0;
|
|
377
|
+
this.schedule(0);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Stop the loop and clear the pending timer. Safe to call when stopped. */
|
|
381
|
+
stop(): void {
|
|
382
|
+
this.runningValue = false;
|
|
383
|
+
this.clearTimer();
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* The bridge's own state, for `dpi telegram status`. Session names resolve
|
|
388
|
+
* through the broker; a session the broker no longer lists falls back to its
|
|
389
|
+
* id (the binding stays — the operator may just have the daemon down).
|
|
390
|
+
*/
|
|
391
|
+
status(): {
|
|
392
|
+
running: boolean;
|
|
393
|
+
chats: Array<{ chatId: number; sessionId: string; sessionName?: string }>;
|
|
394
|
+
pendingCodes: number;
|
|
395
|
+
} {
|
|
396
|
+
const sessions = this.safeListSessions();
|
|
397
|
+
const now = this.now();
|
|
398
|
+
return {
|
|
399
|
+
running: this.runningValue,
|
|
400
|
+
chats: this.chats.map((binding) => {
|
|
401
|
+
const found = sessions.find((session) => session.id === binding.sessionId);
|
|
402
|
+
return {
|
|
403
|
+
chatId: binding.chatId,
|
|
404
|
+
sessionId: binding.sessionId,
|
|
405
|
+
...(found ? { sessionName: found.name } : {}),
|
|
406
|
+
};
|
|
407
|
+
}),
|
|
408
|
+
pendingCodes: this.codes.filter((code) => Date.parse(code.expiresAt) > now).length,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Mint a single-use bind code into the registry. Without `sessionId` the
|
|
414
|
+
* code targets the first session the broker lists — or none at all when the
|
|
415
|
+
* broker has no sessions to name (the CLI minting while the daemon is down),
|
|
416
|
+
* in which case `/start` resolves "first session" against the *live* broker
|
|
417
|
+
* when the code is spent. An explicit `sessionId` that the broker does not
|
|
418
|
+
* list throws `TelegramBridgeError`; a failed registry write rejects, leaving
|
|
419
|
+
* the registry exactly as it was.
|
|
420
|
+
*/
|
|
421
|
+
async bind(sessionId?: string): Promise<{ code: string; expiresAt: string }> {
|
|
422
|
+
const sessions = this.safeListSessions();
|
|
423
|
+
let targetId: string | undefined;
|
|
424
|
+
if (sessionId === undefined) {
|
|
425
|
+
targetId = sessions[0]?.id;
|
|
426
|
+
} else {
|
|
427
|
+
if (!sessions.some((session) => session.id === sessionId)) {
|
|
428
|
+
throw new TelegramBridgeError("invalid", `no session ${sessionId}`);
|
|
429
|
+
}
|
|
430
|
+
targetId = sessionId;
|
|
431
|
+
}
|
|
432
|
+
return this.run(async () => {
|
|
433
|
+
const now = this.now();
|
|
434
|
+
const draft = this.snapshot();
|
|
435
|
+
draft.codes = draft.codes.filter((code) => Date.parse(code.expiresAt) > now); // prune the dead ones
|
|
436
|
+
let code = mintCode();
|
|
437
|
+
while (draft.codes.some((row) => row.code === code)) code = mintCode();
|
|
438
|
+
const record: TelegramBindCode = {
|
|
439
|
+
code,
|
|
440
|
+
...(targetId ? { sessionId: targetId } : {}),
|
|
441
|
+
createdAt: isoTime(now),
|
|
442
|
+
expiresAt: isoTime(now + CODE_TTL_MS),
|
|
443
|
+
};
|
|
444
|
+
draft.codes.push(record);
|
|
445
|
+
await this.persist(draft);
|
|
446
|
+
this.adopt(draft);
|
|
447
|
+
return { code: record.code, expiresAt: record.expiresAt };
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Remove the first binding whose chat id starts with `chatPrefix`; returns the chat id, or undefined when none matched. */
|
|
452
|
+
async unbind(chatPrefix: string): Promise<number | undefined> {
|
|
453
|
+
return this.run(async () => {
|
|
454
|
+
const draft = this.snapshot();
|
|
455
|
+
const hit = draft.chats.find((binding) => String(binding.chatId).startsWith(chatPrefix));
|
|
456
|
+
if (hit === undefined) return undefined;
|
|
457
|
+
draft.chats = draft.chats.filter((binding) => binding !== hit);
|
|
458
|
+
await this.persist(draft);
|
|
459
|
+
this.adopt(draft);
|
|
460
|
+
return hit.chatId;
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** The sessions a chat can switch between (the broker's answer, copied). */
|
|
465
|
+
sessions(): Array<{ id: string; name: string }> {
|
|
466
|
+
return this.safeListSessions().map((session) => ({ ...session }));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ------------------------------------------------------------- load/persist
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Main → `.bak` → empty, the notify-sinks ladder. An unusable main is copied
|
|
473
|
+
* to `<file>.corrupt-<ts>` (kept, never deleted) and, when the copy landed,
|
|
474
|
+
* overwritten with the recovered state so the next boot does not re-recover.
|
|
475
|
+
*/
|
|
476
|
+
private async load(): Promise<void> {
|
|
477
|
+
const main = await this.readRegistry(this.filePath);
|
|
478
|
+
if (main.ok) {
|
|
479
|
+
this.adopt(main.file);
|
|
480
|
+
this.mainIsGood = true;
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (main.missing) return; // fresh device: nothing configured yet, nothing to complain about
|
|
484
|
+
|
|
485
|
+
this.warn(`${this.filePath} is unusable (${describeError(main.error)}); moving it aside`);
|
|
486
|
+
const keptAside = main.text === undefined ? false : await this.keepCorruptCopy(main.text);
|
|
487
|
+
const backup = await this.readRegistry(this.backupPath);
|
|
488
|
+
const recovered = backup.ok
|
|
489
|
+
? backup.file
|
|
490
|
+
: ({ version: TELEGRAM_REGISTRY_VERSION, offset: 0, chats: [], codes: [] } satisfies TelegramRegistryFile);
|
|
491
|
+
this.adopt(recovered);
|
|
492
|
+
if (backup.ok) this.warn(`recovered ${backup.file.chats.length} chat binding(s) from ${this.backupPath}`);
|
|
493
|
+
else if (!backup.missing) this.warn(`${this.backupPath} is unusable too; starting with an empty registry`);
|
|
494
|
+
|
|
495
|
+
if (!keptAside) {
|
|
496
|
+
this.warn(`${this.filePath} was left untouched — fix or remove it before the next change`);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
try {
|
|
500
|
+
await this.run(async () => {
|
|
501
|
+
await this.persist(recovered);
|
|
502
|
+
});
|
|
503
|
+
} catch (error) {
|
|
504
|
+
this.warn(`could not rewrite ${this.filePath} after recovery`, error);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
private async readRegistry(
|
|
509
|
+
path: string,
|
|
510
|
+
): Promise<{ ok: true; file: TelegramRegistryFile } | { ok: false; missing: boolean; text?: string; error?: unknown }> {
|
|
511
|
+
if (!(await this.io.exists(path))) return { ok: false, missing: true };
|
|
512
|
+
let text: string;
|
|
513
|
+
try {
|
|
514
|
+
text = await this.io.readFile(path);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
return { ok: false, missing: false, error };
|
|
517
|
+
}
|
|
518
|
+
try {
|
|
519
|
+
return { ok: true, file: coerceRegistry(JSON.parse(text), this.now()) };
|
|
520
|
+
} catch (error) {
|
|
521
|
+
return { ok: false, missing: false, text, error };
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Keep the unusable bytes somewhere a human can inspect; false when even that failed. */
|
|
526
|
+
private async keepCorruptCopy(text: string): Promise<boolean> {
|
|
527
|
+
const aside = `${this.filePath}.corrupt-${this.now()}`;
|
|
528
|
+
try {
|
|
529
|
+
await this.io.writeFile(aside, text);
|
|
530
|
+
await this.io.chmod(aside, 0o600);
|
|
531
|
+
this.warn(`kept the unusable registry as ${aside}`);
|
|
532
|
+
return true;
|
|
533
|
+
} catch (error) {
|
|
534
|
+
this.warn(`could not keep a copy at ${aside}`, error);
|
|
535
|
+
return false;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private snapshot(): TelegramRegistryFile {
|
|
540
|
+
return {
|
|
541
|
+
version: TELEGRAM_REGISTRY_VERSION,
|
|
542
|
+
offset: this.offset,
|
|
543
|
+
chats: this.chats.map((binding) => ({ ...binding })),
|
|
544
|
+
codes: this.codes.map((code) => ({ ...code })),
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
private adopt(file: TelegramRegistryFile): void {
|
|
549
|
+
this.offset = file.offset;
|
|
550
|
+
this.chats = file.chats.map((binding) => ({ ...binding }));
|
|
551
|
+
this.codes = file.codes.map((code) => ({ ...code }));
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** Stage → persist → swap. A failed write leaves memory exactly as it was. */
|
|
555
|
+
private commit(apply: (draft: TelegramRegistryFile) => void): Promise<void> {
|
|
556
|
+
return this.run(async () => {
|
|
557
|
+
const draft = this.snapshot();
|
|
558
|
+
apply(draft);
|
|
559
|
+
await this.persist(draft);
|
|
560
|
+
this.adopt(draft);
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
private run<T>(task: () => Promise<T>): Promise<T> {
|
|
565
|
+
const started = this.queue.then(task, task);
|
|
566
|
+
// Swallow the rejection on the chain only; the caller still sees it.
|
|
567
|
+
this.queue = started.then(
|
|
568
|
+
() => undefined,
|
|
569
|
+
() => undefined,
|
|
570
|
+
);
|
|
571
|
+
return started;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* `.bak` refreshed from the current good main first (best effort), then the
|
|
576
|
+
* new bytes through the io's atomic write, then 0600.
|
|
577
|
+
*/
|
|
578
|
+
private async persist(draft: TelegramRegistryFile): Promise<void> {
|
|
579
|
+
if (this.mainIsGood && (await this.io.exists(this.filePath))) {
|
|
580
|
+
try {
|
|
581
|
+
const previous = await this.io.readFile(this.filePath);
|
|
582
|
+
await this.io.writeFile(this.backupPath, previous);
|
|
583
|
+
await this.io.chmod(this.backupPath, 0o600);
|
|
584
|
+
} catch (error) {
|
|
585
|
+
this.warn(`could not refresh ${this.backupPath}`, error);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const payload = `${JSON.stringify(draft satisfies TelegramRegistryFile, null, 2)}\n`;
|
|
589
|
+
await this.io.writeFile(this.filePath, payload);
|
|
590
|
+
await this.io.chmod(this.filePath, 0o600);
|
|
591
|
+
this.mainIsGood = true;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// --------------------------------------------------------------- poll loop
|
|
595
|
+
|
|
596
|
+
private schedule(ms: number): void {
|
|
597
|
+
this.clearTimer();
|
|
598
|
+
const timer = this.io.setTimeout(() => {
|
|
599
|
+
this.timer = undefined;
|
|
600
|
+
void this.poll();
|
|
601
|
+
}, ms);
|
|
602
|
+
timer.unref(); // a bridge timer must never hold the process open
|
|
603
|
+
this.timer = timer;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
private clearTimer(): void {
|
|
607
|
+
if (this.timer === undefined) return;
|
|
608
|
+
const timer = this.timer;
|
|
609
|
+
this.timer = undefined;
|
|
610
|
+
this.io.clearTimeout(timer);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
private api(method: string): string {
|
|
614
|
+
return `https://api.telegram.org/bot${this.token}/${method}`;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* One long poll: fetch, walk the updates in order, schedule the next one.
|
|
619
|
+
* Errors back off 5s→10s→…→60s; success resets the ladder. A 401/404 (bad
|
|
620
|
+
* token) stops the loop instead of retrying — retrying a rejected token is
|
|
621
|
+
* just noise with an API call attached.
|
|
622
|
+
*/
|
|
623
|
+
private async poll(): Promise<void> {
|
|
624
|
+
if (!this.runningValue || this.token === undefined) return;
|
|
625
|
+
try {
|
|
626
|
+
const res = await this.io.fetch(`${this.api("getUpdates")}?timeout=${POLL_TIMEOUT_S}&offset=${this.offset}`, {
|
|
627
|
+
method: "GET",
|
|
628
|
+
signal: AbortSignal.timeout(POLL_FETCH_TIMEOUT_MS),
|
|
629
|
+
});
|
|
630
|
+
if (res.status === 401 || res.status === 404) {
|
|
631
|
+
this.warn(`DPI_TELEGRAM_TOKEN rejected (HTTP ${res.status}) — the telegram bridge stopped; check the token`);
|
|
632
|
+
this.stop();
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
if (!res.ok) throw new Error(`getUpdates answered HTTP ${res.status}`);
|
|
636
|
+
const body = (await res.json()) as { ok?: unknown; result?: unknown };
|
|
637
|
+
if (body === null || typeof body !== "object" || body.ok !== true || !Array.isArray(body.result)) {
|
|
638
|
+
throw new Error("getUpdates did not answer an ok result list");
|
|
639
|
+
}
|
|
640
|
+
this.backoffMs = 0;
|
|
641
|
+
for (const update of flattenUpdates(body.result)) {
|
|
642
|
+
if (!this.runningValue) return; // stopped mid-batch (bad token, stop()): drop the rest
|
|
643
|
+
try {
|
|
644
|
+
await this.handle(update);
|
|
645
|
+
} catch (error) {
|
|
646
|
+
// Includes a failed offset persist: the update is re-delivered by the
|
|
647
|
+
// next poll, which is the safe direction to err in.
|
|
648
|
+
this.warn(`update ${update.updateId} was not handled: ${describeError(error)}`, error);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
} catch (error) {
|
|
652
|
+
this.backoffMs = this.backoffMs === 0 ? BACKOFF_FIRST_MS : Math.min(this.backoffMs * 2, BACKOFF_MAX_MS);
|
|
653
|
+
this.warn(`getUpdates failed (${describeError(error)}); retrying in ${this.backoffMs / 1000}s`, error);
|
|
654
|
+
if (this.runningValue) this.schedule(this.backoffMs);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (this.runningValue) this.schedule(POLL_PACE_MS);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Acknowledge first (persist the new offset), then handle. Never both-half-heartedly. */
|
|
661
|
+
private async handle(update: TelegramUpdate): Promise<void> {
|
|
662
|
+
await this.commit((draft) => {
|
|
663
|
+
draft.offset = Math.max(draft.offset, update.updateId + 1);
|
|
664
|
+
});
|
|
665
|
+
if (!update.message) return; // non-message or non-text: acknowledged, ignored
|
|
666
|
+
await this.dispatch(update.message.chatId, update.message.from, update.message.text);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* One message. Commands are exact (case-insensitive) matches; everything else
|
|
671
|
+
* is plain text — including unknown `/words`, which the bound agent can
|
|
672
|
+
* answer better than a canned "unknown command".
|
|
673
|
+
*/
|
|
674
|
+
private async dispatch(chatId: number, _from: string | undefined, rawText: string): Promise<void> {
|
|
675
|
+
const text = rawText.trim();
|
|
676
|
+
const lower = text.toLowerCase();
|
|
677
|
+
|
|
678
|
+
if (lower === "/help") {
|
|
679
|
+
await this.reply(chatId, CHAT_HELP);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (lower === "/stop") {
|
|
683
|
+
await this.commit((draft) => {
|
|
684
|
+
draft.chats = draft.chats.filter((binding) => binding.chatId !== chatId);
|
|
685
|
+
});
|
|
686
|
+
await this.reply(chatId, "unbound");
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
if (lower === "/status") {
|
|
690
|
+
const binding = this.bindingOf(chatId);
|
|
691
|
+
await this.reply(chatId, binding ? this.sessionNameOf(binding.sessionId) : "not bound");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
if (lower === "/start" || lower.startsWith("/start ")) {
|
|
695
|
+
await this.cmdStart(chatId, text);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (lower === "/session" || lower.startsWith("/session ")) {
|
|
699
|
+
await this.cmdSession(chatId, text);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const binding = this.bindingOf(chatId);
|
|
704
|
+
if (!binding) return; // unbound chat: drop silently — a stranger learns nothing
|
|
705
|
+
try {
|
|
706
|
+
const { submissionId } = await this.broker.sendToSession(binding.sessionId, text);
|
|
707
|
+
const answer = await this.broker.awaitAnswer(binding.sessionId, submissionId, ANSWER_TIMEOUT_MS);
|
|
708
|
+
await this.reply(chatId, answer && answer.trim() ? answer : "no answer within 2 minutes");
|
|
709
|
+
} catch (error) {
|
|
710
|
+
await this.reply(chatId, truncate(describeError(error), MAX_REPLY_ERROR_LENGTH));
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/** `/start <code>`: single-use, 10-minute code → bind this chat to the code's session. */
|
|
715
|
+
private async cmdStart(chatId: number, text: string): Promise<void> {
|
|
716
|
+
const code = text.slice("/start".length).trim().toLowerCase();
|
|
717
|
+
const now = this.now();
|
|
718
|
+
const hit = CODE_PATTERN.test(code) ? this.codes.find((row) => row.code === code && Date.parse(row.expiresAt) > now) : undefined;
|
|
719
|
+
const sessionId = hit?.sessionId ?? (hit ? this.safeListSessions()[0]?.id : undefined);
|
|
720
|
+
if (!sessionId) {
|
|
721
|
+
await this.reply(chatId, "unknown or expired code");
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
await this.commit((draft) => {
|
|
725
|
+
draft.codes = draft.codes.filter((row) => row.code !== code); // single use, spent now
|
|
726
|
+
draft.chats = [
|
|
727
|
+
...draft.chats.filter((binding) => binding.chatId !== chatId),
|
|
728
|
+
{ chatId, sessionId, createdAt: isoTime(now) },
|
|
729
|
+
];
|
|
730
|
+
});
|
|
731
|
+
await this.reply(chatId, `bound to ${this.sessionNameOf(sessionId)}`);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** `/session <prefix>`: switch the *bound* chat to the first session whose id starts with the prefix. */
|
|
735
|
+
private async cmdSession(chatId: number, text: string): Promise<void> {
|
|
736
|
+
if (!this.bindingOf(chatId)) {
|
|
737
|
+
await this.reply(chatId, "not bound");
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
const prefix = text.slice("/session".length).trim();
|
|
741
|
+
const target = this.safeListSessions().find((session) => session.id.startsWith(prefix));
|
|
742
|
+
if (!target) {
|
|
743
|
+
await this.reply(chatId, "no such session");
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
await this.commit((draft) => {
|
|
747
|
+
const row = draft.chats.find((binding) => binding.chatId === chatId);
|
|
748
|
+
if (row) row.sessionId = target.id;
|
|
749
|
+
});
|
|
750
|
+
await this.reply(chatId, target.name);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** Best-effort reply: a failed sendMessage is warned and forgotten — the turn already happened. */
|
|
754
|
+
private async reply(chatId: number, text: string): Promise<void> {
|
|
755
|
+
if (this.token === undefined) return;
|
|
756
|
+
try {
|
|
757
|
+
const res = await this.io.fetch(this.api("sendMessage"), {
|
|
758
|
+
method: "POST",
|
|
759
|
+
headers: { "content-type": "application/json" },
|
|
760
|
+
body: JSON.stringify({ chat_id: chatId, text }),
|
|
761
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
762
|
+
});
|
|
763
|
+
if (!res.ok) this.warn(`sendMessage to chat ${chatId} answered HTTP ${res.status}`);
|
|
764
|
+
} catch (error) {
|
|
765
|
+
this.warn(`sendMessage to chat ${chatId} failed: ${describeError(error)}`, error);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// ----------------------------------------------------------------- helpers
|
|
770
|
+
|
|
771
|
+
private bindingOf(chatId: number): TelegramChatBinding | undefined {
|
|
772
|
+
return this.chats.find((binding) => binding.chatId === chatId);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** The name a human reads; a session the broker no longer lists falls back to its id. */
|
|
776
|
+
private sessionNameOf(sessionId: string): string {
|
|
777
|
+
return this.safeListSessions().find((session) => session.id === sessionId)?.name ?? sessionId;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** The broker is injected; a broken one must degrade to "no sessions", not kill the loop. */
|
|
781
|
+
private safeListSessions(): Array<{ id: string; name: string }> {
|
|
782
|
+
try {
|
|
783
|
+
return this.broker.listSessions().map((session) => ({ id: String(session.id), name: String(session.name) }));
|
|
784
|
+
} catch (error) {
|
|
785
|
+
this.warn(`listSessions failed: ${describeError(error)}`, error);
|
|
786
|
+
return [];
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|