angelia-gateway 0.3.23 → 0.3.25
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/dist/adapters/telegram/adapter.js +7 -0
- package/dist/adapters/whatsapp/adapter.js +145 -17
- package/dist/adapters/whatsapp/groups.js +38 -0
- package/dist/adapters/whatsapp/ids.js +9 -2
- package/dist/adapters/whatsapp/parse.js +62 -3
- package/dist/brain/codex.js +7 -0
- package/dist/build.json +3 -3
- package/dist/cli/cli-args.js +3 -2
- package/dist/core/cut-turns.js +42 -0
- package/dist/core/deliver/chunk.js +85 -8
- package/dist/core/deliver/text.js +5 -0
- package/dist/core/orchestrator.js +53 -10
- package/dist/daemon/api/deps.js +2 -1
- package/dist/daemon/api/routes.js +1 -0
- package/dist/daemon/daemon.js +52 -13
- package/dist/daemon/redact.js +39 -0
- package/dist/daemon/self.js +1 -1
- package/dist/instance/config/schema.js +8 -3
- package/dist/instance/guide.js +14 -2
- package/dist/instance/instance.js +12 -3
- package/dist/instance/secrets.js +22 -4
- package/dist/instance/switch-backend.js +27 -3
- package/dist/instance/workspace-commit.js +2 -2
- package/dist/jobs/jobs-cli.js +147 -55
- package/dist/jobs/jobs-view.js +10 -5
- package/dist/jobs/jobs.js +130 -9
- package/package.json +15 -1
|
@@ -249,9 +249,16 @@ export class TelegramAdapter {
|
|
|
249
249
|
else
|
|
250
250
|
note(`a file over ${MAX_INBOUND >> 20} MB was sent and not downloaded`);
|
|
251
251
|
}
|
|
252
|
+
else {
|
|
253
|
+
this.log(`telegram: getFile gave no file_path chat=${chat}`);
|
|
254
|
+
note('the file sent could not be downloaded');
|
|
255
|
+
}
|
|
252
256
|
}
|
|
253
257
|
catch (e) {
|
|
258
|
+
// Said to the agent too (#35): a file with no caption would otherwise be no turn at all, and one
|
|
259
|
+
// with a caption would be answered as if nothing was attached.
|
|
254
260
|
this.log(`telegram: media download failed chat=${chat}: ${String(e.message ?? e).split(this.opts.token).join('<token>').slice(0, 160)}`);
|
|
261
|
+
note('the file sent could not be downloaded');
|
|
255
262
|
}
|
|
256
263
|
}
|
|
257
264
|
if (!head.text && !media.length)
|
|
@@ -6,11 +6,19 @@ import { ChatChains, MAX_INBOUND, SenderQuota, saveInbound } from '../inbox.js';
|
|
|
6
6
|
import { makeWASocket, useMultiFileAuthState, fetchLatestBaileysVersion, downloadMediaMessage, DisconnectReason } from 'baileys';
|
|
7
7
|
import qrcode from 'qrcode-terminal';
|
|
8
8
|
import { LidMap, normalizeJid } from './ids.js';
|
|
9
|
-
import { parseMessage, SeenIds } from './parse.js';
|
|
9
|
+
import { MAX_MENTIONS, parseMessage, SeenIds, withMentions } from './parse.js';
|
|
10
|
+
import { GroupCache } from './groups.js';
|
|
10
11
|
import { SentMessages } from './sent.js';
|
|
11
12
|
import { isOpus } from '../../core/deliver/media.js';
|
|
12
13
|
import { asVoice } from '../../voice/opus.js';
|
|
13
14
|
const MAX_MEDIA = MAX_INBOUND;
|
|
15
|
+
/** How a note to the agent names a kind of file: "a photo", "a voice note", never "a image". */
|
|
16
|
+
const KIND_NAME = { image: 'photo', audio: 'voice note', video: 'video', document: 'document', sticker: 'sticker' };
|
|
17
|
+
/** Paired and not connected for this long, the adapter says 'dead' (see check()). Baileys' own keepalive turns a
|
|
18
|
+
* dead socket into a close within about a minute, and a reconnect takes seconds, so five minutes is never a
|
|
19
|
+
* working session. */
|
|
20
|
+
const DEAD_MS = 5 * 60_000;
|
|
21
|
+
const WATCH_EVERY_MS = 30_000;
|
|
14
22
|
const EXT = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'video/mp4': '.mp4', 'audio/ogg; codecs=opus': '.ogg', 'audio/ogg': '.ogg', 'audio/mpeg': '.mp3', 'application/pdf': '.pdf' };
|
|
15
23
|
/**
|
|
16
24
|
* WhatsApp as a linked device (Baileys, in-process). One socket per daemon. Pairing by code
|
|
@@ -29,26 +37,87 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
29
37
|
log;
|
|
30
38
|
say;
|
|
31
39
|
backoffMs = 3000;
|
|
40
|
+
reconnect;
|
|
32
41
|
lastBackoffNotice = 0;
|
|
33
42
|
/** A field, not made in open(): what we sent must outlive a reconnect, when a retry needs it most. */
|
|
34
43
|
sent = new SentMessages();
|
|
44
|
+
now;
|
|
45
|
+
watch;
|
|
46
|
+
/** When the connection last opened or closed, or the check last acted: it counts from here. */
|
|
47
|
+
since = -1;
|
|
48
|
+
/** The check has opened again once already: the next window says 'dead'. Cleared by an open. */
|
|
49
|
+
reopened = false;
|
|
50
|
+
/** Set by a 440 close, cleared by the next attempt: another client holds the session, and a fresh process
|
|
51
|
+
* would only trade 440s with it faster. */
|
|
52
|
+
conflict = false;
|
|
53
|
+
/** Group members for a minute, for tagging and for Baileys' own lookup on every group send (groups.ts). */
|
|
54
|
+
groups = new GroupCache();
|
|
35
55
|
constructor(opts) {
|
|
36
56
|
super();
|
|
37
57
|
this.opts = opts;
|
|
38
58
|
this.log = opts.log ?? (() => { });
|
|
39
59
|
this.say = opts.say ?? ((l) => console.log(l));
|
|
60
|
+
this.now = opts.now ?? Date.now;
|
|
40
61
|
this.lids = new LidMap(opts.authDir);
|
|
41
62
|
}
|
|
42
63
|
get connected() { return this.state === 'connected'; }
|
|
43
64
|
async start() {
|
|
44
65
|
mkdirSync(this.opts.authDir, { recursive: true, mode: 0o700 });
|
|
66
|
+
// Before open(), and counting from the first start only: a first open that throws is started again
|
|
67
|
+
// by the daemon (30 s, then doubling), and a start that keeps throwing after open() read the
|
|
68
|
+
// credentials (`registered` set: the check is silent before that) reaches the dead path after
|
|
69
|
+
// DEAD_MS twice, like any other failure; a count reset at each retry would race the check's tick.
|
|
70
|
+
// One timer however often start() is called; unref'd, so it never holds a process open.
|
|
71
|
+
if (this.since < 0)
|
|
72
|
+
this.since = this.now();
|
|
73
|
+
clearInterval(this.watch);
|
|
74
|
+
this.watch = setInterval(() => this.check(), this.opts.watchEveryMs ?? WATCH_EVERY_MS);
|
|
75
|
+
this.watch.unref();
|
|
45
76
|
await this.open();
|
|
46
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Every close reconnects, and Baileys' keepalive turns a dead socket into a close, so a session that
|
|
80
|
+
* once worked comes back by itself; during a WhatsApp outage Baileys closes every 20-40 s, each close
|
|
81
|
+
* resets the count, and this check never fires there, by design. What it catches is a socket that
|
|
82
|
+
* neither opens nor closes: open() throwing or hanging in the auth state or the socket maker, a socket
|
|
83
|
+
* that never says open, a reopen that fails. The adapter would sit as 'connecting' in status for good,
|
|
84
|
+
* with nothing in the log. Paired and not connected for DEAD_MS, it first does in this process what a
|
|
85
|
+
* fresh one would: ends the socket and opens again. A second DEAD_MS with no open and no close, and it
|
|
86
|
+
* says 'dead': under launchd the daemon exits non-zero for a fresh process; started by hand it logs
|
|
87
|
+
* that a restart is needed, and the reopen here goes on every DEAD_MS. Not while pairing (the owner is
|
|
88
|
+
* typing a code), after a logout (pairing again is the fix), while stopping, or during a 440 backoff.
|
|
89
|
+
*/
|
|
90
|
+
check() {
|
|
91
|
+
// The clock first, every tick: a test counts its calls to see the timer end with stop().
|
|
92
|
+
const idle = this.now() - this.since;
|
|
93
|
+
if (this.connected || this.stopping || this.conflict || !this.registered || this.opts.pairOnly || idle < DEAD_MS)
|
|
94
|
+
return;
|
|
95
|
+
this.since = this.now();
|
|
96
|
+
if (this.reopened) {
|
|
97
|
+
this.log('whatsapp: still not connected after opening again; a fresh process is needed');
|
|
98
|
+
this.emit('dead');
|
|
99
|
+
}
|
|
100
|
+
else
|
|
101
|
+
this.log(`whatsapp: not connected for ${DEAD_MS / 60_000} min; ending the socket and opening again`);
|
|
102
|
+
this.reopened = true;
|
|
103
|
+
const sock = this.sock;
|
|
104
|
+
this.sock = undefined;
|
|
105
|
+
this.retire(sock);
|
|
106
|
+
this.reopenIn(0);
|
|
107
|
+
}
|
|
47
108
|
async open() {
|
|
48
109
|
if (this.stopping)
|
|
49
110
|
return;
|
|
50
111
|
this.state = 'connecting';
|
|
112
|
+
// The attempt a 440 backoff waited for gets its own DEAD_MS: the backoff itself may have been 30 min.
|
|
113
|
+
if (this.conflict) {
|
|
114
|
+
this.conflict = false;
|
|
115
|
+
this.since = this.now();
|
|
116
|
+
}
|
|
51
117
|
const { state, saveCreds } = await useMultiFileAuthState(this.opts.authDir);
|
|
118
|
+
// A QR link sets `me` and never `registered`; a code link sets both. Known before the socket is made,
|
|
119
|
+
// so a socket maker that throws leaves the not-connected check armed.
|
|
120
|
+
this.registered = !!(state.creds.registered || state.creds.me);
|
|
52
121
|
// Checked before any socket exists: a setup that cannot pair would otherwise leave a socket and
|
|
53
122
|
// its reconnects behind at every retry of the start.
|
|
54
123
|
if (!(state.creds.registered || state.creds.me) && this.opts.pairing === 'code' && !(this.opts.phone ?? '').replace(/\D/g, ''))
|
|
@@ -57,7 +126,7 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
57
126
|
// ANGELIA_WA_DEBUG=<file>: full Baileys debug log to that file (pairing diagnostics). Never on by default: it contains message payloads.
|
|
58
127
|
const debugFile = process.env.ANGELIA_WA_DEBUG;
|
|
59
128
|
const logger = debugFile ? pino({ level: 'trace' }, pino.destination({ dest: debugFile, sync: true })) : pino({ level: 'silent' });
|
|
60
|
-
const sock = makeWASocket({
|
|
129
|
+
const sock = (this.opts.makeSocket ?? makeWASocket)({
|
|
61
130
|
...(version ? { version } : {}),
|
|
62
131
|
auth: state,
|
|
63
132
|
logger,
|
|
@@ -69,18 +138,31 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
69
138
|
// Baileys' own cache answers first, but only for 5 minutes and it is cleared when the socket
|
|
70
139
|
// ends. Unknown ids get undefined: Baileys then resends nothing, which is the honest outcome.
|
|
71
140
|
getMessage: async (key) => this.sent.get(key.id),
|
|
141
|
+
// Filled by groupMeta(); an empty answer and Baileys asks the server itself, as it would without it.
|
|
142
|
+
// A change to disappearing messages or to the addressing mode emits no groups.update, so for those
|
|
143
|
+
// an entry can be up to the cache's 60 s stale. Accepted: the next minute reads it fresh.
|
|
144
|
+
cachedGroupMetadata: async (jid) => this.groups.get(jid),
|
|
72
145
|
});
|
|
146
|
+
// The socket this one replaces (the check() path ends one that never opened) is done with: a late
|
|
147
|
+
// close from it would start a second socket beside this one, and a late save would write its credentials.
|
|
148
|
+
const old = this.sock;
|
|
73
149
|
this.sock = sock;
|
|
74
|
-
|
|
75
|
-
|
|
150
|
+
this.retire(old);
|
|
151
|
+
// A change made while no socket listened was never heard: a new socket starts with no cached group.
|
|
152
|
+
this.groups.clear();
|
|
153
|
+
sock.ev.on('groups.update', (us) => { for (const u of us)
|
|
154
|
+
this.groups.drop(u.id); });
|
|
155
|
+
sock.ev.on('group-participants.update', (u) => this.groups.drop(u.id));
|
|
156
|
+
sock.ev.on('creds.update', () => { if (sock !== this.sock)
|
|
157
|
+
return; void saveCreds(); this.lids.reload(); });
|
|
158
|
+
sock.ev.on('connection.update', (u) => { if (sock === this.sock)
|
|
159
|
+
void this.onConnection(u, sock); });
|
|
76
160
|
sock.ev.on('messages.upsert', ({ messages, type }) => {
|
|
77
161
|
if (type !== 'notify' && type !== 'append')
|
|
78
162
|
return;
|
|
79
163
|
for (const m of messages)
|
|
80
164
|
void this.onMessage(m).catch((e) => this.log(`whatsapp: message error ${e.message}`));
|
|
81
165
|
});
|
|
82
|
-
// A QR link sets `me` and never `registered`; a code link sets both.
|
|
83
|
-
this.registered = !!(state.creds.registered || state.creds.me);
|
|
84
166
|
if (!this.registered && this.opts.pairing === 'qr')
|
|
85
167
|
this.say('Scan the QR below with WhatsApp > Linked devices > Link a device.');
|
|
86
168
|
}
|
|
@@ -131,6 +213,9 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
131
213
|
this.state = 'connected';
|
|
132
214
|
this.registered = true;
|
|
133
215
|
this.backoffMs = 3000;
|
|
216
|
+
this.since = this.now();
|
|
217
|
+
this.conflict = false;
|
|
218
|
+
this.reopened = false;
|
|
134
219
|
const me = normalizeJid(sock.user?.id);
|
|
135
220
|
this.log(`whatsapp: connected as ${me ? me.slice(0, 4) + '…' : '?'}`);
|
|
136
221
|
this.emit('open');
|
|
@@ -142,7 +227,10 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
142
227
|
}
|
|
143
228
|
if (u.connection === 'close') {
|
|
144
229
|
this.state = 'disconnected';
|
|
230
|
+
this.since = this.now();
|
|
231
|
+
this.emit('close');
|
|
145
232
|
const code = u.lastDisconnect?.error?.output?.statusCode;
|
|
233
|
+
this.conflict = code === DisconnectReason.connectionReplaced;
|
|
146
234
|
const why = u.lastDisconnect?.error?.message ?? '';
|
|
147
235
|
this.codeRequested = false; // a reconnect opens a new pairing window; a new code is requested if still unpaired
|
|
148
236
|
if (this.stopping)
|
|
@@ -156,10 +244,12 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
156
244
|
rmSync(this.opts.authDir, { recursive: true, force: true });
|
|
157
245
|
mkdirSync(this.opts.authDir, { recursive: true, mode: 0o700 });
|
|
158
246
|
this.emit('restart');
|
|
159
|
-
|
|
247
|
+
this.reopenIn(1000);
|
|
160
248
|
return;
|
|
161
249
|
}
|
|
250
|
+
// Logged out, nothing reconnects, and a fresh process would not be paired either: the check ends too.
|
|
162
251
|
if (code === DisconnectReason.loggedOut) {
|
|
252
|
+
clearInterval(this.watch);
|
|
163
253
|
this.log('whatsapp: logged out; delete the auth dir and pair again');
|
|
164
254
|
this.emit('logged-out');
|
|
165
255
|
return;
|
|
@@ -180,9 +270,21 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
180
270
|
delay = this.backoffMs;
|
|
181
271
|
}
|
|
182
272
|
this.log(`whatsapp: closed code=${code ?? '?'} reconnect_in=${delay}ms`);
|
|
183
|
-
|
|
273
|
+
this.reopenIn(delay);
|
|
184
274
|
}
|
|
185
275
|
}
|
|
276
|
+
/** One pending reopen at a time: the check() path and a close must not each start a socket. */
|
|
277
|
+
reopenIn(ms) {
|
|
278
|
+
clearTimeout(this.reconnect);
|
|
279
|
+
this.reconnect = setTimeout(() => void this.open().catch((e) => this.log(`whatsapp: reopen failed ${e.message}`)), ms);
|
|
280
|
+
}
|
|
281
|
+
/** End a socket we are done with. end() is async: a rejection would escape the try and become an unhandled one. */
|
|
282
|
+
retire(sock) {
|
|
283
|
+
try {
|
|
284
|
+
sock?.end(undefined)?.catch(() => { });
|
|
285
|
+
}
|
|
286
|
+
catch { /* already closed */ }
|
|
287
|
+
}
|
|
186
288
|
ourIds() {
|
|
187
289
|
const u = this.sock?.user;
|
|
188
290
|
return [normalizeJid(u?.id), normalizeJid(u?.lid)].filter(Boolean);
|
|
@@ -208,7 +310,7 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
208
310
|
if (inbox && p.media && p.media.kind !== 'sticker') {
|
|
209
311
|
if ((p.media.size ?? 0) > MAX_MEDIA) {
|
|
210
312
|
this.log(`whatsapp: media over ${MAX_MEDIA >> 20} MB not downloaded chat=${p.chat.slice(0, 8)}…`);
|
|
211
|
-
note(`a ${p.media.kind} over ${MAX_MEDIA >> 20} MB was sent and not downloaded`);
|
|
313
|
+
note(`a ${KIND_NAME[p.media.kind] ?? p.media.kind} over ${MAX_MEDIA >> 20} MB was sent and not downloaded`);
|
|
212
314
|
}
|
|
213
315
|
else if (!this.quota.take(senderId)) {
|
|
214
316
|
this.log(`whatsapp: media not downloaded chat=${p.chat.slice(0, 8)}… reason=sender-hourly-limit`);
|
|
@@ -229,11 +331,13 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
229
331
|
media.push(dest);
|
|
230
332
|
else {
|
|
231
333
|
this.log(`whatsapp: media passed ${MAX_MEDIA >> 20} MB while downloading, dropped chat=${p.chat.slice(0, 8)}…`);
|
|
232
|
-
note(`a ${p.media.kind} over ${MAX_MEDIA >> 20} MB was sent and not downloaded`);
|
|
334
|
+
note(`a ${KIND_NAME[p.media.kind] ?? p.media.kind} over ${MAX_MEDIA >> 20} MB was sent and not downloaded`);
|
|
233
335
|
}
|
|
234
336
|
}
|
|
235
337
|
catch (e) {
|
|
338
|
+
// Said to the agent too (#35): a file with no caption would otherwise be no turn at all.
|
|
236
339
|
this.log(`whatsapp: media download failed chat=${p.chat.slice(0, 8)}…: ${String(e.message ?? e).slice(0, 160)}`);
|
|
340
|
+
note(`the ${KIND_NAME[p.media.kind] ?? p.media.kind} sent could not be downloaded`);
|
|
237
341
|
}
|
|
238
342
|
}
|
|
239
343
|
if (!head.text && !media.length)
|
|
@@ -242,11 +346,37 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
242
346
|
void this.opts.onInbound({ ...head, media }).catch((e) => this.log(`whatsapp: handler error ${e.message}`));
|
|
243
347
|
});
|
|
244
348
|
}
|
|
245
|
-
|
|
349
|
+
/**
|
|
350
|
+
* `mentions`: an agent's answer or `angelia send` may tag group members with `@<number>`; Angelia's own
|
|
351
|
+
* lines and progress lines never do. Every group text with `@<digit>` is rewritten either way: a phone
|
|
352
|
+
* the lid map knows goes out as the lid (withMentions). A group whose members cannot be fetched gets
|
|
353
|
+
* that text with no tags: the answer matters more than the tag.
|
|
354
|
+
*/
|
|
355
|
+
async send(chat, text, _thread, o = {}) {
|
|
246
356
|
if (!this.sock || !this.connected)
|
|
247
357
|
throw new Error('whatsapp: not connected');
|
|
358
|
+
if (chat.endsWith('@g.us') && /@\+?\d/.test(text)) {
|
|
359
|
+
const meta = o.mentions ? await this.groupMeta(chat).catch((e) => {
|
|
360
|
+
this.log(`whatsapp: group members not fetched, sent without tags chat=${chat.slice(0, 8)}…: ${String(e.message ?? e).slice(0, 120)}`);
|
|
361
|
+
return undefined;
|
|
362
|
+
}) : undefined;
|
|
363
|
+
const m = withMentions(text, meta?.participants, { lidFor: (n) => this.lids.lidFor(n) });
|
|
364
|
+
if (m.capped)
|
|
365
|
+
this.log(`whatsapp: ${m.mentions.length + m.capped} members named in one message, ${m.capped} not tagged (at most ${MAX_MENTIONS}) chat=${chat.slice(0, 8)}…`);
|
|
366
|
+
await this.post(chat, m.mentions.length ? { text: m.text, mentions: m.mentions } : { text: m.text });
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
248
369
|
await this.post(chat, { text });
|
|
249
370
|
}
|
|
371
|
+
/** A group's metadata, from the cache or the server (which then fills the cache). */
|
|
372
|
+
async groupMeta(chat) {
|
|
373
|
+
const hit = this.groups.get(chat);
|
|
374
|
+
if (hit)
|
|
375
|
+
return hit;
|
|
376
|
+
const meta = await this.sock.groupMetadata(chat);
|
|
377
|
+
this.groups.set(chat, meta);
|
|
378
|
+
return meta;
|
|
379
|
+
}
|
|
250
380
|
/** Every outgoing message goes through here, so a retry receipt can find it later. */
|
|
251
381
|
async post(chat, content) {
|
|
252
382
|
this.sent.remember(await this.sock.sendMessage(chat, content));
|
|
@@ -255,7 +385,7 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
255
385
|
async chatName(chat) {
|
|
256
386
|
if (!this.sock || !chat.endsWith('@g.us'))
|
|
257
387
|
return undefined;
|
|
258
|
-
return (await this.
|
|
388
|
+
return (await this.groupMeta(chat)).subject || undefined;
|
|
259
389
|
}
|
|
260
390
|
/** Attach a file. Baileys streams it from disk, so a large document never sits in this process's heap. */
|
|
261
391
|
async sendMedia(chat, m) {
|
|
@@ -312,11 +442,9 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
312
442
|
for (const t of this.typingTimers.values())
|
|
313
443
|
clearInterval(t);
|
|
314
444
|
this.typingTimers.clear();
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
catch { /* already closed */ }
|
|
445
|
+
clearTimeout(this.reconnect);
|
|
446
|
+
clearInterval(this.watch);
|
|
447
|
+
this.retire(this.sock);
|
|
320
448
|
this.state = 'disconnected';
|
|
321
449
|
}
|
|
322
450
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Group metadata for a short while. Baileys asks the server for a group's members on every group send
|
|
3
|
+
* unless `cachedGroupMetadata` answers, and a tagged reply asks once more before that: one answer in
|
|
4
|
+
* three parts would be six queries, and WhatsApp answers a burst with rate-overlimit. An entry lives
|
|
5
|
+
* `ttlMs` and is dropped as soon as the group or its members change, so a new member is never left out
|
|
6
|
+
* of the sender keys for long.
|
|
7
|
+
*/
|
|
8
|
+
export class GroupCache {
|
|
9
|
+
ttlMs;
|
|
10
|
+
now;
|
|
11
|
+
entries = new Map();
|
|
12
|
+
constructor(ttlMs = 60_000, now = Date.now) {
|
|
13
|
+
this.ttlMs = ttlMs;
|
|
14
|
+
this.now = now;
|
|
15
|
+
}
|
|
16
|
+
get(jid) {
|
|
17
|
+
const e = this.entries.get(jid);
|
|
18
|
+
if (!e)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (this.now() - e.at >= this.ttlMs) {
|
|
21
|
+
this.entries.delete(jid);
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
return e.value;
|
|
25
|
+
}
|
|
26
|
+
set(jid, value) {
|
|
27
|
+
const now = this.now();
|
|
28
|
+
// Expired entries go when a new one comes, so a group read once is not kept for good.
|
|
29
|
+
for (const [k, e] of this.entries)
|
|
30
|
+
if (now - e.at >= this.ttlMs)
|
|
31
|
+
this.entries.delete(k);
|
|
32
|
+
this.entries.set(jid, { at: now, value });
|
|
33
|
+
}
|
|
34
|
+
drop(jid) { if (jid)
|
|
35
|
+
this.entries.delete(jid); }
|
|
36
|
+
clear() { this.entries.clear(); }
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=groups.js.map
|
|
@@ -17,12 +17,14 @@ export function bareId(jid) { return normalizeJid(jid).replace(/@.*$/, ''); }
|
|
|
17
17
|
export class LidMap {
|
|
18
18
|
authDir;
|
|
19
19
|
lidToPhone = new Map();
|
|
20
|
+
phoneToLid = new Map();
|
|
20
21
|
constructor(authDir) {
|
|
21
22
|
this.authDir = authDir;
|
|
22
23
|
this.reload();
|
|
23
24
|
}
|
|
24
25
|
reload() {
|
|
25
26
|
this.lidToPhone.clear();
|
|
27
|
+
this.phoneToLid.clear();
|
|
26
28
|
let files = [];
|
|
27
29
|
try {
|
|
28
30
|
files = readdirSync(this.authDir);
|
|
@@ -36,8 +38,11 @@ export class LidMap {
|
|
|
36
38
|
continue;
|
|
37
39
|
try {
|
|
38
40
|
const lid = JSON.parse(readFileSync(join(this.authDir, f), 'utf8'));
|
|
39
|
-
if (lid)
|
|
40
|
-
|
|
41
|
+
if (!lid)
|
|
42
|
+
continue;
|
|
43
|
+
const bare = String(lid).replace(/@.*$/, '');
|
|
44
|
+
this.lidToPhone.set(bare, m[1]);
|
|
45
|
+
this.phoneToLid.set(m[1], bare);
|
|
41
46
|
}
|
|
42
47
|
catch { /* a half-written file; next reload */ }
|
|
43
48
|
}
|
|
@@ -47,5 +52,7 @@ export class LidMap {
|
|
|
47
52
|
const bare = bareId(jid);
|
|
48
53
|
return jid.endsWith('@lid') ? (this.lidToPhone.get(bare) ?? bare) : bare;
|
|
49
54
|
}
|
|
55
|
+
/** The bare lid of a phone number (bare digits), when known: the way back of phoneFor(). */
|
|
56
|
+
lidFor(phone) { return this.phoneToLid.get(phone); }
|
|
50
57
|
}
|
|
51
58
|
//# sourceMappingURL=ids.js.map
|
|
@@ -29,10 +29,22 @@ export class SeenIds {
|
|
|
29
29
|
return true;
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Unwrap ephemeral / view-once / caption wrappers to the message body Baileys nests them in. WhatsApp
|
|
34
|
+
* stacks them (a document with a caption in a disappearing chat is ephemeral > documentWithCaption >
|
|
35
|
+
* document), so this peels up to five layers, as Baileys' own normalizeMessageContent does (#34).
|
|
36
|
+
* Baileys also peels editedMessage and the group status wrappers; those are left out on purpose, an edit
|
|
37
|
+
* holds a protocol message and a group status post must not become a turn.
|
|
38
|
+
*/
|
|
33
39
|
export function messageContent(m) {
|
|
34
|
-
|
|
35
|
-
|
|
40
|
+
let c = m.message ?? {};
|
|
41
|
+
for (let i = 0; i < 5; i++) {
|
|
42
|
+
const inner = c.ephemeralMessage ?? c.viewOnceMessage ?? c.viewOnceMessageV2 ?? c.viewOnceMessageV2Extension ?? c.documentWithCaptionMessage;
|
|
43
|
+
if (!inner?.message)
|
|
44
|
+
break;
|
|
45
|
+
c = inner.message;
|
|
46
|
+
}
|
|
47
|
+
return c;
|
|
36
48
|
}
|
|
37
49
|
/**
|
|
38
50
|
* Baileys message -> the router's view of it, or null when it is nothing we act on
|
|
@@ -93,4 +105,51 @@ export function parseMessage(m, us) {
|
|
|
93
105
|
export function toInbound(p, senderId, mediaPaths) {
|
|
94
106
|
return { platform: 'whatsapp', chat: p.chat, sender: senderId, senderName: p.senderName, text: p.text, isGroup: p.isGroup, mentioned: p.mentioned, media: mediaPaths };
|
|
95
107
|
}
|
|
108
|
+
/** At most this many members are tagged in one message: a tag notifies even a member who muted the group. */
|
|
109
|
+
export const MAX_MENTIONS = 5;
|
|
110
|
+
/** `@<5-20 digits>`, `+` allowed, and never a part of a longer number. Not after a Latin letter or a
|
|
111
|
+
* digit (an email address, `a@1555…`), nor inside a URL (`x.com/@1555…`, `?u=@1555…`, `#@1555…`) or a
|
|
112
|
+
* domain (`@1555….example.com`). A non-Latin letter may come right before it, as a Hebrew prefix
|
|
113
|
+
* does (`ל@1555…`), and `_` on either side (WhatsApp italics). */
|
|
114
|
+
const TOKEN = /(?<![\p{Script=Latin}\p{N}/.@=?#])@\+?(\d{5,20})(?![\p{L}\p{N}]|\.[\p{L}\p{N}_])/gu;
|
|
115
|
+
/** Code is shown as written: a fenced block (an unclosed one runs to the end) or an inline span. */
|
|
116
|
+
const CODE = /```[\s\S]*?(?:```|$)|`[^`\n]+`/g;
|
|
117
|
+
/**
|
|
118
|
+
* `@<number>` in an outgoing group text. Two things, kept apart:
|
|
119
|
+
* - The rewrite, always: a phone whose lid the lid map knows becomes `@<lid>`, so a phone the group
|
|
120
|
+
* hides never goes out, whether or not a tag is made (a progress line, a failed member fetch, a
|
|
121
|
+
* token past the cap). It needs no member list and no network.
|
|
122
|
+
* - The tag, only with `members` (the caller wants tags and has the list): a phone or lid of a member
|
|
123
|
+
* becomes a mention, written as the member's `id`, the form WhatsApp renders as their name. At most
|
|
124
|
+
* `max` distinct members; the others are named as written (or by lid), untagged, and `capped`
|
|
125
|
+
* counts those members.
|
|
126
|
+
* A number that is no member is left as written. Text inside backticks is never touched.
|
|
127
|
+
*/
|
|
128
|
+
export function withMentions(text, members, o = {}) {
|
|
129
|
+
const max = o.max ?? MAX_MENTIONS;
|
|
130
|
+
const byNum = new Map();
|
|
131
|
+
for (const p of members ?? [])
|
|
132
|
+
for (const j of [p.id, p.lid, p.phoneNumber])
|
|
133
|
+
if (j)
|
|
134
|
+
byNum.set(bareId(j), normalizeJid(p.id));
|
|
135
|
+
const mentions = new Set(), capped = new Set();
|
|
136
|
+
const tag = (plain) => plain.replace(TOKEN, (tok, n) => {
|
|
137
|
+
const lid = o.lidFor?.(n);
|
|
138
|
+
const jid = byNum.get(n) ?? (lid ? byNum.get(lid) : undefined);
|
|
139
|
+
if (jid && (mentions.has(jid) || mentions.size < max)) {
|
|
140
|
+
mentions.add(jid);
|
|
141
|
+
return `@${bareId(jid)}`;
|
|
142
|
+
}
|
|
143
|
+
if (jid)
|
|
144
|
+
capped.add(jid);
|
|
145
|
+
return lid ? `@${lid}` : tok;
|
|
146
|
+
});
|
|
147
|
+
let out = '', at = 0;
|
|
148
|
+
for (const c of text.matchAll(CODE)) {
|
|
149
|
+
out += tag(text.slice(at, c.index)) + c[0];
|
|
150
|
+
at = c.index + c[0].length;
|
|
151
|
+
}
|
|
152
|
+
out += tag(text.slice(at));
|
|
153
|
+
return { text: out, mentions: [...mentions], capped: capped.size };
|
|
154
|
+
}
|
|
96
155
|
//# sourceMappingURL=parse.js.map
|
package/dist/brain/codex.js
CHANGED
|
@@ -300,6 +300,13 @@ export class CodexBrain extends EventEmitter {
|
|
|
300
300
|
continue;
|
|
301
301
|
}
|
|
302
302
|
if (m.__approval) {
|
|
303
|
+
// What Codex said before it asks ("I'll request write access…") goes out first: it arrived in the
|
|
304
|
+
// chat after the permission line otherwise, as the turn's final text.
|
|
305
|
+
if (pendingText && pendingText !== lastProgress) {
|
|
306
|
+
lastProgress = pendingText;
|
|
307
|
+
yield { kind: 'progress', text: pendingText };
|
|
308
|
+
pendingText = '';
|
|
309
|
+
}
|
|
303
310
|
const a = m.__approval;
|
|
304
311
|
const p = a.params ?? {};
|
|
305
312
|
const id = randomUUID();
|
package/dist/build.json
CHANGED
package/dist/cli/cli-args.js
CHANGED
|
@@ -38,9 +38,10 @@ export const COMMANDS = {
|
|
|
38
38
|
profiles: { line: L.config, flags: { '--json': false } },
|
|
39
39
|
profile: { line: L.profile },
|
|
40
40
|
compile: { line: L.compile, flags: { '--write': false, '--check': false, '--config': true } },
|
|
41
|
-
// --hash: what a timer passes, so a changed job refuses to run from an old timer
|
|
41
|
+
// --hash: what a timer passes, so a changed job refuses to run from an old timer; --once, a one-time
|
|
42
|
+
// job's date, so its timer knows it is one whatever the file says by then.
|
|
42
43
|
accept: { line: L.accept, flags: { '--check': false, '--expect': true, '--config': true } },
|
|
43
|
-
jobs: { line: L.jobs, flags: { '--config': true, '--hash': true } },
|
|
44
|
+
jobs: { line: L.jobs, flags: { '--config': true, '--hash': true, '--once': true } },
|
|
44
45
|
workspace: { line: L.workspace, usage: 'usage: angelia workspace sync [--quiet]\n angelia workspace commit -m <message> [path...] [--no-push]', flags: { '--quiet': false, '-m': true, '--message': true, '--no-push': false } },
|
|
45
46
|
send: { line: L.send, text: true },
|
|
46
47
|
'send-media': { line: L.media, flags: { '--name': true, '--caption': true, '--no-voice': false } },
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
/**
|
|
4
|
+
* The chats whose turn was running when the daemon stopped. An orderly shutdown (SIGTERM, /restart,
|
|
5
|
+
* WhatsApp dead) stops the adapters before the orchestrator (daemon.ts), so nothing can be said to those
|
|
6
|
+
* chats then: the keys are written here first, and the daemon that starts next says one line in each.
|
|
7
|
+
* Only an orderly shutdown writes the file: a crash, a SIGKILL or the exit timer firing before this ran
|
|
8
|
+
* leaves the old silence. The messages are not replayed. WhatsApp delivers what was sent while the link
|
|
9
|
+
* was down when it opens again (offline notifications, which the adapter takes as any message, with
|
|
10
|
+
* repeats dropped by id); Telegram holds the updates nobody fetched for the next getUpdates. The message
|
|
11
|
+
* whose turn was cut had been fetched and confirmed before the stop, as were the ones waiting behind it,
|
|
12
|
+
* so only their senders can send them again.
|
|
13
|
+
*/
|
|
14
|
+
export const CUT_TURNS = 'cut-turns.json';
|
|
15
|
+
export const CUT_LINE = 'Angelia restarted while working on your message. Send it again.';
|
|
16
|
+
/** Older than this, the file is from a daemon nobody started again for a day; the chat has moved on. A
|
|
17
|
+
* reboot or a long update still gets the line, and a day is Telegram's own window for held updates. */
|
|
18
|
+
const CUT_TTL_MS = 24 * 3600_000;
|
|
19
|
+
export function writeCutTurns(stateDir, keys) {
|
|
20
|
+
if (!keys.length)
|
|
21
|
+
return;
|
|
22
|
+
writeFileSync(join(stateDir, CUT_TURNS), JSON.stringify({ keys, at: new Date().toISOString() }));
|
|
23
|
+
}
|
|
24
|
+
/** The keys the last shutdown wrote, and the file is gone; none when there is no file or it is stale. */
|
|
25
|
+
export function takeCutTurns(stateDir, now = Date.now()) {
|
|
26
|
+
const path = join(stateDir, CUT_TURNS);
|
|
27
|
+
let note;
|
|
28
|
+
try {
|
|
29
|
+
note = JSON.parse(readFileSync(path, 'utf8'));
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
unlinkSync(path);
|
|
36
|
+
}
|
|
37
|
+
catch { }
|
|
38
|
+
if (!Array.isArray(note.keys) || !note.at || now - Date.parse(note.at) > CUT_TTL_MS)
|
|
39
|
+
return [];
|
|
40
|
+
return note.keys.filter((k) => typeof k === 'string');
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=cut-turns.js.map
|