wherever-dev 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/assistant-channels.d.ts +242 -0
- package/dist/assistant-channels.d.ts.map +1 -0
- package/dist/assistant-channels.js +270 -0
- package/dist/assistant-channels.js.map +1 -0
- package/dist/assistant-controller.d.ts +228 -0
- package/dist/assistant-controller.d.ts.map +1 -0
- package/dist/assistant-controller.js +314 -0
- package/dist/assistant-controller.js.map +1 -0
- package/dist/assistant-cron.d.ts +87 -0
- package/dist/assistant-cron.d.ts.map +1 -0
- package/dist/assistant-cron.js +352 -0
- package/dist/assistant-cron.js.map +1 -0
- package/dist/assistant-folder.d.ts +161 -0
- package/dist/assistant-folder.d.ts.map +1 -0
- package/dist/assistant-folder.js +333 -0
- package/dist/assistant-folder.js.map +1 -0
- package/dist/assistant-schedule.d.ts +236 -0
- package/dist/assistant-schedule.d.ts.map +1 -0
- package/dist/assistant-schedule.js +454 -0
- package/dist/assistant-schedule.js.map +1 -0
- package/dist/assistant-scheduler.d.ts +210 -0
- package/dist/assistant-scheduler.d.ts.map +1 -0
- package/dist/assistant-scheduler.js +472 -0
- package/dist/assistant-scheduler.js.map +1 -0
- package/dist/assistant-tool-text.d.ts +40 -0
- package/dist/assistant-tool-text.d.ts.map +1 -0
- package/dist/assistant-tool-text.js +102 -0
- package/dist/assistant-tool-text.js.map +1 -0
- package/dist/assistant-tools.d.ts +207 -0
- package/dist/assistant-tools.d.ts.map +1 -0
- package/dist/assistant-tools.js +390 -0
- package/dist/assistant-tools.js.map +1 -0
- package/dist/attach-file-tool.d.ts +20 -1
- package/dist/attach-file-tool.d.ts.map +1 -1
- package/dist/attach-file-tool.js +45 -3
- package/dist/attach-file-tool.js.map +1 -1
- package/dist/cli-requests.d.ts +90 -0
- package/dist/cli-requests.d.ts.map +1 -0
- package/dist/cli-requests.js +75 -0
- package/dist/cli-requests.js.map +1 -0
- package/dist/download-grants.d.ts +12 -0
- package/dist/download-grants.d.ts.map +1 -0
- package/dist/download-grants.js +76 -0
- package/dist/download-grants.js.map +1 -0
- package/dist/index.js +431 -20
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +43 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/reply-routing.d.ts +106 -0
- package/dist/reply-routing.d.ts.map +1 -0
- package/dist/reply-routing.js +174 -0
- package/dist/reply-routing.js.map +1 -0
- package/dist/session-pool.d.ts +243 -4
- package/dist/session-pool.d.ts.map +1 -1
- package/dist/session-pool.js +464 -100
- package/dist/session-pool.js.map +1 -1
- package/dist/telegram-channel.d.ts +272 -0
- package/dist/telegram-channel.d.ts.map +1 -0
- package/dist/telegram-channel.js +701 -0
- package/dist/telegram-channel.js.map +1 -0
- package/dist/telegram-files.d.ts +101 -0
- package/dist/telegram-files.d.ts.map +1 -0
- package/dist/telegram-files.js +145 -0
- package/dist/telegram-files.js.map +1 -0
- package/dist/telegram-pairing.d.ts +119 -0
- package/dist/telegram-pairing.d.ts.map +1 -0
- package/dist/telegram-pairing.js +97 -0
- package/dist/telegram-pairing.js.map +1 -0
- package/dist/telegram-replies.d.ts +94 -0
- package/dist/telegram-replies.d.ts.map +1 -0
- package/dist/telegram-replies.js +329 -0
- package/dist/telegram-replies.js.map +1 -0
- package/dist/telegram-token.d.ts +55 -0
- package/dist/telegram-token.d.ts.map +1 -0
- package/dist/telegram-token.js +86 -0
- package/dist/telegram-token.js.map +1 -0
- package/dist/web-push.d.ts +167 -0
- package/dist/web-push.d.ts.map +1 -0
- package/dist/web-push.js +387 -0
- package/dist/web-push.js.map +1 -0
- package/package.json +1 -1
- package/public/_app/immutable/assets/0.BkzT3rFr.css +1 -0
- package/public/_app/immutable/chunks/CExVgK9Z.js +2 -0
- package/public/_app/immutable/chunks/CExVgK9Z.js.map +1 -0
- package/public/_app/immutable/chunks/CkOw6fRa.js +2 -0
- package/public/_app/immutable/chunks/{idnZrCTB.js.map → CkOw6fRa.js.map} +1 -1
- package/public/_app/immutable/chunks/DyHllYtq.js +2 -0
- package/public/_app/immutable/chunks/{DJMI34rR.js.map → DyHllYtq.js.map} +1 -1
- package/public/_app/immutable/entry/{app.CF_gzWKW.js → app.D3PEFbtP.js} +3 -3
- package/public/_app/immutable/entry/{app.CF_gzWKW.js.map → app.D3PEFbtP.js.map} +1 -1
- package/public/_app/immutable/entry/start.BR00Qps5.js +2 -0
- package/public/_app/immutable/entry/start.BR00Qps5.js.map +1 -0
- package/public/_app/immutable/nodes/{0.CIIhZFWl.js → 0.DG3L8hMN.js} +3 -3
- package/public/_app/immutable/nodes/{0.CIIhZFWl.js.map → 0.DG3L8hMN.js.map} +1 -1
- package/public/_app/immutable/nodes/{1.D4WVeMej.js → 1.BCpuoZxW.js} +2 -2
- package/public/_app/immutable/nodes/{1.D4WVeMej.js.map → 1.BCpuoZxW.js.map} +1 -1
- package/public/_app/immutable/nodes/2.D2auiZW1.js +122 -0
- package/public/_app/immutable/nodes/2.D2auiZW1.js.map +1 -0
- package/public/_app/version.json +1 -1
- package/public/index.html +11 -11
- package/public/service-worker.js +1 -1
- package/public/_app/immutable/assets/0.BKJ49K71.css +0 -1
- package/public/_app/immutable/chunks/CkzyFwPn.js +0 -2
- package/public/_app/immutable/chunks/CkzyFwPn.js.map +0 -1
- package/public/_app/immutable/chunks/DJMI34rR.js +0 -2
- package/public/_app/immutable/chunks/idnZrCTB.js +0 -2
- package/public/_app/immutable/entry/start.GpPJ13Gr.js +0 -2
- package/public/_app/immutable/entry/start.GpPJ13Gr.js.map +0 -1
- package/public/_app/immutable/nodes/2._KcrsFWH.js +0 -120
- package/public/_app/immutable/nodes/2._KcrsFWH.js.map +0 -1
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { applyPairing, decideInbound, effectivePairing, generatePairingCode, initialPairingState, parseCommand, repair as repairState, } from './telegram-pairing.js';
|
|
4
|
+
import { TelegramReplies, splitTelegramText } from './telegram-replies.js';
|
|
5
|
+
import { FILES_UNAVAILABLE_REPLY, TELEGRAM_DOWNLOAD_MAX_BYTES, UNSUPPORTED_MEDIA_REPLY, hasUnsupportedMedia, inboundFailedNote, inboundFilesOf, inboundTooLargeNote, saveUploaded, } from './telegram-files.js';
|
|
6
|
+
/**
|
|
7
|
+
* The assistant's TELEGRAM channel: the secure base (task
|
|
8
|
+
* `telegram-token-and-pairing`: token, polling, pairing) and the CONVERSATION
|
|
9
|
+
* (task `telegram-conversation`):
|
|
10
|
+
*
|
|
11
|
+
* - INBOUND, from the paired user only (telegram-pairing.ts): `stop` / `/stop`
|
|
12
|
+
* aborts the running turn; `/new` / `/reset` reset the assistant (the
|
|
13
|
+
* controller's reset, never sent to pi); `!` / `!!` text is refused with an
|
|
14
|
+
* explanation (it never reaches the pool's shell path); anything else,
|
|
15
|
+
* including other `/` text such as `/skill:`, goes to the controller
|
|
16
|
+
* untouched (the origin `telegram` rides the pool's routing queue, never a
|
|
17
|
+
* text prefix). Into a running turn it STEERS (ADR 0003), shown by a
|
|
18
|
+
* `STEER_REACTION` on the user's message, or, when reactions are refused,
|
|
19
|
+
* the short `STEER_NOTE`. Each message is handled once it is DISPATCHED
|
|
20
|
+
* (not when its turn ends), so messages keep their order and polling goes on.
|
|
21
|
+
* - REPLIES: output whose current destination is `telegram` (ADR 0014), from
|
|
22
|
+
* the dispatcher, streamed and split by telegram-replies.ts.
|
|
23
|
+
* - NOTIFY (`assistant_notify`): its OWN message `🔔 <source>: <title>`, the
|
|
24
|
+
* body below, then a link to the target session when `publicUrl` is
|
|
25
|
+
* configured; sent at once, even mid-reply, never folded into a reply.
|
|
26
|
+
* - DROPPED messages (a reset, an aborted settle): reported back as a list.
|
|
27
|
+
* - FILES (task `telegram-files`, telegram-files.ts): a photo or a document
|
|
28
|
+
* (an ALBUM is its messages gathered for `mediaGroupDelayMs`, then handled as
|
|
29
|
+
* one message) is downloaded into the upload dir and reaches the assistant as
|
|
30
|
+
* paths in the text, as a web upload does; its caption is the text. An
|
|
31
|
+
* `attach_file` in a Telegram-routed reply sends the file back.
|
|
32
|
+
*
|
|
33
|
+
* Bot API LONG POLLING (`getUpdates` with a server-side `timeout`), the
|
|
34
|
+
* mechanics ported from the MIT `badlogic/pi-telegram` extension, but NOT its
|
|
35
|
+
* pairing (it pairs whoever sends the first `/start`): pairing is the one-time
|
|
36
|
+
* code of telegram-pairing.ts.
|
|
37
|
+
*
|
|
38
|
+
* State, in the STATE dir (ADR 0006), mode 0600, atomic tmp + rename:
|
|
39
|
+
* - `assistant-telegram-offset.json` `{botId, offset}`: the next `getUpdates`
|
|
40
|
+
* offset, written after EACH handled update, so a restart neither replays
|
|
41
|
+
* (Telegram drops everything below the offset) nor loses an update (a crash
|
|
42
|
+
* between handling and writing replays at most that one). It is bound to the
|
|
43
|
+
* bot id (the token's numeric prefix): update ids are per bot, so an offset
|
|
44
|
+
* left by another bot is ignored rather than used to skip the new bot's updates.
|
|
45
|
+
* - `assistant-telegram-pairing.json`: the paired user (`PairedUser`).
|
|
46
|
+
* The one-time code lives in memory only (a restart issues a new one), so an
|
|
47
|
+
* unpaired channel writes nothing until someone pairs.
|
|
48
|
+
*
|
|
49
|
+
* Built only while the assistant is ACTIVE (configured AND this server holds the
|
|
50
|
+
* folder lock: two servers must never poll the same bot) AND
|
|
51
|
+
* `assistantTelegram.enabled` is true AND a token resolved (telegram-token.ts);
|
|
52
|
+
* see `server/src/index.ts`.
|
|
53
|
+
*
|
|
54
|
+
* Failure handling: a 401 / 404 from the Bot API means the token is wrong; the
|
|
55
|
+
* channel stops polling and reports `error` (a restart with a fixed token is the
|
|
56
|
+
* cure). Any other failure (network, 409 another poller or a webhook, 429, 5xx)
|
|
57
|
+
* is logged and retried with backoff (honouring `retry_after`).
|
|
58
|
+
*/
|
|
59
|
+
export const TELEGRAM_CHANNEL = 'telegram';
|
|
60
|
+
export const TELEGRAM_OFFSET_FILE = 'assistant-telegram-offset.json';
|
|
61
|
+
export const TELEGRAM_PAIRING_FILE = 'assistant-telegram-pairing.json';
|
|
62
|
+
export const TELEGRAM_API_BASE = 'https://api.telegram.org';
|
|
63
|
+
/** How long an album's messages are gathered before it is handled (pi-telegram's 1200 ms). */
|
|
64
|
+
export const MEDIA_GROUP_DELAY_MS = 1200;
|
|
65
|
+
/** The reaction marking a message that STEERED the running turn (one of Telegram's allowed reaction emoji). */
|
|
66
|
+
export const STEER_REACTION = '✍';
|
|
67
|
+
/** The fallback when the reaction is refused. */
|
|
68
|
+
export const STEER_NOTE = '↪️ Added to the current reply.';
|
|
69
|
+
export const SHELL_REFUSAL_REPLY = 'Shell commands ("!" or "!!") cannot be run from Telegram. Ask the assistant in words instead, and it can run what is needed itself.';
|
|
70
|
+
export const RESET_REPLY = '🆕 Started a fresh assistant session. What it wrote down in its folder is kept.';
|
|
71
|
+
export const STOPPED_REPLY = '⏹ Stopped the current reply.';
|
|
72
|
+
export const NOTHING_RUNNING_REPLY = 'Nothing is running.';
|
|
73
|
+
/** The `🔔` notification text (an `assistant_notify`), before splitting. */
|
|
74
|
+
export function formatTelegramNotification(n, publicUrl) {
|
|
75
|
+
let text = `🔔 ${n.source}: ${n.title}`;
|
|
76
|
+
if (n.body && n.body.trim())
|
|
77
|
+
text += `\n\n${n.body.trim()}`;
|
|
78
|
+
const link = sessionLink(publicUrl, n.navigate);
|
|
79
|
+
if (link)
|
|
80
|
+
text += `\n\n${link}`;
|
|
81
|
+
return text;
|
|
82
|
+
}
|
|
83
|
+
/** `<publicUrl>/#<sessionId>`, or null without a usable http(s) public URL. */
|
|
84
|
+
export function sessionLink(publicUrl, sessionId) {
|
|
85
|
+
if (typeof publicUrl !== 'string' || !publicUrl.trim() || !sessionId)
|
|
86
|
+
return null;
|
|
87
|
+
try {
|
|
88
|
+
const u = new URL(publicUrl.trim());
|
|
89
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:')
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
return `${publicUrl.trim().replace(/[/#]+$/, '')}/#${sessionId}`;
|
|
96
|
+
}
|
|
97
|
+
/** The report of messages a reset or an aborted settle dropped, before splitting. */
|
|
98
|
+
export function formatDroppedReport(report) {
|
|
99
|
+
const n = report.messages.length;
|
|
100
|
+
const what = n === 1 ? 'this message' : `these ${n} messages`;
|
|
101
|
+
const head = report.reason === 'reset'
|
|
102
|
+
? `⚠️ The assistant was reset before it read ${what}; send again if still needed:`
|
|
103
|
+
: `⚠️ The turn was stopped before the assistant read ${what}; send again if still needed:`;
|
|
104
|
+
return [head, ...report.messages.map((m) => `• ${m}`)].join('\n\n');
|
|
105
|
+
}
|
|
106
|
+
class BotApiError extends Error {
|
|
107
|
+
method;
|
|
108
|
+
status;
|
|
109
|
+
description;
|
|
110
|
+
retryAfterSeconds;
|
|
111
|
+
constructor(method, status, description, retryAfterSeconds) {
|
|
112
|
+
super(`Bot API ${method} failed: HTTP ${status}${description ? ` (${description})` : ''}`);
|
|
113
|
+
this.method = method;
|
|
114
|
+
this.status = status;
|
|
115
|
+
this.description = description;
|
|
116
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
117
|
+
}
|
|
118
|
+
/** The token is wrong: retrying cannot help. */
|
|
119
|
+
get fatal() {
|
|
120
|
+
return this.status === 401 || this.status === 404;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export class TelegramChannel {
|
|
124
|
+
name = TELEGRAM_CHANNEL;
|
|
125
|
+
token;
|
|
126
|
+
botId;
|
|
127
|
+
apiBase;
|
|
128
|
+
fetchImpl;
|
|
129
|
+
pollTimeout;
|
|
130
|
+
retryDelay;
|
|
131
|
+
offsetPath;
|
|
132
|
+
pairingPath;
|
|
133
|
+
newCode;
|
|
134
|
+
onChange;
|
|
135
|
+
log;
|
|
136
|
+
configuredUserId;
|
|
137
|
+
pairing;
|
|
138
|
+
offset;
|
|
139
|
+
bot = null;
|
|
140
|
+
fatalError = null;
|
|
141
|
+
lastError = null;
|
|
142
|
+
started = false;
|
|
143
|
+
ctx = null;
|
|
144
|
+
abort = null;
|
|
145
|
+
loopDone = null;
|
|
146
|
+
publicUrl;
|
|
147
|
+
replies;
|
|
148
|
+
uploadDir;
|
|
149
|
+
maxUploadBytes;
|
|
150
|
+
mediaGroupDelayMs;
|
|
151
|
+
/** Albums being gathered, by `media_group_id`. */
|
|
152
|
+
groups = new Map();
|
|
153
|
+
/** Every inbound message is handled through this one chain (an album's timer and the polling loop never interleave). */
|
|
154
|
+
inbound = Promise.resolve();
|
|
155
|
+
constructor(opts) {
|
|
156
|
+
this.token = opts.token;
|
|
157
|
+
this.botId = opts.token.split(':')[0] ?? '';
|
|
158
|
+
this.apiBase = (opts.apiBaseUrl ?? TELEGRAM_API_BASE).replace(/\/+$/, '');
|
|
159
|
+
this.fetchImpl = opts.fetch ?? ((url, init) => fetch(url, init));
|
|
160
|
+
this.pollTimeout = opts.pollTimeoutSeconds ?? 30;
|
|
161
|
+
this.retryDelay = opts.retryDelayMs ?? ((n) => Math.min(60_000, 1000 * 2 ** (n - 1)));
|
|
162
|
+
this.offsetPath = path.join(opts.stateDir, TELEGRAM_OFFSET_FILE);
|
|
163
|
+
this.pairingPath = path.join(opts.stateDir, TELEGRAM_PAIRING_FILE);
|
|
164
|
+
this.newCode = opts.newCode ?? (() => generatePairingCode());
|
|
165
|
+
this.onChange = opts.onChange ?? (() => { });
|
|
166
|
+
this.log = opts.log ?? console;
|
|
167
|
+
this.configuredUserId = opts.configuredUserId;
|
|
168
|
+
this.publicUrl = opts.publicUrl;
|
|
169
|
+
this.uploadDir = opts.uploadDir;
|
|
170
|
+
this.maxUploadBytes = opts.maxUploadBytes ?? (() => TELEGRAM_DOWNLOAD_MAX_BYTES);
|
|
171
|
+
this.mediaGroupDelayMs = opts.mediaGroupDelayMs ?? MEDIA_GROUP_DELAY_MS;
|
|
172
|
+
this.replies = new TelegramReplies({
|
|
173
|
+
call: (method, params) => this.call(method, params),
|
|
174
|
+
upload: (method, fields, fileField, filePath, fileName) => this.callMultipart(method, fields, fileField, filePath, fileName),
|
|
175
|
+
chatId: () => (this.started ? this.pairedChatId() : null),
|
|
176
|
+
throttleMs: opts.replyThrottleMs,
|
|
177
|
+
log: this.log,
|
|
178
|
+
});
|
|
179
|
+
// Nothing is read before start(): the state lives in memory from there.
|
|
180
|
+
this.pairing = { configuredUserId: opts.configuredUserId, stored: null, code: null };
|
|
181
|
+
}
|
|
182
|
+
/** Load the stored pairing and offset, then start polling (not awaited). */
|
|
183
|
+
start(ctx) {
|
|
184
|
+
if (this.started)
|
|
185
|
+
return;
|
|
186
|
+
this.started = true;
|
|
187
|
+
this.ctx = ctx;
|
|
188
|
+
this.pairing = initialPairingState(this.configuredUserId, this.readPairing(), this.newCode);
|
|
189
|
+
this.offset = this.readOffset();
|
|
190
|
+
this.abort = new AbortController();
|
|
191
|
+
this.loopDone = this.run(this.abort.signal);
|
|
192
|
+
}
|
|
193
|
+
async stop() {
|
|
194
|
+
if (!this.started)
|
|
195
|
+
return;
|
|
196
|
+
this.started = false;
|
|
197
|
+
this.abort?.abort();
|
|
198
|
+
this.replies.stop();
|
|
199
|
+
for (const g of this.groups.values())
|
|
200
|
+
clearTimeout(g.timer);
|
|
201
|
+
this.groups.clear();
|
|
202
|
+
await this.loopDone?.catch(() => { });
|
|
203
|
+
this.loopDone = null;
|
|
204
|
+
this.ctx = null;
|
|
205
|
+
}
|
|
206
|
+
status() {
|
|
207
|
+
if (this.fatalError)
|
|
208
|
+
return { state: 'error', error: this.fatalError, bot: this.bot };
|
|
209
|
+
const extra = this.lastError ? { error: this.lastError } : {};
|
|
210
|
+
if (!this.started)
|
|
211
|
+
return { state: 'starting', bot: this.bot, ...extra };
|
|
212
|
+
const eff = effectivePairing(this.pairing);
|
|
213
|
+
if (eff.kind === 'unpaired')
|
|
214
|
+
return { state: 'unpaired', code: eff.code, bot: this.bot, ...extra };
|
|
215
|
+
return {
|
|
216
|
+
state: 'paired',
|
|
217
|
+
user: { id: eff.userId, ...(eff.name ? { name: eff.name } : {}), source: eff.source },
|
|
218
|
+
bot: this.bot,
|
|
219
|
+
...extra,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/** The paired user's chat (null while unpaired), for `telegram-conversation`. */
|
|
223
|
+
pairedChatId() {
|
|
224
|
+
const eff = effectivePairing(this.pairing);
|
|
225
|
+
return eff.kind === 'paired' ? eff.chatId : null;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The web's RE-PAIR: forget the stored pairing (the file is removed) and
|
|
229
|
+
* issue a new code. Refused while the user id comes from the config.
|
|
230
|
+
*/
|
|
231
|
+
repair() {
|
|
232
|
+
if (!this.started)
|
|
233
|
+
return { ok: false, error: 'the Telegram channel is not running' };
|
|
234
|
+
const r = repairState(this.pairing, this.newCode());
|
|
235
|
+
if (!r.ok)
|
|
236
|
+
return r;
|
|
237
|
+
this.pairing = r.state;
|
|
238
|
+
try {
|
|
239
|
+
fs.rmSync(this.pairingPath, { force: true });
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
this.log.error(`[wherever] telegram: could not remove ${this.pairingPath}: ${errMessage(err)}`);
|
|
243
|
+
}
|
|
244
|
+
this.log.log('[wherever] telegram: pairing reset from the web; a new pairing code was issued');
|
|
245
|
+
this.onChange();
|
|
246
|
+
return { ok: true };
|
|
247
|
+
}
|
|
248
|
+
/** Output answering a Telegram message (its destination is `telegram`): streamed to the paired chat. */
|
|
249
|
+
deliverReply(reply) {
|
|
250
|
+
this.replies.handle(reply.sessionFile, reply.event);
|
|
251
|
+
}
|
|
252
|
+
/** Resolves once every pending reply preview and send has run (tests). */
|
|
253
|
+
replyIdle() {
|
|
254
|
+
return this.replies.idle();
|
|
255
|
+
}
|
|
256
|
+
/** Resolves once every gathered album and inbound message has been handled (tests). */
|
|
257
|
+
async inboundIdle() {
|
|
258
|
+
for (;;) {
|
|
259
|
+
const chain = this.inbound;
|
|
260
|
+
await chain;
|
|
261
|
+
if (this.groups.size > 0) {
|
|
262
|
+
await new Promise((r) => setTimeout(r, Math.max(5, this.mediaGroupDelayMs)));
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (chain === this.inbound)
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** `assistant_notify`: its own `🔔` message, sent now (never waits for, or joins, a reply). */
|
|
270
|
+
async notify(n) {
|
|
271
|
+
const chatId = this.started ? this.pairedChatId() : null;
|
|
272
|
+
if (!chatId)
|
|
273
|
+
return { ok: false, error: this.started ? 'Telegram is not paired yet' : 'the Telegram channel is not running' };
|
|
274
|
+
try {
|
|
275
|
+
for (const part of splitTelegramText(formatTelegramNotification(n, this.publicUrl))) {
|
|
276
|
+
await this.call('sendMessage', { chat_id: chatId, text: part });
|
|
277
|
+
}
|
|
278
|
+
return { ok: true, detail: 'sent' };
|
|
279
|
+
}
|
|
280
|
+
catch (err) {
|
|
281
|
+
return { ok: false, error: errMessage(err).split(this.token).join('<token>') };
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** Messages from Telegram that a reset or an aborted settle dropped: listed back to the user. */
|
|
285
|
+
async reportDropped(report) {
|
|
286
|
+
const chatId = this.started ? this.pairedChatId() : null;
|
|
287
|
+
if (!chatId || report.messages.length === 0)
|
|
288
|
+
return;
|
|
289
|
+
for (const part of splitTelegramText(formatDroppedReport(report))) {
|
|
290
|
+
await this.reply(chatId, part);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/** One Bot API call; resolves `result`, throws `BotApiError` on `ok: false`. */
|
|
294
|
+
async call(method, params, signal) {
|
|
295
|
+
const res = await this.fetchImpl(`${this.apiBase}/bot${this.token}/${method}`, {
|
|
296
|
+
method: 'POST',
|
|
297
|
+
headers: { 'Content-Type': 'application/json' },
|
|
298
|
+
body: JSON.stringify(params),
|
|
299
|
+
...(signal ? { signal } : {}),
|
|
300
|
+
});
|
|
301
|
+
return this.answer(method, res);
|
|
302
|
+
}
|
|
303
|
+
/** A multipart Bot API call sending the local `filePath` as `fileField`. */
|
|
304
|
+
async callMultipart(method, fields, fileField, filePath, fileName) {
|
|
305
|
+
const form = new FormData();
|
|
306
|
+
for (const [k, v] of Object.entries(fields))
|
|
307
|
+
form.set(k, v);
|
|
308
|
+
const bytes = await fs.promises.readFile(filePath);
|
|
309
|
+
form.set(fileField, new Blob([bytes]), fileName);
|
|
310
|
+
const res = await this.fetchImpl(`${this.apiBase}/bot${this.token}/${method}`, {
|
|
311
|
+
method: 'POST',
|
|
312
|
+
body: form,
|
|
313
|
+
...(this.abort ? { signal: this.abort.signal } : {}),
|
|
314
|
+
});
|
|
315
|
+
return this.answer(method, res);
|
|
316
|
+
}
|
|
317
|
+
// -------------------------------------------------------------------------
|
|
318
|
+
async answer(method, res) {
|
|
319
|
+
let body = null;
|
|
320
|
+
try {
|
|
321
|
+
body = await res.json();
|
|
322
|
+
}
|
|
323
|
+
catch { }
|
|
324
|
+
if (res.status >= 200 && res.status < 300 && body?.ok === true)
|
|
325
|
+
return body.result;
|
|
326
|
+
throw new BotApiError(method, res.status, typeof body?.description === 'string' ? body.description : '', typeof body?.parameters?.retry_after === 'number' ? body.parameters.retry_after : undefined);
|
|
327
|
+
}
|
|
328
|
+
async run(signal) {
|
|
329
|
+
let attempt = 0;
|
|
330
|
+
for (;;) {
|
|
331
|
+
if (signal.aborted)
|
|
332
|
+
return;
|
|
333
|
+
try {
|
|
334
|
+
const me = await this.call('getMe', {}, signal);
|
|
335
|
+
this.bot = me?.username ? `@${me.username}` : null;
|
|
336
|
+
this.log.log(`[wherever] telegram: connected as ${this.bot ?? 'the bot'}${this.pairedChatId() ? '' : ' (unpaired: see the wherever settings for the pairing code)'}`);
|
|
337
|
+
this.onChange();
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
catch (err) {
|
|
341
|
+
if (signal.aborted)
|
|
342
|
+
return;
|
|
343
|
+
if (!(await this.failed(err, ++attempt, signal)))
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
attempt = 0;
|
|
348
|
+
while (!signal.aborted) {
|
|
349
|
+
let updates;
|
|
350
|
+
try {
|
|
351
|
+
updates = await this.call('getUpdates', { ...(this.offset !== undefined ? { offset: this.offset } : {}), timeout: this.pollTimeout, allowed_updates: ['message'] }, signal);
|
|
352
|
+
}
|
|
353
|
+
catch (err) {
|
|
354
|
+
if (signal.aborted)
|
|
355
|
+
return;
|
|
356
|
+
if (!(await this.failed(err, ++attempt, signal)))
|
|
357
|
+
return;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
attempt = 0;
|
|
361
|
+
if (this.lastError) {
|
|
362
|
+
this.lastError = null;
|
|
363
|
+
this.onChange();
|
|
364
|
+
}
|
|
365
|
+
for (const u of Array.isArray(updates) ? updates : []) {
|
|
366
|
+
if (signal.aborted)
|
|
367
|
+
return;
|
|
368
|
+
if (typeof u?.update_id !== 'number')
|
|
369
|
+
continue;
|
|
370
|
+
try {
|
|
371
|
+
await this.handle(u);
|
|
372
|
+
}
|
|
373
|
+
catch (err) {
|
|
374
|
+
this.log.error(`[wherever] telegram: handling update ${u.update_id} failed: ${errMessage(err)}`);
|
|
375
|
+
}
|
|
376
|
+
this.offset = u.update_id + 1;
|
|
377
|
+
this.writeOffset(this.offset);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** Log a failed call; false = stop polling (fatal), true = retried after the backoff. */
|
|
382
|
+
async failed(err, attempt, signal) {
|
|
383
|
+
if (err instanceof BotApiError && err.fatal) {
|
|
384
|
+
this.fatalError = `the bot token was rejected by Telegram (${err.message}); fix it and restart wherever`;
|
|
385
|
+
this.log.error(`[wherever] telegram: ${this.fatalError}. Telegram is DISABLED.`);
|
|
386
|
+
this.onChange();
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
// Never log the token (a network error may quote the request URL).
|
|
390
|
+
const msg = errMessage(err).split(this.token).join('<token>');
|
|
391
|
+
if (this.lastError !== msg) {
|
|
392
|
+
this.lastError = msg;
|
|
393
|
+
this.log.warn(`[wherever] telegram: ${msg}; retrying`);
|
|
394
|
+
this.onChange();
|
|
395
|
+
}
|
|
396
|
+
const wait = err instanceof BotApiError && err.retryAfterSeconds ? err.retryAfterSeconds * 1000 : this.retryDelay(attempt);
|
|
397
|
+
await sleep(wait, signal);
|
|
398
|
+
return !signal.aborted;
|
|
399
|
+
}
|
|
400
|
+
async handle(u) {
|
|
401
|
+
const m = u.message;
|
|
402
|
+
if (!m || !m.from || m.from.is_bot)
|
|
403
|
+
return;
|
|
404
|
+
const text = typeof m.text === 'string' ? m.text : typeof m.caption === 'string' ? m.caption : undefined;
|
|
405
|
+
const hasMedia = inboundFilesOf(m).length > 0 || hasUnsupportedMedia(m);
|
|
406
|
+
if (text === undefined && !hasMedia)
|
|
407
|
+
return;
|
|
408
|
+
const fromId = String(m.from.id);
|
|
409
|
+
const name = m.from.username ? `@${m.from.username}` : m.from.first_name;
|
|
410
|
+
// Pairing decides on the text alone (a caption here), BEFORE anything is
|
|
411
|
+
// downloaded: a stranger's file is never fetched.
|
|
412
|
+
const decision = decideInbound(this.pairing, {
|
|
413
|
+
fromId,
|
|
414
|
+
chatId: String(m.chat.id),
|
|
415
|
+
chatType: m.chat.type,
|
|
416
|
+
text: text ?? '',
|
|
417
|
+
...(name ? { name } : {}),
|
|
418
|
+
});
|
|
419
|
+
switch (decision.kind) {
|
|
420
|
+
case 'ignore':
|
|
421
|
+
// Never answered; logged without the text (it is a stranger's).
|
|
422
|
+
this.log.log(`[wherever] telegram: ignored a message from user ${fromId} (${decision.why})`);
|
|
423
|
+
return;
|
|
424
|
+
case 'pair':
|
|
425
|
+
this.writePairing(decision.user);
|
|
426
|
+
this.pairing = applyPairing(this.pairing, decision.user);
|
|
427
|
+
this.log.log(`[wherever] telegram: paired with user ${decision.user.userId}${decision.user.name ? ` (${decision.user.name})` : ''}`);
|
|
428
|
+
this.onChange();
|
|
429
|
+
await this.reply(m.chat.id, decision.reply);
|
|
430
|
+
return;
|
|
431
|
+
case 'refuse':
|
|
432
|
+
await this.reply(m.chat.id, decision.reply);
|
|
433
|
+
return;
|
|
434
|
+
case 'forward': {
|
|
435
|
+
const groupId = typeof m.media_group_id === 'string' && m.media_group_id ? m.media_group_id : null;
|
|
436
|
+
if (groupId) {
|
|
437
|
+
// Albums before this one go first, in order.
|
|
438
|
+
for (const key of [...this.groups.keys()])
|
|
439
|
+
if (key !== groupId)
|
|
440
|
+
void this.flushGroup(key);
|
|
441
|
+
this.gather(groupId, m, fromId);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
// Any album still being gathered was sent before this message.
|
|
445
|
+
for (const key of [...this.groups.keys()])
|
|
446
|
+
void this.flushGroup(key);
|
|
447
|
+
await this.serial(() => this.converse([m], fromId));
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
/** Run `fn` after every inbound message before it has been handled. */
|
|
453
|
+
serial(fn) {
|
|
454
|
+
const run = this.inbound.then(fn, fn);
|
|
455
|
+
this.inbound = run.catch((err) => this.log.error(`[wherever] telegram: handling a message failed: ${errMessage(err)}`));
|
|
456
|
+
return this.inbound;
|
|
457
|
+
}
|
|
458
|
+
/** Add an album message; the album is handled `mediaGroupDelayMs` after its LAST message. */
|
|
459
|
+
gather(groupId, m, fromId) {
|
|
460
|
+
const g = this.groups.get(groupId);
|
|
461
|
+
if (g)
|
|
462
|
+
clearTimeout(g.timer);
|
|
463
|
+
const messages = [...(g?.messages ?? []), m];
|
|
464
|
+
const timer = setTimeout(() => void this.flushGroup(groupId), this.mediaGroupDelayMs);
|
|
465
|
+
this.groups.set(groupId, { messages, fromId, timer });
|
|
466
|
+
}
|
|
467
|
+
flushGroup(groupId) {
|
|
468
|
+
const g = this.groups.get(groupId);
|
|
469
|
+
if (!g)
|
|
470
|
+
return Promise.resolve();
|
|
471
|
+
this.groups.delete(groupId);
|
|
472
|
+
clearTimeout(g.timer);
|
|
473
|
+
return this.serial(() => this.converse(g.messages, g.fromId));
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* The paired user's message (one, or an album's): a command, a refusal, or a
|
|
477
|
+
* message for the assistant, with its files downloaded into the upload dir.
|
|
478
|
+
*/
|
|
479
|
+
async converse(messages, fromId) {
|
|
480
|
+
const ctx = this.ctx;
|
|
481
|
+
const first = messages[0];
|
|
482
|
+
if (!ctx || !first)
|
|
483
|
+
return;
|
|
484
|
+
const chatId = first.chat.id;
|
|
485
|
+
const messageId = first.message_id;
|
|
486
|
+
const textOf = (m) => (typeof m.text === 'string' ? m.text : typeof m.caption === 'string' ? m.caption : '');
|
|
487
|
+
// One message's text goes to the assistant untouched; an album's captions are joined.
|
|
488
|
+
const text = messages.length === 1
|
|
489
|
+
? textOf(first)
|
|
490
|
+
: messages
|
|
491
|
+
.map((m) => textOf(m).trim())
|
|
492
|
+
.filter(Boolean)
|
|
493
|
+
.join('\n\n');
|
|
494
|
+
const wanted = messages.flatMap((m) => inboundFilesOf(m));
|
|
495
|
+
const unsupported = messages.some((m) => hasUnsupportedMedia(m));
|
|
496
|
+
const trimmed = text.trim();
|
|
497
|
+
const cmd = parseCommand(trimmed);
|
|
498
|
+
// Commands are a TEXT message's; a caption is text for the assistant.
|
|
499
|
+
if (wanted.length === 0 && !unsupported) {
|
|
500
|
+
if (trimmed.toLowerCase() === 'stop' || cmd?.command === 'stop') {
|
|
501
|
+
const r = await ctx.abortTurn();
|
|
502
|
+
await this.reply(chatId, r.aborted ? STOPPED_REPLY : NOTHING_RUNNING_REPLY);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (cmd && (cmd.command === 'new' || cmd.command === 'reset')) {
|
|
506
|
+
const r = await ctx.resetSession();
|
|
507
|
+
await this.reply(chatId, r.ok ? RESET_REPLY : `⚠️ Could not reset the assistant: ${r.error}`);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (trimmed.startsWith('!')) {
|
|
512
|
+
await this.reply(chatId, SHELL_REFUSAL_REPLY);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (unsupported)
|
|
516
|
+
await this.reply(chatId, UNSUPPORTED_MEDIA_REPLY);
|
|
517
|
+
const files = [];
|
|
518
|
+
if (wanted.length > 0) {
|
|
519
|
+
const dir = this.uploadDir?.();
|
|
520
|
+
if (!dir) {
|
|
521
|
+
await this.reply(chatId, FILES_UNAVAILABLE_REPLY);
|
|
522
|
+
}
|
|
523
|
+
else {
|
|
524
|
+
for (const f of wanted) {
|
|
525
|
+
const r = await this.download(f, dir);
|
|
526
|
+
if (r.ok)
|
|
527
|
+
files.push(r.file);
|
|
528
|
+
else
|
|
529
|
+
await this.reply(chatId, r.note);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
if (!trimmed && files.length === 0)
|
|
534
|
+
return;
|
|
535
|
+
// Wait until the message is DISPATCHED (handed to the session as a start or
|
|
536
|
+
// a steer), not until its turn ends: the next message is then decided
|
|
537
|
+
// against the right state (steer vs start), and polling goes on.
|
|
538
|
+
await new Promise((resolve) => {
|
|
539
|
+
let done = false;
|
|
540
|
+
const dispatched = () => {
|
|
541
|
+
if (done)
|
|
542
|
+
return;
|
|
543
|
+
done = true;
|
|
544
|
+
resolve();
|
|
545
|
+
};
|
|
546
|
+
ctx
|
|
547
|
+
.onUserMessage({ channel: TELEGRAM_CHANNEL, text, ...(files.length ? { files } : {}), senderId: fromId }, {
|
|
548
|
+
onDispatched: ({ steered }) => {
|
|
549
|
+
dispatched();
|
|
550
|
+
if (steered)
|
|
551
|
+
void this.markSteer(chatId, messageId);
|
|
552
|
+
},
|
|
553
|
+
})
|
|
554
|
+
.then((r) => {
|
|
555
|
+
if (!r.accepted)
|
|
556
|
+
this.log.log(`[wherever] telegram: message not sent to the assistant (${r.reason})`);
|
|
557
|
+
})
|
|
558
|
+
.catch((err) => {
|
|
559
|
+
this.log.error(`[wherever] telegram: sending a message to the assistant failed: ${errMessage(err)}`);
|
|
560
|
+
void this.reply(chatId, `⚠️ The assistant could not take your message: ${errMessage(err)}`);
|
|
561
|
+
})
|
|
562
|
+
.finally(dispatched);
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Fetch one file from Telegram (`getFile`, then its download URL) into `dir`.
|
|
567
|
+
* Refused, with a note for the user, over the upload limit (`maxUploadBytes`,
|
|
568
|
+
* capped at Telegram's 20 MB), before downloading when Telegram announced the
|
|
569
|
+
* size and after it otherwise.
|
|
570
|
+
*/
|
|
571
|
+
async download(f, dir) {
|
|
572
|
+
const limit = Math.min(TELEGRAM_DOWNLOAD_MAX_BYTES, this.maxUploadBytes());
|
|
573
|
+
if (typeof f.size === 'number' && f.size > limit)
|
|
574
|
+
return { ok: false, note: inboundTooLargeNote(f.name, f.size, limit) };
|
|
575
|
+
try {
|
|
576
|
+
const info = await this.call('getFile', { file_id: f.fileId }, this.abort?.signal);
|
|
577
|
+
if (typeof info?.file_size === 'number' && info.file_size > limit)
|
|
578
|
+
return { ok: false, note: inboundTooLargeNote(f.name, info.file_size, limit) };
|
|
579
|
+
if (!info?.file_path)
|
|
580
|
+
throw new Error('Telegram gave no download path');
|
|
581
|
+
const res = await this.fetchImpl(`${this.apiBase}/file/bot${this.token}/${info.file_path.split('/').map(encodeURIComponent).join('/')}`, {
|
|
582
|
+
method: 'GET',
|
|
583
|
+
...(this.abort ? { signal: this.abort.signal } : {}),
|
|
584
|
+
});
|
|
585
|
+
if (res.status < 200 || res.status >= 300 || !res.arrayBuffer)
|
|
586
|
+
throw new Error(`download failed: HTTP ${res.status}`);
|
|
587
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
588
|
+
if (bytes.byteLength > limit)
|
|
589
|
+
return { ok: false, note: inboundTooLargeNote(f.name, bytes.byteLength, limit) };
|
|
590
|
+
const saved = await saveUploaded(dir, f.name, bytes);
|
|
591
|
+
this.log.log(`[wherever] telegram: received ${f.name} (${bytes.byteLength} bytes) into ${saved}`);
|
|
592
|
+
return { ok: true, file: { path: saved, name: f.name, ...(f.mimeType ? { mimeType: f.mimeType } : {}) } };
|
|
593
|
+
}
|
|
594
|
+
catch (err) {
|
|
595
|
+
const msg = errMessage(err).split(this.token).join('<token>');
|
|
596
|
+
if (/file is too big/i.test(msg))
|
|
597
|
+
return { ok: false, note: inboundTooLargeNote(f.name, f.size, limit) };
|
|
598
|
+
this.log.warn(`[wherever] telegram: receiving ${f.name} failed: ${msg}`);
|
|
599
|
+
return { ok: false, note: inboundFailedNote(f.name, msg) };
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/** Show that a message steered the running turn: a reaction, else a short note replying to it. */
|
|
603
|
+
async markSteer(chatId, messageId) {
|
|
604
|
+
try {
|
|
605
|
+
await this.call('setMessageReaction', { chat_id: chatId, message_id: messageId, reaction: [{ type: 'emoji', emoji: STEER_REACTION }] });
|
|
606
|
+
}
|
|
607
|
+
catch (err) {
|
|
608
|
+
this.log.log(`[wherever] telegram: setMessageReaction failed (${errMessage(err)}); sending the steer note instead`);
|
|
609
|
+
try {
|
|
610
|
+
await this.call('sendMessage', {
|
|
611
|
+
chat_id: chatId,
|
|
612
|
+
text: STEER_NOTE,
|
|
613
|
+
reply_parameters: { message_id: messageId, allow_sending_without_reply: true },
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
catch (err2) {
|
|
617
|
+
this.log.warn(`[wherever] telegram: sending the steer note failed: ${errMessage(err2)}`);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
async reply(chatId, text) {
|
|
622
|
+
try {
|
|
623
|
+
await this.call('sendMessage', { chat_id: chatId, text });
|
|
624
|
+
}
|
|
625
|
+
catch (err) {
|
|
626
|
+
this.log.warn(`[wherever] telegram: sendMessage failed: ${errMessage(err)}`);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
readOffset() {
|
|
630
|
+
const data = readJson(this.offsetPath, this.log);
|
|
631
|
+
if (!data)
|
|
632
|
+
return undefined;
|
|
633
|
+
if (data.botId !== this.botId) {
|
|
634
|
+
this.log.log('[wherever] telegram: ignoring the stored polling offset of another bot');
|
|
635
|
+
return undefined;
|
|
636
|
+
}
|
|
637
|
+
return typeof data.offset === 'number' && Number.isSafeInteger(data.offset) ? data.offset : undefined;
|
|
638
|
+
}
|
|
639
|
+
writeOffset(offset) {
|
|
640
|
+
try {
|
|
641
|
+
writeAtomic0600(this.offsetPath, JSON.stringify({ botId: this.botId, offset }) + '\n');
|
|
642
|
+
}
|
|
643
|
+
catch (err) {
|
|
644
|
+
this.log.error(`[wherever] telegram: could not persist the polling offset to ${this.offsetPath}: ${errMessage(err)}`);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
readPairing() {
|
|
648
|
+
const d = readJson(this.pairingPath, this.log);
|
|
649
|
+
if (!d || typeof d.userId !== 'string' || !/^\d+$/.test(d.userId))
|
|
650
|
+
return null;
|
|
651
|
+
return {
|
|
652
|
+
userId: d.userId,
|
|
653
|
+
chatId: typeof d.chatId === 'string' ? d.chatId : d.userId,
|
|
654
|
+
...(typeof d.name === 'string' ? { name: d.name } : {}),
|
|
655
|
+
...(typeof d.pairedAt === 'string' ? { pairedAt: d.pairedAt } : {}),
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
writePairing(user) {
|
|
659
|
+
writeAtomic0600(this.pairingPath, JSON.stringify(user, null, 2) + '\n');
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
function readJson(file, log) {
|
|
663
|
+
let raw;
|
|
664
|
+
try {
|
|
665
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
return null;
|
|
669
|
+
}
|
|
670
|
+
try {
|
|
671
|
+
const d = JSON.parse(raw);
|
|
672
|
+
return d && typeof d === 'object' ? d : null;
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
log.warn(`[wherever] telegram: ignoring an unreadable ${file}`);
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
function writeAtomic0600(file, content) {
|
|
680
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
681
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
682
|
+
fs.writeFileSync(tmp, content, { mode: 0o600 });
|
|
683
|
+
fs.renameSync(tmp, file);
|
|
684
|
+
}
|
|
685
|
+
function sleep(ms, signal) {
|
|
686
|
+
return new Promise((resolve) => {
|
|
687
|
+
if (signal.aborted)
|
|
688
|
+
return resolve();
|
|
689
|
+
const t = setTimeout(done, ms);
|
|
690
|
+
function done() {
|
|
691
|
+
clearTimeout(t);
|
|
692
|
+
signal.removeEventListener('abort', done);
|
|
693
|
+
resolve();
|
|
694
|
+
}
|
|
695
|
+
signal.addEventListener('abort', done);
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
function errMessage(err) {
|
|
699
|
+
return err instanceof Error ? err.message : String(err);
|
|
700
|
+
}
|
|
701
|
+
//# sourceMappingURL=telegram-channel.js.map
|