angelia-gateway 0.3.27 → 0.3.29
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/README.md +1 -1
- package/dist/adapters/telegram/adapter.js +142 -7
- package/dist/adapters/whatsapp/adapter.js +8 -5
- package/dist/adapters/whatsapp/parse.js +8 -2
- package/dist/brain/argv.js +1 -1
- package/dist/brain/canary.js +618 -0
- package/dist/brain/catalog.js +1 -0
- package/dist/brain/claude.js +1 -1
- package/dist/brain/codex.js +3 -1
- package/dist/brain/grok.js +3 -1
- package/dist/brain/pi.js +3 -1
- package/dist/brain/tmux.js +45 -6
- package/dist/brain/tool-request.js +38 -0
- package/dist/brain/tui-permissions.js +1 -1
- package/dist/brain/tui.js +501 -30
- package/dist/build.json +3 -3
- package/dist/capabilities/compile.js +55 -3
- package/dist/cli/cli-args.js +19 -0
- package/dist/cli/cli.js +9 -0
- package/dist/core/deliver/text.js +64 -2
- package/dist/core/orchestrator.js +394 -44
- package/dist/core/permission-rules.js +678 -0
- package/dist/daemon/api/client.js +47 -13
- package/dist/daemon/api/routes.js +1 -1
- package/dist/daemon/daemon.js +1 -1
- package/dist/daemon/health.js +326 -0
- package/dist/instance/accepted.js +3 -1
- package/dist/instance/config/load.js +25 -2
- package/dist/instance/config/schema.js +49 -4
- package/dist/instance/guide.js +35 -2
- package/dist/instance/profiles.js +2 -1
- package/package.json +1 -1
- package/scripts/tui-stop-hook.mjs +18 -2
- package/scripts/turn-origin.mjs +290 -0
package/README.md
CHANGED
|
@@ -173,7 +173,7 @@ Back at your desk? In a Claude Code chat, `/status` ends with a line such as `cd
|
|
|
173
173
|
An assistant that can read your files can be talked into reading them aloud. Read the [security model](docs/security.md) before you give the bot to anyone but yourself.
|
|
174
174
|
|
|
175
175
|
- Only chats in the table reach the agent. In a group, only the owners are heard unless you name others.
|
|
176
|
-
- Only owners approve commands, change the session or restart. A group member's
|
|
176
|
+
- Only owners approve commands, change the session or restart. A group member's "yes" approves nothing.
|
|
177
177
|
- What the agent may do is its CLI's own permission mode. For a profile other people talk to, keep a cautious mode or set `sandbox: true`.
|
|
178
178
|
- Prompt injection is not solved: a web page or a forwarded message can still talk the agent into anything its permission mode allows.
|
|
179
179
|
|
|
@@ -3,6 +3,7 @@ import { extname } from 'node:path';
|
|
|
3
3
|
import { Readable } from 'node:stream';
|
|
4
4
|
import { COMMANDS } from '../../core/commands.js';
|
|
5
5
|
import { ext, isOpus } from '../../core/deliver/media.js';
|
|
6
|
+
import { shortId } from '../../core/deliver/text.js';
|
|
6
7
|
import { asVoice } from '../../voice/opus.js';
|
|
7
8
|
import { ChatChains, MAX_INBOUND, SenderQuota, saveInbound } from '../inbox.js';
|
|
8
9
|
/** A file download gives up after this long: a stalled one must not hold its chat for good. */
|
|
@@ -35,6 +36,12 @@ export const STAND_IN_IDS = [1087968824, 136817688, 777000];
|
|
|
35
36
|
export function standIn(m) {
|
|
36
37
|
return !!m.sender_chat || (m.from !== undefined && STAND_IN_IDS.includes(m.from.id));
|
|
37
38
|
}
|
|
39
|
+
/** What a request's buttons carry back: the answer and the request's short id (callback_data, 1-64 bytes). */
|
|
40
|
+
const PRESS = /^ask:([yn]):([0-9a-z_-]{1,8})$/i;
|
|
41
|
+
/** What a send gives back: the message's id, and Telegram's date for it in ms (whole seconds). */
|
|
42
|
+
const stamp = (m) => ({ ...(m?.message_id !== undefined ? { id: String(m.message_id) } : {}), ...(m?.date ? { at: m.date * 1000 } : {}) });
|
|
43
|
+
/** Requests whose buttons are remembered for removal; past it the oldest go (their buttons then stay until pressed). */
|
|
44
|
+
const ASKED_MAX = 200;
|
|
38
45
|
export class TelegramAdapter {
|
|
39
46
|
opts;
|
|
40
47
|
bot;
|
|
@@ -49,6 +56,12 @@ export class TelegramAdapter {
|
|
|
49
56
|
retryMs = RETRY_FIRST_MS;
|
|
50
57
|
pollingSince;
|
|
51
58
|
loop = Promise.resolve();
|
|
59
|
+
/** The request whose buttons each message carries, by `<chat>/<message id>`, while it is open. */
|
|
60
|
+
asked = new Map();
|
|
61
|
+
/** Chats with a request line on its way out: its message id is not known yet (asking). */
|
|
62
|
+
asking = new Map();
|
|
63
|
+
/** What kind of chat each one is ('private', 'group', 'supergroup', 'channel'), as Telegram said. */
|
|
64
|
+
kinds = new Map();
|
|
52
65
|
/** What Telegram is doing right now: 'starting', 'polling', 'conflict: ...', 'stopped: ...' or
|
|
53
66
|
* 'error: ...'. `angelia status` shows this and nothing else. */
|
|
54
67
|
get state() { return this.current; }
|
|
@@ -59,6 +72,9 @@ export class TelegramAdapter {
|
|
|
59
72
|
this.username = opts.botInfo.username;
|
|
60
73
|
this.log = opts.log ?? (() => { });
|
|
61
74
|
this.bot.on('message', (ctx) => this.onMessage(ctx));
|
|
75
|
+
// callback_query is among the update types polling asks for by default (grammY passes an empty
|
|
76
|
+
// allowed_updates: every type but chat_member and the two reaction ones).
|
|
77
|
+
this.bot.on('callback_query', (ctx) => this.onPress(ctx));
|
|
62
78
|
// grammY rethrows anything a handler throws, and an unhandled rejection out of the polling
|
|
63
79
|
// loop takes the whole daemon down - every other chat on every other platform with it.
|
|
64
80
|
this.bot.catch((err) => this.log(`telegram: handler error ${err.message}`));
|
|
@@ -203,14 +219,30 @@ export class TelegramAdapter {
|
|
|
203
219
|
return;
|
|
204
220
|
}
|
|
205
221
|
const isGroup = m.chat.type === 'group' || m.chat.type === 'supergroup';
|
|
222
|
+
if (this.kinds.size >= 1000)
|
|
223
|
+
this.kinds.clear();
|
|
224
|
+
this.kinds.set(chat, m.chat.type);
|
|
206
225
|
const text = m.text ?? m.caption ?? '';
|
|
207
226
|
const me = `@${this.username.toLowerCase()}`;
|
|
227
|
+
// The bot's own @name as written, each time: what a bare "yes" may carry and still be bare.
|
|
228
|
+
const botMentions = [];
|
|
208
229
|
// A command tapped in a group's menu arrives as /status@bot: that addresses the bot as much as a mention does.
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
230
|
+
let mentioned = false;
|
|
231
|
+
for (const e of m.entities ?? m.caption_entities ?? []) {
|
|
232
|
+
const word = text.slice(e.offset, e.offset + e.length);
|
|
233
|
+
if (e.type === 'mention' && word.toLowerCase() === me) {
|
|
234
|
+
mentioned = true;
|
|
235
|
+
botMentions.push(word);
|
|
236
|
+
}
|
|
237
|
+
else if (e.type === 'bot_command' && word.toLowerCase().endsWith(me))
|
|
238
|
+
mentioned = true;
|
|
239
|
+
}
|
|
240
|
+
mentioned ||= m.reply_to_message?.from?.id === ctx.me.id;
|
|
241
|
+
// A reply, by the id of the message replied to. In a forum topic every message that is no reply
|
|
242
|
+
// still names the topic's first (service) message there: that is not one. A reply into another
|
|
243
|
+
// chat, or a bare quote, has no message of this chat to name.
|
|
244
|
+
const to = m.reply_to_message && !(m.is_topic_message && (m.reply_to_message.message_id === m.message_thread_id || m.reply_to_message.forum_topic_created)) ? m.reply_to_message : undefined;
|
|
245
|
+
const reply = to ? { id: String(to.message_id), ours: to.from?.id === ctx.me.id } : m.external_reply || m.quote ? { ours: false } : undefined;
|
|
214
246
|
// What a reply quotes: the part the user selected when there is one (Bot API TextQuote; the only text
|
|
215
247
|
// a reply to another chat, external_reply, carries), else the whole message replied to, or its caption.
|
|
216
248
|
const quoted = m.quote?.text || m.reply_to_message?.text || m.reply_to_message?.caption || undefined;
|
|
@@ -220,6 +252,9 @@ export class TelegramAdapter {
|
|
|
220
252
|
sender: String(m.from?.id ?? ''), senderName: m.from?.first_name,
|
|
221
253
|
text, isGroup, mentioned,
|
|
222
254
|
...(quoted ? { quoted } : {}),
|
|
255
|
+
...(reply ? { reply } : {}),
|
|
256
|
+
...(botMentions.length ? { botMentions } : {}),
|
|
257
|
+
...(m.date ? { at: m.date * 1000 } : {}),
|
|
223
258
|
};
|
|
224
259
|
const inbox = this.opts.inboxFor(head);
|
|
225
260
|
const file = inbox ? m.document ?? m.photo?.at(-1) ?? m.voice ?? m.audio ?? m.video : undefined;
|
|
@@ -275,14 +310,114 @@ export class TelegramAdapter {
|
|
|
275
310
|
}
|
|
276
311
|
}).catch(failed);
|
|
277
312
|
}
|
|
313
|
+
/**
|
|
314
|
+
* Yes or No pressed under a permission request. A press counts only on a message this adapter put
|
|
315
|
+
* buttons under, and only with the data of one of those two buttons: the request is the one that
|
|
316
|
+
* message was sent for, never one the data names (the data is the client's word; a changed client can
|
|
317
|
+
* send any). The sender is the person who pressed, and whether they may answer is the orchestrator's
|
|
318
|
+
* to say, by the rules of a typed "yes <id>". The callback is always answered, or the person's app
|
|
319
|
+
* shows a spinner on the button.
|
|
320
|
+
*/
|
|
321
|
+
onPress(ctx) {
|
|
322
|
+
const q = ctx.callbackQuery, m = q.message;
|
|
323
|
+
const say = (text) => void ctx.answerCallbackQuery(text ? { text: text.slice(0, 200) } : undefined).catch((e) => this.log(`telegram: press not answered: ${this.redact(String(e.message ?? e))}`));
|
|
324
|
+
const hit = PRESS.exec(q.data ?? '');
|
|
325
|
+
if (!hit || !m || !this.opts.onPress)
|
|
326
|
+
return say();
|
|
327
|
+
const chat = String(m.chat.id), k = `${chat}/${m.message_id}`, id = this.asked.get(k);
|
|
328
|
+
if (STAND_IN_IDS.includes(q.from.id)) {
|
|
329
|
+
this.log(`telegram: drop press chat=${chat} reason=sent-as-channel-or-anonymous-admin`);
|
|
330
|
+
return say();
|
|
331
|
+
}
|
|
332
|
+
// A request line is on its way out in this chat right now: its message id is not known yet, so
|
|
333
|
+
// this may be a press on it. Nothing is answered and nothing removed.
|
|
334
|
+
if (id === undefined && this.asking.get(chat))
|
|
335
|
+
return say();
|
|
336
|
+
if (id !== undefined && hit[2].toLowerCase() !== shortId(id).toLowerCase()) {
|
|
337
|
+
this.log(`telegram: drop press chat=${chat} reason=not-this-message's-button`);
|
|
338
|
+
return say();
|
|
339
|
+
}
|
|
340
|
+
const thread = 'is_topic_message' in m && m.is_topic_message && m.message_thread_id !== undefined ? String(m.message_thread_id) : undefined;
|
|
341
|
+
let r;
|
|
342
|
+
// Everything but a private chat has its owners named in the table: a channel too, where a "group"
|
|
343
|
+
// read of the chat's kind would make every subscriber the owner. With no id (buttons this adapter
|
|
344
|
+
// does not know: a request from before a restart) the orchestrator still says whether the chat is
|
|
345
|
+
// routed and hears this person: a stranger's presses in any other chat get the bare answer and
|
|
346
|
+
// no call to the Bot API beyond it.
|
|
347
|
+
try {
|
|
348
|
+
r = this.opts.onPress({ platform: 'telegram', chat, thread, sender: String(q.from.id), isGroup: m.chat.type !== 'private' }, id, hit[1].toLowerCase() === 'y');
|
|
349
|
+
}
|
|
350
|
+
catch (e) {
|
|
351
|
+
this.log(`telegram: handler error ${e instanceof Error ? e.message : String(e)}`);
|
|
352
|
+
return say();
|
|
353
|
+
}
|
|
354
|
+
say(r.text);
|
|
355
|
+
// An answer taken here already took the buttons away (askDone). What is left: a request that was
|
|
356
|
+
// over before the press, whose buttons were never removed, and buttons from before a restart.
|
|
357
|
+
if (r.over && (id === undefined || this.asked.delete(k)))
|
|
358
|
+
this.clearButtons(chat, m.message_id);
|
|
359
|
+
}
|
|
360
|
+
askDone(chat, id) {
|
|
361
|
+
for (const [k, asked] of this.asked) {
|
|
362
|
+
if (asked !== id || !k.startsWith(`${chat}/`))
|
|
363
|
+
continue;
|
|
364
|
+
this.asked.delete(k);
|
|
365
|
+
this.clearButtons(chat, Number(k.slice(chat.length + 1)));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** The text stays; a failure is logged only (the message was deleted, the bot was removed). */
|
|
369
|
+
clearButtons(chat, message) {
|
|
370
|
+
void this.bot.api.editMessageReplyMarkup(chat, message, { reply_markup: { inline_keyboard: [] } })
|
|
371
|
+
.catch((e) => this.log(`telegram: buttons not removed chat=${chat}: ${this.redact(String(e.message ?? e))}`));
|
|
372
|
+
}
|
|
373
|
+
/** May a request in this chat carry buttons? Not in a channel: its subscribers are no members the
|
|
374
|
+
* table knows, and a request there is answered by id, from a chat with owners. A positive id is a
|
|
375
|
+
* person; any other chat is asked of Telegram once. Unknown (the call failed): no buttons. */
|
|
376
|
+
async buttonsIn(chat) {
|
|
377
|
+
if (!chat.startsWith('-'))
|
|
378
|
+
return true;
|
|
379
|
+
let kind = this.kinds.get(chat);
|
|
380
|
+
if (kind === undefined) {
|
|
381
|
+
try {
|
|
382
|
+
kind = (await this.bot.api.getChat(chat)).type;
|
|
383
|
+
}
|
|
384
|
+
catch (e) {
|
|
385
|
+
this.log(`telegram: chat kind not read, request sent without buttons chat=${chat}: ${this.redact(String(e.message ?? e))}`);
|
|
386
|
+
}
|
|
387
|
+
if (kind)
|
|
388
|
+
this.kinds.set(chat, kind);
|
|
389
|
+
}
|
|
390
|
+
return kind === 'group' || kind === 'supergroup';
|
|
391
|
+
}
|
|
278
392
|
/** Every message received so far has been handed on (tests, and a clean stop). */
|
|
279
393
|
drained() { return this.chains.idle(); }
|
|
280
394
|
async chatName(chat) {
|
|
281
395
|
const c = await this.bot.api.getChat(chat);
|
|
282
396
|
return ('title' in c && c.title) || ('first_name' in c && c.first_name) || undefined;
|
|
283
397
|
}
|
|
284
|
-
|
|
285
|
-
|
|
398
|
+
/** `o.ask`: the text is a permission request's line; Yes and No go under it, each carrying the answer
|
|
399
|
+
* and the request's short id. The line itself still says how to answer by typing. Returns the
|
|
400
|
+
* message's id and the time Telegram dates it. */
|
|
401
|
+
async send(chat, text, thread, o) {
|
|
402
|
+
const topic = thread ? { message_thread_id: Number(thread) } : undefined;
|
|
403
|
+
const id = o?.ask !== undefined && this.opts.onPress && PRESS.test(`ask:y:${shortId(o.ask)}`) && await this.buttonsIn(chat) ? shortId(o.ask).toLowerCase() : undefined;
|
|
404
|
+
if (id === undefined)
|
|
405
|
+
return stamp(await this.bot.api.sendMessage(chat, text, topic));
|
|
406
|
+
this.asking.set(chat, (this.asking.get(chat) ?? 0) + 1);
|
|
407
|
+
try {
|
|
408
|
+
const sent = await this.bot.api.sendMessage(chat, text, { ...topic, reply_markup: { inline_keyboard: [[{ text: 'Yes', callback_data: `ask:y:${id}` }, { text: 'No', callback_data: `ask:n:${id}` }]] } });
|
|
409
|
+
this.asked.set(`${chat}/${sent.message_id}`, o.ask);
|
|
410
|
+
if (this.asked.size > ASKED_MAX)
|
|
411
|
+
this.asked.delete(this.asked.keys().next().value);
|
|
412
|
+
return stamp(sent);
|
|
413
|
+
}
|
|
414
|
+
finally {
|
|
415
|
+
const n = (this.asking.get(chat) ?? 1) - 1;
|
|
416
|
+
if (n > 0)
|
|
417
|
+
this.asking.set(chat, n);
|
|
418
|
+
else
|
|
419
|
+
this.asking.delete(chat);
|
|
420
|
+
}
|
|
286
421
|
}
|
|
287
422
|
/**
|
|
288
423
|
* Attach a file. The Bot API is picky: sendVoice takes ogg/opus only, sendAudio mp3/m4a only,
|
|
@@ -364,10 +364,9 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
364
364
|
const m = withMentions(text, meta?.participants, { lidFor: (n) => this.lids.lidFor(n) });
|
|
365
365
|
if (m.capped)
|
|
366
366
|
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)}…`);
|
|
367
|
-
|
|
368
|
-
return;
|
|
367
|
+
return this.post(chat, m.mentions.length ? { text: m.text, mentions: m.mentions } : { text: m.text });
|
|
369
368
|
}
|
|
370
|
-
|
|
369
|
+
return this.post(chat, { text });
|
|
371
370
|
}
|
|
372
371
|
/** A group's metadata, from the cache or the server (which then fills the cache). */
|
|
373
372
|
async groupMeta(chat) {
|
|
@@ -378,9 +377,13 @@ export class WhatsAppAdapter extends EventEmitter {
|
|
|
378
377
|
this.groups.set(chat, meta);
|
|
379
378
|
return meta;
|
|
380
379
|
}
|
|
381
|
-
/** Every outgoing message goes through here, so a retry receipt can find it later.
|
|
380
|
+
/** Every outgoing message goes through here, so a retry receipt can find it later. Gives back the
|
|
381
|
+
* message's id, which a reply to it names (contextInfo.stanzaId). No time: the one Baileys puts on a
|
|
382
|
+
* sent message is this machine's own. */
|
|
382
383
|
async post(chat, content) {
|
|
383
|
-
|
|
384
|
+
const sent = await this.sock.sendMessage(chat, content);
|
|
385
|
+
this.sent.remember(sent);
|
|
386
|
+
return sent?.key?.id ? { id: sent.key.id } : {};
|
|
384
387
|
}
|
|
385
388
|
/** A group's subject, for naming its profile. A DM has no name here. */
|
|
386
389
|
async chatName(chat) {
|
|
@@ -103,11 +103,17 @@ export function parseMessage(m, us) {
|
|
|
103
103
|
// Strings only, as for the message itself: a field of another type is not text.
|
|
104
104
|
const quoted = q ? [q.conversation, q.extendedTextMessage?.text, q.imageMessage?.caption, q.videoMessage?.caption, q.documentMessage?.caption]
|
|
105
105
|
.find((v) => typeof v === 'string' && v !== '') : undefined;
|
|
106
|
-
|
|
106
|
+
const sent = byteLength(m.messageTimestamp);
|
|
107
|
+
// A reply names the message it answers by id and by author. The id alone is the sender's to choose
|
|
108
|
+
// (a client can send a message under any id), so "ours" is read from the author WhatsApp names.
|
|
109
|
+
const reply = ctx?.stanzaId || ctx?.quotedMessage ? { ...(typeof ctx.stanzaId === 'string' && ctx.stanzaId ? { id: ctx.stanzaId } : {}), ours: !!quotedBy && ours.has(quotedBy) } : undefined;
|
|
110
|
+
// A mention is written in the text as @ and the number of the jid it names.
|
|
111
|
+
const botMentions = mentionedJids.map((j) => bareId(String(j))).filter((n) => ours.has(n)).map((n) => `@${n}`);
|
|
112
|
+
return { chat, sender, senderName: m.pushName ?? undefined, text, ...(quoted ? { quoted } : {}), ...(reply ? { reply } : {}), ...(botMentions.length ? { botMentions } : {}), ...(sent ? { at: sent * 1000 } : {}), isGroup, mentioned, media };
|
|
107
113
|
}
|
|
108
114
|
/** ParsedMessage -> Inbound, with the sender written the way routing.yaml expects (bare phone or lid). */
|
|
109
115
|
export function toInbound(p, senderId, mediaPaths) {
|
|
110
|
-
return { platform: 'whatsapp', chat: p.chat, sender: senderId, senderName: p.senderName, text: p.text, ...(p.quoted ? { quoted: p.quoted } : {}), isGroup: p.isGroup, mentioned: p.mentioned, media: mediaPaths };
|
|
116
|
+
return { platform: 'whatsapp', chat: p.chat, sender: senderId, senderName: p.senderName, text: p.text, ...(p.quoted ? { quoted: p.quoted } : {}), ...(p.reply ? { reply: p.reply } : {}), ...(p.botMentions ? { botMentions: p.botMentions } : {}), ...(p.at ? { at: p.at } : {}), isGroup: p.isGroup, mentioned: p.mentioned, media: mediaPaths };
|
|
111
117
|
}
|
|
112
118
|
/** At most this many members are tagged in one message: a tag notifies even a member who muted the group. */
|
|
113
119
|
export const MAX_MENTIONS = 5;
|
package/dist/brain/argv.js
CHANGED
|
@@ -43,7 +43,7 @@ export function claudeArgv(p, s, bin = 'claude', system) {
|
|
|
43
43
|
* print mode the flag is accepted and ignored), so print mode never passes it; tui mode always does. */
|
|
44
44
|
export function remoteControlName(p, s) {
|
|
45
45
|
const dir = p.cwd.replace(/\/+$/, '').split('/').pop() || 'angelia';
|
|
46
|
-
return
|
|
46
|
+
return `${p.session_prefix ?? 'angelia'}-${dir}-${s.id.slice(0, 8)}`.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').slice(0, 60);
|
|
47
47
|
}
|
|
48
48
|
/** The same CLI as `claudeArgv`, hosted in a terminal instead of print mode. An interactive
|
|
49
49
|
* session is the only kind Remote Control registers, so this is what puts a chat in the Claude
|