angelia-gateway 0.3.24 → 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/whatsapp/adapter.js +139 -15
- package/dist/adapters/whatsapp/groups.js +38 -0
- package/dist/adapters/whatsapp/ids.js +9 -2
- package/dist/adapters/whatsapp/parse.js +47 -0
- 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 +77 -12
- 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/secrets.js +2 -1
- package/dist/instance/switch-backend.js +27 -3
- 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 +1 -1
|
@@ -6,13 +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;
|
|
14
15
|
/** How a note to the agent names a kind of file: "a photo", "a voice note", never "a image". */
|
|
15
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;
|
|
16
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' };
|
|
17
23
|
/**
|
|
18
24
|
* WhatsApp as a linked device (Baileys, in-process). One socket per daemon. Pairing by code
|
|
@@ -31,26 +37,87 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
31
37
|
log;
|
|
32
38
|
say;
|
|
33
39
|
backoffMs = 3000;
|
|
40
|
+
reconnect;
|
|
34
41
|
lastBackoffNotice = 0;
|
|
35
42
|
/** A field, not made in open(): what we sent must outlive a reconnect, when a retry needs it most. */
|
|
36
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();
|
|
37
55
|
constructor(opts) {
|
|
38
56
|
super();
|
|
39
57
|
this.opts = opts;
|
|
40
58
|
this.log = opts.log ?? (() => { });
|
|
41
59
|
this.say = opts.say ?? ((l) => console.log(l));
|
|
60
|
+
this.now = opts.now ?? Date.now;
|
|
42
61
|
this.lids = new LidMap(opts.authDir);
|
|
43
62
|
}
|
|
44
63
|
get connected() { return this.state === 'connected'; }
|
|
45
64
|
async start() {
|
|
46
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();
|
|
47
76
|
await this.open();
|
|
48
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
|
+
}
|
|
49
108
|
async open() {
|
|
50
109
|
if (this.stopping)
|
|
51
110
|
return;
|
|
52
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
|
+
}
|
|
53
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);
|
|
54
121
|
// Checked before any socket exists: a setup that cannot pair would otherwise leave a socket and
|
|
55
122
|
// its reconnects behind at every retry of the start.
|
|
56
123
|
if (!(state.creds.registered || state.creds.me) && this.opts.pairing === 'code' && !(this.opts.phone ?? '').replace(/\D/g, ''))
|
|
@@ -59,7 +126,7 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
59
126
|
// ANGELIA_WA_DEBUG=<file>: full Baileys debug log to that file (pairing diagnostics). Never on by default: it contains message payloads.
|
|
60
127
|
const debugFile = process.env.ANGELIA_WA_DEBUG;
|
|
61
128
|
const logger = debugFile ? pino({ level: 'trace' }, pino.destination({ dest: debugFile, sync: true })) : pino({ level: 'silent' });
|
|
62
|
-
const sock = makeWASocket({
|
|
129
|
+
const sock = (this.opts.makeSocket ?? makeWASocket)({
|
|
63
130
|
...(version ? { version } : {}),
|
|
64
131
|
auth: state,
|
|
65
132
|
logger,
|
|
@@ -71,18 +138,31 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
71
138
|
// Baileys' own cache answers first, but only for 5 minutes and it is cleared when the socket
|
|
72
139
|
// ends. Unknown ids get undefined: Baileys then resends nothing, which is the honest outcome.
|
|
73
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),
|
|
74
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;
|
|
75
149
|
this.sock = sock;
|
|
76
|
-
|
|
77
|
-
|
|
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); });
|
|
78
160
|
sock.ev.on('messages.upsert', ({ messages, type }) => {
|
|
79
161
|
if (type !== 'notify' && type !== 'append')
|
|
80
162
|
return;
|
|
81
163
|
for (const m of messages)
|
|
82
164
|
void this.onMessage(m).catch((e) => this.log(`whatsapp: message error ${e.message}`));
|
|
83
165
|
});
|
|
84
|
-
// A QR link sets `me` and never `registered`; a code link sets both.
|
|
85
|
-
this.registered = !!(state.creds.registered || state.creds.me);
|
|
86
166
|
if (!this.registered && this.opts.pairing === 'qr')
|
|
87
167
|
this.say('Scan the QR below with WhatsApp > Linked devices > Link a device.');
|
|
88
168
|
}
|
|
@@ -133,6 +213,9 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
133
213
|
this.state = 'connected';
|
|
134
214
|
this.registered = true;
|
|
135
215
|
this.backoffMs = 3000;
|
|
216
|
+
this.since = this.now();
|
|
217
|
+
this.conflict = false;
|
|
218
|
+
this.reopened = false;
|
|
136
219
|
const me = normalizeJid(sock.user?.id);
|
|
137
220
|
this.log(`whatsapp: connected as ${me ? me.slice(0, 4) + '…' : '?'}`);
|
|
138
221
|
this.emit('open');
|
|
@@ -144,7 +227,10 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
144
227
|
}
|
|
145
228
|
if (u.connection === 'close') {
|
|
146
229
|
this.state = 'disconnected';
|
|
230
|
+
this.since = this.now();
|
|
231
|
+
this.emit('close');
|
|
147
232
|
const code = u.lastDisconnect?.error?.output?.statusCode;
|
|
233
|
+
this.conflict = code === DisconnectReason.connectionReplaced;
|
|
148
234
|
const why = u.lastDisconnect?.error?.message ?? '';
|
|
149
235
|
this.codeRequested = false; // a reconnect opens a new pairing window; a new code is requested if still unpaired
|
|
150
236
|
if (this.stopping)
|
|
@@ -158,10 +244,12 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
158
244
|
rmSync(this.opts.authDir, { recursive: true, force: true });
|
|
159
245
|
mkdirSync(this.opts.authDir, { recursive: true, mode: 0o700 });
|
|
160
246
|
this.emit('restart');
|
|
161
|
-
|
|
247
|
+
this.reopenIn(1000);
|
|
162
248
|
return;
|
|
163
249
|
}
|
|
250
|
+
// Logged out, nothing reconnects, and a fresh process would not be paired either: the check ends too.
|
|
164
251
|
if (code === DisconnectReason.loggedOut) {
|
|
252
|
+
clearInterval(this.watch);
|
|
165
253
|
this.log('whatsapp: logged out; delete the auth dir and pair again');
|
|
166
254
|
this.emit('logged-out');
|
|
167
255
|
return;
|
|
@@ -182,9 +270,21 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
182
270
|
delay = this.backoffMs;
|
|
183
271
|
}
|
|
184
272
|
this.log(`whatsapp: closed code=${code ?? '?'} reconnect_in=${delay}ms`);
|
|
185
|
-
|
|
273
|
+
this.reopenIn(delay);
|
|
186
274
|
}
|
|
187
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
|
+
}
|
|
188
288
|
ourIds() {
|
|
189
289
|
const u = this.sock?.user;
|
|
190
290
|
return [normalizeJid(u?.id), normalizeJid(u?.lid)].filter(Boolean);
|
|
@@ -246,11 +346,37 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
246
346
|
void this.opts.onInbound({ ...head, media }).catch((e) => this.log(`whatsapp: handler error ${e.message}`));
|
|
247
347
|
});
|
|
248
348
|
}
|
|
249
|
-
|
|
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 = {}) {
|
|
250
356
|
if (!this.sock || !this.connected)
|
|
251
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
|
+
}
|
|
252
369
|
await this.post(chat, { text });
|
|
253
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
|
+
}
|
|
254
380
|
/** Every outgoing message goes through here, so a retry receipt can find it later. */
|
|
255
381
|
async post(chat, content) {
|
|
256
382
|
this.sent.remember(await this.sock.sendMessage(chat, content));
|
|
@@ -259,7 +385,7 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
259
385
|
async chatName(chat) {
|
|
260
386
|
if (!this.sock || !chat.endsWith('@g.us'))
|
|
261
387
|
return undefined;
|
|
262
|
-
return (await this.
|
|
388
|
+
return (await this.groupMeta(chat)).subject || undefined;
|
|
263
389
|
}
|
|
264
390
|
/** Attach a file. Baileys streams it from disk, so a large document never sits in this process's heap. */
|
|
265
391
|
async sendMedia(chat, m) {
|
|
@@ -316,11 +442,9 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
316
442
|
for (const t of this.typingTimers.values())
|
|
317
443
|
clearInterval(t);
|
|
318
444
|
this.typingTimers.clear();
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
323
|
-
catch { /* already closed */ }
|
|
445
|
+
clearTimeout(this.reconnect);
|
|
446
|
+
clearInterval(this.watch);
|
|
447
|
+
this.retire(this.sock);
|
|
324
448
|
this.state = 'disconnected';
|
|
325
449
|
}
|
|
326
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
|
|
@@ -105,4 +105,51 @@ export function parseMessage(m, us) {
|
|
|
105
105
|
export function toInbound(p, senderId, mediaPaths) {
|
|
106
106
|
return { platform: 'whatsapp', chat: p.chat, sender: senderId, senderName: p.senderName, text: p.text, isGroup: p.isGroup, mentioned: p.mentioned, media: mediaPaths };
|
|
107
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
|
+
}
|
|
108
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
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export const LIMITS = { telegram: 4000, whatsapp: 3500 };
|
|
2
|
-
/** Split text for a chat platform: paragraphs first, then lines, then hard cuts. Code fences are closed
|
|
2
|
+
/** Split text for a chat platform: paragraphs first, then lines, then hard cuts. Code fences are closed
|
|
3
|
+
* and reopened; a table cut in two gets its header row and separator row again. */
|
|
3
4
|
export function chunk(text, limit) {
|
|
4
5
|
const t = text.trim();
|
|
5
6
|
if (!t)
|
|
@@ -9,6 +10,9 @@ export function chunk(text, limit) {
|
|
|
9
10
|
const out = [];
|
|
10
11
|
let rest = t;
|
|
11
12
|
let open = null;
|
|
13
|
+
let table = null;
|
|
14
|
+
/** `rest` starts in the middle of a line: the last cut was a hard one, or at a space. */
|
|
15
|
+
let midLine = false;
|
|
12
16
|
while (rest.length) {
|
|
13
17
|
// A reopened fence costs its opener on top and its closer at the end. When that would eat more
|
|
14
18
|
// than half the room (a tiny limit), the piece goes out without it: a long code block then loses
|
|
@@ -16,7 +20,12 @@ export function chunk(text, limit) {
|
|
|
16
20
|
const reopen = open && fenceCost(open) <= limit / 2 ? open : null;
|
|
17
21
|
if (!reopen)
|
|
18
22
|
open = null;
|
|
19
|
-
|
|
23
|
+
// The same for a table's two rows: without them the next piece's rows read as a run of bars. Not on
|
|
24
|
+
// top of the rest of a row cut in the middle (the table is still open: the rows after it get them).
|
|
25
|
+
if (table && tableCost(table) > limit / 2)
|
|
26
|
+
table = null;
|
|
27
|
+
const again = table && rest.startsWith('|') ? table : null;
|
|
28
|
+
const head = prefix(reopen) + (again ? again.header + '\n' + again.sep + '\n' : '');
|
|
20
29
|
if (head.length + rest.length <= limit) {
|
|
21
30
|
out.push(head + rest);
|
|
22
31
|
break;
|
|
@@ -45,7 +54,27 @@ export function chunk(text, limit) {
|
|
|
45
54
|
if (cut > 1 && /[\uD800-\uDBFF]/.test(rest[cut - 1]))
|
|
46
55
|
cut -= 1;
|
|
47
56
|
}
|
|
48
|
-
|
|
57
|
+
let after = rest.slice(cut).replace(/^\s+/, '');
|
|
58
|
+
// A cut between a table's header row and its separator row would leave the next piece starting
|
|
59
|
+
// with a lone separator: the header row moves over with it, and the repeat below then sees the table.
|
|
60
|
+
// When the header row is the first line of this piece there is nothing to move it after: the
|
|
61
|
+
// separator comes up instead when the limit (not the room, which kept space for a closer) holds it.
|
|
62
|
+
const nl = rest.lastIndexOf('\n', cut - 1);
|
|
63
|
+
const sepEnd = after.indexOf('\n') < 0 ? after.length : after.indexOf('\n');
|
|
64
|
+
if (!next && !(nl < 0 && midLine) && /^\s*\|/.test(rest.slice(nl + 1, cut)) && SEPARATOR.test(after.slice(0, sepEnd))) {
|
|
65
|
+
const end = rest.length - after.length + sepEnd;
|
|
66
|
+
if (nl > 0)
|
|
67
|
+
cut = nl;
|
|
68
|
+
else if ((head + rest.slice(0, end)).trim().length <= limit)
|
|
69
|
+
cut = end;
|
|
70
|
+
piece = head + rest.slice(0, cut);
|
|
71
|
+
after = rest.slice(cut).replace(/^\s+/, '');
|
|
72
|
+
}
|
|
73
|
+
// The table this piece ends inside of, if any: a row cut in the middle keeps it open, and the rows
|
|
74
|
+
// after the rest of that row get the two rows on top again.
|
|
75
|
+
table = tableAt(rest.slice(0, cut), open, table, midLine);
|
|
76
|
+
midLine = rest[cut - 1] !== '\n' && !rest.slice(cut, rest.length - after.length).includes('\n');
|
|
77
|
+
rest = after;
|
|
49
78
|
open = next;
|
|
50
79
|
out.push(piece.trim());
|
|
51
80
|
}
|
|
@@ -62,20 +91,56 @@ function prefix(fence) {
|
|
|
62
91
|
* rules (#36): a backtick opener's info string holds no backtick, so a line of inline code such as
|
|
63
92
|
* "```x``` is the flag" opens nothing; a closer is at least as long as its opener and carries no info
|
|
64
93
|
* string, so a ``` line inside a ```` block, or a tagged one, is content.
|
|
94
|
+
* Backtick fences only. A tilde fence (~~~) and an indented code block (four spaces) are code in
|
|
95
|
+
* CommonMark too, and are not tracked: the CLIs' answers write code in backtick fences, so a cut
|
|
96
|
+
* inside either of the other two was never seen; one would lose the formatting of that block in the
|
|
97
|
+
* pieces after the cut, never its text.
|
|
65
98
|
*/
|
|
66
99
|
function fenceState(piece, open) {
|
|
67
100
|
let state = open;
|
|
68
|
-
for (const line of piece.split('\n'))
|
|
69
|
-
|
|
70
|
-
|
|
101
|
+
for (const line of piece.split('\n'))
|
|
102
|
+
state = fenceStep(line, state);
|
|
103
|
+
return state;
|
|
104
|
+
}
|
|
105
|
+
function fenceStep(line, state) {
|
|
106
|
+
const m = /^\s*(`{3,10})(?!`)(.*)$/.exec(line);
|
|
107
|
+
if (!m)
|
|
108
|
+
return state;
|
|
109
|
+
const info = m[2].trim();
|
|
110
|
+
if (state)
|
|
111
|
+
return m[1].length >= state.closer.length && !info ? null : state;
|
|
112
|
+
return info.includes('`') ? null : { opener: m[1] + (/^[\w+#.-]{0,20}/.exec(info)?.[0] ?? ''), closer: m[1] };
|
|
113
|
+
}
|
|
114
|
+
function tableCost(t) {
|
|
115
|
+
return t.header.length + 1 + t.sep.length + 1;
|
|
116
|
+
}
|
|
117
|
+
const SEPARATOR = /^\s*\|\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
118
|
+
/**
|
|
119
|
+
* The table `piece` ends inside of, given the fence and table in force at its start, or null. A table is
|
|
120
|
+
* a run of lines that start with a bar, the first a header and the second a separator (|---|); the run
|
|
121
|
+
* ends at the first line without a bar. Inside a fence a line is code, whatever it starts with. A GFM
|
|
122
|
+
* table without leading bars (`a | b`) is not tracked: the CLIs rarely write one, and its rows after a
|
|
123
|
+
* cut still read as text.
|
|
124
|
+
*/
|
|
125
|
+
function tableAt(piece, open, table, midLine = false) {
|
|
126
|
+
let fence = open, state = table, header = null;
|
|
127
|
+
// The first line is the rest of one cut in the middle: the line it belongs to was counted already.
|
|
128
|
+
for (const line of piece.split('\n').slice(midLine ? 1 : 0)) {
|
|
129
|
+
const was = fence;
|
|
130
|
+
fence = fenceStep(line, fence);
|
|
131
|
+
if (was || fence || !/^\s*\|/.test(line)) {
|
|
132
|
+
state = null;
|
|
133
|
+
header = null;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (state)
|
|
71
137
|
continue;
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
state = null;
|
|
138
|
+
if (header && SEPARATOR.test(line)) {
|
|
139
|
+
state = { header, sep: line.trim() };
|
|
140
|
+
header = null;
|
|
76
141
|
}
|
|
77
|
-
else
|
|
78
|
-
|
|
142
|
+
else
|
|
143
|
+
header = line.trim();
|
|
79
144
|
}
|
|
80
145
|
return state;
|
|
81
146
|
}
|
|
@@ -14,6 +14,11 @@ export function failureLine(reason, home, group = false) {
|
|
|
14
14
|
return `Something broke on my side (${tidy.slice(0, 300)}). Try again, or /new.`;
|
|
15
15
|
}
|
|
16
16
|
export const PERMISSION_TIMEOUT_LINE = 'No answer to the permission request in time, so it was denied.';
|
|
17
|
+
/** A turn that ended well with nothing new for the chat. Grok Build ends its turn this way after a denial
|
|
18
|
+
* (measured 2026-10-27), so the chat saw its own "no" and then nothing; Claude Code in print mode, Codex
|
|
19
|
+
* and pi can all end a turn with an empty final too. One line, so the chat knows the turn is over. */
|
|
20
|
+
export const DENIED_LINE = 'Denied; the agent stopped.';
|
|
21
|
+
export const NO_ANSWER_LINE = 'The agent ended its turn without an answer. Send your message again, or /new for a fresh session.';
|
|
17
22
|
export const UNMATCHED_LINE = '[Angelia] This chat is not routed to a profile.';
|
|
18
23
|
export const NOT_OWNER_LINE = 'Only an owner of this chat can do that.';
|
|
19
24
|
/** A chat answer to a request no hook waits for any more (it stepped aside when the chat stopped
|