@cello-protocol/cli 0.0.316 → 0.0.317
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 +83 -67
- package/dist/cli.js +2 -1
- package/dist/daemon/engine.d.ts +6 -1
- package/dist/daemon/engine.js +91 -5
- package/dist/daemon/governance.js +1 -1
- package/dist/daemon/main.js +60 -4
- package/dist/daemon/notifiers.d.ts +30 -0
- package/dist/daemon/notifiers.js +415 -0
- package/dist/daemon/operator-inbox.d.ts +15 -0
- package/dist/daemon/operator-inbox.js +39 -0
- package/dist/daemon/reach.js +4 -0
- package/dist/daemon/reminders.d.ts +26 -0
- package/dist/daemon/reminders.js +204 -0
- package/dist/daemon/telegram.d.ts +36 -0
- package/dist/daemon/telegram.js +72 -0
- package/dist/ipc/operations.js +92 -1
- package/dist/mcp.js +7 -1
- package/hermes/plugin/__init__.py +82 -9
- package/hermes/plugin/__pycache__/__init__.cpython-314.pyc +0 -0
- package/package.json +1 -1
- package/plugins/cello/skills/cello/SKILL.md +2 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Store } from "./store.ts";
|
|
2
|
+
import { type TelegramEndpoint } from "./telegram.ts";
|
|
3
|
+
export declare const NOTIFIER_TYPES: readonly ["telegram"];
|
|
4
|
+
export declare const NOTIFY_KINDS: readonly ["message", "request"];
|
|
5
|
+
type Kind = (typeof NOTIFY_KINDS)[number];
|
|
6
|
+
export declare function cannedLine(agentName: string, kind: Kind): string;
|
|
7
|
+
export declare function withText(agentName: string, kind: Kind, text: string): string;
|
|
8
|
+
export interface NotifierHost {
|
|
9
|
+
agentName(agentHex: string): string;
|
|
10
|
+
screenOutbound(agentHex: string, text: string, params: Record<string, unknown>, retry: string): Promise<{
|
|
11
|
+
text: string;
|
|
12
|
+
report: Record<string, unknown>;
|
|
13
|
+
}>;
|
|
14
|
+
reachable(agentHex: string): boolean;
|
|
15
|
+
tell(agentHex: string, text: string): void;
|
|
16
|
+
fromOperator(agentHex: string, sessionId: Uint8Array | null, text: string, via: string, sourceId: string): "stored" | "already" | "no_agent";
|
|
17
|
+
}
|
|
18
|
+
export declare class Notifiers {
|
|
19
|
+
#private;
|
|
20
|
+
constructor(store: Store, host: NotifierHost, telegram?: TelegramEndpoint);
|
|
21
|
+
start(): void;
|
|
22
|
+
stop(): void;
|
|
23
|
+
forget(agentHex: string): void;
|
|
24
|
+
add(agentHex: string, params: Record<string, unknown>): Promise<unknown>;
|
|
25
|
+
list(agentHex: string): unknown;
|
|
26
|
+
remove(agentHex: string, name: string): unknown;
|
|
27
|
+
test(agentHex: string, name: string | undefined): Promise<unknown>;
|
|
28
|
+
notify(agentHex: string, params: Record<string, unknown>): Promise<unknown>;
|
|
29
|
+
}
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
// How an agent reaches its human operator when they aren't at the session: a notifier is one route to the person, such as a
|
|
2
|
+
// Telegram chat. The agent decides when to use one and what leaves the machine: a fixed line, or its own words.
|
|
3
|
+
// Anyone can set one up, agents included, because setting up a bot is hard enough already.
|
|
4
|
+
import { LocalError } from "./errors.js";
|
|
5
|
+
import { logEvent } from "./log.js";
|
|
6
|
+
import { TELEGRAM, TelegramError, botIdOf, botUsername, newestUpdate, sendText, updatesFrom } from "./telegram.js";
|
|
7
|
+
const SCHEMA = `
|
|
8
|
+
CREATE TABLE IF NOT EXISTS notifiers (
|
|
9
|
+
agent_id BLOB NOT NULL REFERENCES agents(agent_id),
|
|
10
|
+
name TEXT NOT NULL,
|
|
11
|
+
type TEXT NOT NULL CHECK (type IN ('telegram')),
|
|
12
|
+
-- JSON, and it holds the bot token, so no command, log or notice ever shows it whole.
|
|
13
|
+
config TEXT NOT NULL,
|
|
14
|
+
added_at INTEGER NOT NULL,
|
|
15
|
+
PRIMARY KEY (agent_id, name)
|
|
16
|
+
);
|
|
17
|
+
-- One row per notification that reached a notifier, so a reply can be traced to the agent and session that asked.
|
|
18
|
+
CREATE TABLE IF NOT EXISTS notifications (
|
|
19
|
+
id INTEGER PRIMARY KEY,
|
|
20
|
+
agent_id BLOB NOT NULL REFERENCES agents(agent_id),
|
|
21
|
+
notifier TEXT NOT NULL,
|
|
22
|
+
session_id BLOB,
|
|
23
|
+
kind TEXT NOT NULL,
|
|
24
|
+
-- The notifier's own id for it. For Telegram: the bot's id, the chat's number and the message's, with colons. All three,
|
|
25
|
+
-- because each bot numbers its messages from one, so two bots in one person's chat share numbers.
|
|
26
|
+
remote_id TEXT NOT NULL,
|
|
27
|
+
sent_at INTEGER NOT NULL
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS notifications_remote ON notifications (remote_id);
|
|
30
|
+
`;
|
|
31
|
+
export const NOTIFIER_TYPES = ["telegram"];
|
|
32
|
+
export const NOTIFY_KINDS = ["message", "request"];
|
|
33
|
+
// Telegram's own limit for one message.
|
|
34
|
+
const TELEGRAM_MAX_CHARS = 4096;
|
|
35
|
+
const NAME_RULE = /^[A-Za-z0-9_-]{1,32}$/;
|
|
36
|
+
// The fixed lines. They say that something is waiting and nothing about what.
|
|
37
|
+
export function cannedLine(agentName, kind) {
|
|
38
|
+
return `Your agent ${agentName} has a ${kind} waiting for you.`;
|
|
39
|
+
}
|
|
40
|
+
export function withText(agentName, kind, text) {
|
|
41
|
+
return `Your agent ${agentName} has a ${kind} for you:\n\n${text}`;
|
|
42
|
+
}
|
|
43
|
+
const idOf = (agentHex) => new Uint8Array(Buffer.from(agentHex, "hex"));
|
|
44
|
+
const offsetKey = (botId) => `notifier.telegram.next_update.${botId}`;
|
|
45
|
+
const FIRST_RETRY_MS = 1_000;
|
|
46
|
+
const LONGEST_RETRY_MS = 60_000;
|
|
47
|
+
// Ends early when the reader is stopped, so stopping the daemon never waits out a retry.
|
|
48
|
+
function pause(ms, stop) {
|
|
49
|
+
return new Promise((resolve) => {
|
|
50
|
+
const timer = setTimeout(done, ms);
|
|
51
|
+
function done() {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
stop.removeEventListener("abort", done);
|
|
54
|
+
resolve();
|
|
55
|
+
}
|
|
56
|
+
stop.addEventListener("abort", done);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export class Notifiers {
|
|
60
|
+
#store;
|
|
61
|
+
#host;
|
|
62
|
+
#telegram;
|
|
63
|
+
// One reader per bot, however many notifiers use it: Telegram allows a bot only one.
|
|
64
|
+
#readers = new Map();
|
|
65
|
+
constructor(store, host, telegram = TELEGRAM) {
|
|
66
|
+
this.#telegram = telegram;
|
|
67
|
+
this.#store = store;
|
|
68
|
+
this.#host = host;
|
|
69
|
+
store.exec(SCHEMA);
|
|
70
|
+
}
|
|
71
|
+
// Starts listening for the operator's replies on every bot a notifier uses.
|
|
72
|
+
start() {
|
|
73
|
+
for (const holder of this.#holders())
|
|
74
|
+
this.#listen(holder.botId);
|
|
75
|
+
}
|
|
76
|
+
stop() {
|
|
77
|
+
for (const reader of this.#readers.values())
|
|
78
|
+
reader.abort();
|
|
79
|
+
this.#readers.clear();
|
|
80
|
+
}
|
|
81
|
+
// An agent that's removed takes its notifiers with it, tokens included, and a bot nobody else uses stops being read.
|
|
82
|
+
forget(agentHex) {
|
|
83
|
+
this.#store.prepare("DELETE FROM notifications WHERE agent_id = ?").run(idOf(agentHex));
|
|
84
|
+
this.#store.prepare("DELETE FROM notifiers WHERE agent_id = ?").run(idOf(agentHex));
|
|
85
|
+
const inUse = new Set(this.#holders().map((h) => h.botId));
|
|
86
|
+
for (const [botId, reader] of this.#readers) {
|
|
87
|
+
if (inUse.has(botId))
|
|
88
|
+
continue;
|
|
89
|
+
reader.abort();
|
|
90
|
+
this.#readers.delete(botId);
|
|
91
|
+
}
|
|
92
|
+
logEvent("notifier.agent_forgotten", { agent: agentHex });
|
|
93
|
+
}
|
|
94
|
+
// Every agent's notifiers, oldest first.
|
|
95
|
+
#holders() {
|
|
96
|
+
const rows = this.#store.prepare("SELECT agent_id, name, config FROM notifiers ORDER BY added_at, name").all();
|
|
97
|
+
return rows.map((row) => {
|
|
98
|
+
const config = JSON.parse(row.config);
|
|
99
|
+
return { agentHex: Buffer.from(row.agent_id).toString("hex"), name: row.name, botId: botIdOf(config.bot_token), token: config.bot_token, chat: config.chat_number };
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
#listen(botId) {
|
|
103
|
+
if (this.#readers.has(botId))
|
|
104
|
+
return;
|
|
105
|
+
const reader = new AbortController();
|
|
106
|
+
this.#readers.set(botId, reader);
|
|
107
|
+
// Nothing in the reader may take the daemon down with it. If it dies it says so, and the next add or restart starts it again.
|
|
108
|
+
this.#read(botId, reader).catch((err) => {
|
|
109
|
+
if (this.#readers.get(botId) === reader)
|
|
110
|
+
this.#readers.delete(botId);
|
|
111
|
+
logEvent("notifier.reading_crashed", { bot: botId, message: err instanceof Error ? err.message : String(err) });
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
// Reads what people send the bot, for as long as a notifier uses it. The place reached is kept in the database and moves
|
|
115
|
+
// on only once a reply is stored, so a restart or a failed write repeats nothing and loses nothing.
|
|
116
|
+
async #read(botId, reader) {
|
|
117
|
+
const stop = reader.signal;
|
|
118
|
+
let retry = FIRST_RETRY_MS;
|
|
119
|
+
while (!stop.aborted) {
|
|
120
|
+
// The newest notifier's token, since an older one may have been replaced at BotFather.
|
|
121
|
+
const token = this.#holders().filter((h) => h.botId === botId).at(-1)?.token;
|
|
122
|
+
if (token === undefined)
|
|
123
|
+
break;
|
|
124
|
+
try {
|
|
125
|
+
const updates = await updatesFrom(this.#telegram, token, Number(this.#store.getConfig(offsetKey(botId)) ?? 0), stop);
|
|
126
|
+
for (const update of updates) {
|
|
127
|
+
// A reader stopped part-way must not write its place over one a new notifier has just set.
|
|
128
|
+
if (stop.aborted)
|
|
129
|
+
break;
|
|
130
|
+
await this.#onUpdate(botId, token, update);
|
|
131
|
+
if (stop.aborted)
|
|
132
|
+
break;
|
|
133
|
+
this.#store.setConfig(offsetKey(botId), String(update.update_id + 1));
|
|
134
|
+
}
|
|
135
|
+
retry = FIRST_RETRY_MS;
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
if (stop.aborted)
|
|
139
|
+
break;
|
|
140
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
141
|
+
const code = err instanceof TelegramError ? err.code : undefined;
|
|
142
|
+
if (code === 401 || code === 404 || code === 409) {
|
|
143
|
+
logEvent("notifier.reading_stopped", { bot: botId, code, message });
|
|
144
|
+
for (const holder of this.#holders().filter((h) => h.botId === botId)) {
|
|
145
|
+
this.#host.tell(holder.agentHex, code === 409
|
|
146
|
+
? `Another program is reading the Telegram bot behind your notifier ${holder.name}, and a bot allows only one reader, so your operator's replies can't arrive here. Notifications still go out. Tell your operator to give this agent a bot nothing else uses: cello notifier-remove ${holder.name}, then notifier-add.`
|
|
147
|
+
: `Telegram no longer accepts the token of the bot behind your notifier ${holder.name} (${message}), so you can't reach your operator through it and their replies won't arrive. Set it up again with a current token: cello notifier-remove ${holder.name}, then notifier-add.`);
|
|
148
|
+
}
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
logEvent("notifier.reading_failed", { bot: botId, message, retry_ms: retry });
|
|
152
|
+
await pause(retry, stop);
|
|
153
|
+
retry = Math.min(retry * 2, LONGEST_RETRY_MS);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (this.#readers.get(botId) === reader)
|
|
157
|
+
this.#readers.delete(botId);
|
|
158
|
+
}
|
|
159
|
+
// Says something back in the operator's chat. It's a courtesy: failing to say it never holds up or undoes the reply itself.
|
|
160
|
+
async #answer(holder, text) {
|
|
161
|
+
try {
|
|
162
|
+
await sendText(this.#telegram, holder.token, holder.chat, text);
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
logEvent("notifier.answer_failed", { bot: holder.botId, message: err instanceof Error ? err.message : String(err) });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// One thing sent to the bot. Only the exact bot and chat a notifier holds may speak as the operator, and only a private chat.
|
|
169
|
+
async #onUpdate(botId, token, update) {
|
|
170
|
+
const message = update.message;
|
|
171
|
+
if (message?.chat?.id === undefined)
|
|
172
|
+
return;
|
|
173
|
+
const chat = String(message.chat.id);
|
|
174
|
+
const holders = this.#holders().filter((h) => h.botId === botId && h.chat === chat);
|
|
175
|
+
const first = holders[0];
|
|
176
|
+
if (!first) {
|
|
177
|
+
logEvent("notifier.reply_ignored", { bot: botId, reason: "not a chat any notifier holds" });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const here = { ...first, token };
|
|
181
|
+
if (message.chat.type !== "private") {
|
|
182
|
+
await this.#answer(here, "Replies are only taken from a private chat with this bot, so this wasn't passed to any agent.");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const text = typeof message.text === "string" ? message.text.trim() : "";
|
|
186
|
+
// Telegram's own greeting when a chat with a bot is opened. It isn't something the person said to an agent.
|
|
187
|
+
if (/^\/start(@\S+)?(\s|$)/.test(text))
|
|
188
|
+
return;
|
|
189
|
+
if (text.length === 0) {
|
|
190
|
+
await this.#answer(here, "Only text reaches your agent, so this wasn't passed on. Type your answer.");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const holds = (agentId, notifier) => holders.find((h) => h.name === notifier && h.agentHex === Buffer.from(agentId).toString("hex"));
|
|
194
|
+
let target;
|
|
195
|
+
// A reply to one of an agent's notifications goes to that agent, about that session.
|
|
196
|
+
const repliedTo = message.reply_to_message?.message_id;
|
|
197
|
+
if (repliedTo !== undefined) {
|
|
198
|
+
const sent = this.#store.prepare("SELECT agent_id, notifier, session_id FROM notifications WHERE remote_id = ? ORDER BY id DESC").get(`${botId}:${chat}:${repliedTo}`);
|
|
199
|
+
const holder = sent && holds(sent.agent_id, sent.notifier);
|
|
200
|
+
if (sent && !holder) {
|
|
201
|
+
// The person named an agent by answering its message. Handing it to another one would be a guess they didn't make.
|
|
202
|
+
await this.#answer(here, "The agent that sent that message no longer uses this chat, so your reply wasn't passed on.");
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (sent && holder)
|
|
206
|
+
target = { holder, sessionId: sent.session_id };
|
|
207
|
+
}
|
|
208
|
+
// A plain message goes to whichever agent wrote to this chat last, because that's who the person is answering. It
|
|
209
|
+
// names no session: only answering a message says which conversation it's about.
|
|
210
|
+
if (!target) {
|
|
211
|
+
const sent = this.#store.prepare("SELECT agent_id, notifier, session_id FROM notifications WHERE remote_id LIKE ? ORDER BY id DESC LIMIT 50").all(`${botId}:${chat}:%`).find((row) => holds(row.agent_id, row.notifier));
|
|
212
|
+
if (sent)
|
|
213
|
+
target = { holder: holds(sent.agent_id, sent.notifier), sessionId: null };
|
|
214
|
+
}
|
|
215
|
+
if (!target) {
|
|
216
|
+
if (new Set(holders.map((h) => h.agentHex)).size > 1) {
|
|
217
|
+
await this.#answer(here, "More than one agent uses this chat, and none has written to you yet, so it isn't clear who this is for. It wasn't passed on. Reply to one of an agent's messages once it has written.");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
target = { holder: first, sessionId: null };
|
|
221
|
+
}
|
|
222
|
+
const agentHex = target.holder.agentHex;
|
|
223
|
+
const outcome = this.#host.fromOperator(agentHex, target.sessionId, text, target.holder.name, `telegram:${botId}:${update.update_id}`);
|
|
224
|
+
if (outcome === "already")
|
|
225
|
+
return;
|
|
226
|
+
if (outcome === "no_agent") {
|
|
227
|
+
// Never silently: the person believes they've given an instruction.
|
|
228
|
+
await this.#answer(here, "The agent this was for is no longer on this machine, so it wasn't passed on.");
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const name = this.#host.agentName(agentHex);
|
|
232
|
+
await this.#answer(here, this.#host.reachable(agentHex) ? `Passed to ${name}.` : `Passed to ${name}. No session is holding ${name} right now, so it will see this when one next reads.`);
|
|
233
|
+
}
|
|
234
|
+
#rows(agentHex) {
|
|
235
|
+
return this.#store.prepare("SELECT name, type, config, added_at FROM notifiers WHERE agent_id = ? ORDER BY added_at, name").all(idOf(agentHex));
|
|
236
|
+
}
|
|
237
|
+
#row(agentHex, name) {
|
|
238
|
+
const row = this.#rows(agentHex).find((r) => r.name === name);
|
|
239
|
+
if (!row)
|
|
240
|
+
throw new LocalError("no_such_notifier", `${this.#host.agentName(agentHex)} has no notifier named ${name}. notifier-list shows them.`);
|
|
241
|
+
return row;
|
|
242
|
+
}
|
|
243
|
+
// One send through one notifier. Returns the notifier's own id for what it sent.
|
|
244
|
+
async #deliver(row, text) {
|
|
245
|
+
const config = JSON.parse(row.config);
|
|
246
|
+
const sent = await sendText(this.#telegram, config.bot_token, config.chat_id, text);
|
|
247
|
+
return `${botIdOf(config.bot_token)}:${sent.chatId}:${sent.messageId}`;
|
|
248
|
+
}
|
|
249
|
+
// Proves the token and the chat with Telegram before anything is stored, so a mistake shows here and not at the first real notify.
|
|
250
|
+
async add(agentHex, params) {
|
|
251
|
+
const type = params["type"];
|
|
252
|
+
if (type !== "telegram")
|
|
253
|
+
throw new LocalError("bad_argument", `type must be one of: ${NOTIFIER_TYPES.join(", ")}`);
|
|
254
|
+
const name = typeof params["name"] === "string" ? params["name"] : type;
|
|
255
|
+
if (!NAME_RULE.test(name))
|
|
256
|
+
throw new LocalError("bad_argument", "name must be 1 to 32 letters, digits, underscores or dashes");
|
|
257
|
+
// A pasted token often carries a stray space or newline, which Telegram answers with a bare "Not Found".
|
|
258
|
+
const token = typeof params["bot_token"] === "string" ? params["bot_token"].trim() : "";
|
|
259
|
+
if (token.length === 0)
|
|
260
|
+
throw new LocalError("bad_argument", "A Telegram notifier needs bot_token: the token BotFather gave for the bot.");
|
|
261
|
+
const agentName = this.#host.agentName(agentHex);
|
|
262
|
+
const existing = this.#rows(agentHex);
|
|
263
|
+
if (existing.some((r) => r.name === name))
|
|
264
|
+
throw new LocalError("notifier_exists", `${agentName} already has a notifier named ${name}. Remove it first with notifier-remove, or give this one another name.`);
|
|
265
|
+
const apiUrl = this.#telegram;
|
|
266
|
+
const botId = botIdOf(token);
|
|
267
|
+
// A bot this daemon already reads can't be asked for its newest message: Telegram allows one reader, and asking would
|
|
268
|
+
// throw away replies the reader hasn't taken yet.
|
|
269
|
+
// The database says whether it's in use, not the running readers, so this holds from the daemon's first moment.
|
|
270
|
+
const sameBot = this.#holders().filter((h) => h.botId === botId);
|
|
271
|
+
const reading = sameBot.length > 0;
|
|
272
|
+
let bot;
|
|
273
|
+
let chatId = typeof params["chat_id"] === "string" && params["chat_id"].trim().length > 0 ? params["chat_id"].trim() : undefined;
|
|
274
|
+
let chatWho;
|
|
275
|
+
let chatNumber;
|
|
276
|
+
let newest;
|
|
277
|
+
try {
|
|
278
|
+
bot = await botUsername(apiUrl, token);
|
|
279
|
+
if (reading && chatId === undefined) {
|
|
280
|
+
// One bot can serve every agent a person has. The next agent uses the chat the first one found, with nothing more to give.
|
|
281
|
+
const chats = [...new Set(sameBot.map((h) => h.chat))];
|
|
282
|
+
if (chats.length !== 1)
|
|
283
|
+
throw new LocalError("chat_id_needed", `Nothing was saved. This machine uses @${bot} with more than one chat, so it isn't clear which one this agent should write to. Give it with chat_id: notifier-list on an agent that has it shows them.`);
|
|
284
|
+
chatId = chats[0];
|
|
285
|
+
chatWho = "the chat this bot already writes to";
|
|
286
|
+
}
|
|
287
|
+
if (!reading)
|
|
288
|
+
newest = await newestUpdate(apiUrl, token);
|
|
289
|
+
if (chatId === undefined) {
|
|
290
|
+
// No chat id given: use the chat that wrote to the bot last, and say whose it is so a wrong one shows.
|
|
291
|
+
// Only a person's own chat counts, so a group the bot sits in is never picked by accident.
|
|
292
|
+
const chat = newest?.message?.chat;
|
|
293
|
+
if (chat?.id === undefined)
|
|
294
|
+
throw new LocalError("no_chat_yet", `Nothing was saved. Nobody has written to @${bot} yet, so there's no chat to send to. Open Telegram, send @${bot} any message, and run this again. Or give the chat id with chat_id.`);
|
|
295
|
+
if (chat.type !== "private")
|
|
296
|
+
throw new LocalError("no_chat_yet", `Nothing was saved. The last message to @${bot} came from the group "${chat.title ?? String(chat.id)}", and a group is only used when you name it. Send @${bot} a message from your own chat and run this again, or give the group's id with chat_id.`);
|
|
297
|
+
chatId = String(chat.id);
|
|
298
|
+
chatWho = chat.username ? `@${chat.username}` : chat.first_name ?? chatId;
|
|
299
|
+
}
|
|
300
|
+
chatNumber = (await sendText(apiUrl, token, chatId, `CELLO is connected. Your agent ${agentName} can now reach you here.`)).chatId;
|
|
301
|
+
}
|
|
302
|
+
catch (err) {
|
|
303
|
+
if (!(err instanceof TelegramError))
|
|
304
|
+
throw err;
|
|
305
|
+
throw new LocalError("notifier_check_failed", `Nothing was saved, because the check with Telegram failed. ${err.message}`);
|
|
306
|
+
}
|
|
307
|
+
const config = { bot_token: token, chat_id: chatId, chat_number: chatNumber, bot };
|
|
308
|
+
this.#store.prepare("INSERT INTO notifiers (agent_id, name, type, config, added_at) VALUES (?, ?, ?, ?, ?)").run(idOf(agentHex), name, type, JSON.stringify(config), Date.now());
|
|
309
|
+
logEvent("notifier.added", { agent: agentHex, notifier: name, type });
|
|
310
|
+
// Reading starts after whatever was sent to the bot to set it up. A "hi" typed to find the chat is not an instruction.
|
|
311
|
+
if (newest)
|
|
312
|
+
this.#store.setConfig(offsetKey(botId), String(newest.update_id + 1));
|
|
313
|
+
this.#listen(botId);
|
|
314
|
+
// The routes that were already there hear about the new one, so one added by a tricked agent doesn't go unseen.
|
|
315
|
+
const told = [];
|
|
316
|
+
const untold = [];
|
|
317
|
+
for (const other of existing) {
|
|
318
|
+
try {
|
|
319
|
+
await this.#deliver(other, `A new notifier was added for your agent ${agentName}: ${name}, a Telegram chat with @${bot}. If that wasn't you, remove it with: cello notifier-remove ${name} --agent ${agentHex}`);
|
|
320
|
+
told.push(other.name);
|
|
321
|
+
}
|
|
322
|
+
catch (err) {
|
|
323
|
+
if (!(err instanceof TelegramError))
|
|
324
|
+
throw err;
|
|
325
|
+
logEvent("notifier.failed", { agent: agentHex, notifier: other.name, message: err.message });
|
|
326
|
+
untold.push({ notifier: other.name, message: err.message });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return { added: true, agent: agentName, notifier: name, type, bot: `@${bot}`, chat_id: chatId, ...(chatWho ? { chat_with: chatWho } : {}), told_existing: told, ...(untold.length > 0 ? { could_not_tell: untold } : {}) };
|
|
330
|
+
}
|
|
331
|
+
list(agentHex) {
|
|
332
|
+
return {
|
|
333
|
+
agent: this.#host.agentName(agentHex),
|
|
334
|
+
notifiers: this.#rows(agentHex).map((row) => {
|
|
335
|
+
const config = JSON.parse(row.config);
|
|
336
|
+
return { notifier: row.name, type: row.type, bot: `@${config.bot}`, chat_id: config.chat_id, added_at: new Date(row.added_at).toISOString() };
|
|
337
|
+
}),
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
remove(agentHex, name) {
|
|
341
|
+
const botId = botIdOf(JSON.parse(this.#row(agentHex, name).config).bot_token);
|
|
342
|
+
this.#store.prepare("DELETE FROM notifiers WHERE agent_id = ? AND name = ?").run(idOf(agentHex), name);
|
|
343
|
+
logEvent("notifier.removed", { agent: agentHex, notifier: name });
|
|
344
|
+
// The bot's last notifier going takes its reader with it.
|
|
345
|
+
if (!this.#holders().some((h) => h.botId === botId)) {
|
|
346
|
+
this.#readers.get(botId)?.abort();
|
|
347
|
+
this.#readers.delete(botId);
|
|
348
|
+
}
|
|
349
|
+
return { removed: true, agent: this.#host.agentName(agentHex), notifier: name };
|
|
350
|
+
}
|
|
351
|
+
#chosen(agentHex, name, command) {
|
|
352
|
+
if (name !== undefined)
|
|
353
|
+
return [this.#row(agentHex, name)];
|
|
354
|
+
const rows = this.#rows(agentHex);
|
|
355
|
+
if (rows.length === 0) {
|
|
356
|
+
throw new LocalError("no_notifier", `${this.#host.agentName(agentHex)} has no notifier, so ${command === "notify" ? "nobody was told" : "there's nothing to test"}. Set one up with: cello notifier-add telegram --bot-token <token> --chat-id <id> --agent ${agentHex}`);
|
|
357
|
+
}
|
|
358
|
+
return rows;
|
|
359
|
+
}
|
|
360
|
+
// Sends to every chosen notifier. It answers sent only if at least one accepted it, and names each that didn't.
|
|
361
|
+
async #sendAll(agentHex, rows, text, kind, sessionId, record) {
|
|
362
|
+
const reached = [];
|
|
363
|
+
const failed = [];
|
|
364
|
+
for (const row of rows) {
|
|
365
|
+
try {
|
|
366
|
+
const remoteId = await this.#deliver(row, text);
|
|
367
|
+
if (record)
|
|
368
|
+
this.#store.prepare("INSERT INTO notifications (agent_id, notifier, session_id, kind, remote_id, sent_at) VALUES (?, ?, ?, ?, ?, ?)").run(idOf(agentHex), row.name, sessionId, kind, remoteId, Date.now());
|
|
369
|
+
reached.push(row.name);
|
|
370
|
+
}
|
|
371
|
+
catch (err) {
|
|
372
|
+
if (!(err instanceof TelegramError))
|
|
373
|
+
throw err;
|
|
374
|
+
logEvent("notifier.failed", { agent: agentHex, notifier: row.name, message: err.message });
|
|
375
|
+
failed.push({ notifier: row.name, message: err.message });
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (reached.length === 0)
|
|
379
|
+
throw new LocalError("notify_failed", `Nobody was told. ${failed.map((f) => `${f.notifier}: ${f.message}`).join(" ")}`);
|
|
380
|
+
return { sent: true, agent: this.#host.agentName(agentHex), notifiers: reached, ...(failed.length > 0 ? { failed } : {}) };
|
|
381
|
+
}
|
|
382
|
+
async test(agentHex, name) {
|
|
383
|
+
const rows = this.#chosen(agentHex, name, "notifier-test");
|
|
384
|
+
return this.#sendAll(agentHex, rows, `This is a test from your agent ${this.#host.agentName(agentHex)}. Its notifier works.`, "test", null, false);
|
|
385
|
+
}
|
|
386
|
+
async notify(agentHex, params) {
|
|
387
|
+
const kind = (params["kind"] ?? "message");
|
|
388
|
+
if (!NOTIFY_KINDS.includes(kind))
|
|
389
|
+
throw new LocalError("bad_argument", `kind must be one of: ${NOTIFY_KINDS.join(", ")}`);
|
|
390
|
+
const only = params["notifier"];
|
|
391
|
+
if (only !== undefined && typeof only !== "string")
|
|
392
|
+
throw new LocalError("bad_argument", "notifier must be a notifier's name");
|
|
393
|
+
const rows = this.#chosen(agentHex, only, "notify");
|
|
394
|
+
const sessionHex = params["session_id"];
|
|
395
|
+
if (sessionHex !== undefined && (typeof sessionHex !== "string" || !/^[0-9a-f]{32}$/.test(sessionHex)))
|
|
396
|
+
throw new LocalError("bad_argument", "session_id must be 32 hex characters");
|
|
397
|
+
const agentName = this.#host.agentName(agentHex);
|
|
398
|
+
const given = params["text"];
|
|
399
|
+
if (given !== undefined && typeof given !== "string")
|
|
400
|
+
throw new LocalError("bad_argument", "text must be a string");
|
|
401
|
+
let text = cannedLine(agentName, kind);
|
|
402
|
+
// What the screen changed or let through, so the agent knows the person didn't read its exact words.
|
|
403
|
+
let report = {};
|
|
404
|
+
if (given !== undefined && given.length > 0) {
|
|
405
|
+
const screened = await this.#host.screenOutbound(agentHex, given, params, `cello notify - --kind ${kind}${only ? ` --notifier ${only}` : ""}${sessionHex ? ` --session-id ${sessionHex}` : ""} --allow-flagged --agent ${agentHex}`);
|
|
406
|
+
text = withText(agentName, kind, screened.text);
|
|
407
|
+
report = screened.report;
|
|
408
|
+
if (text.length > TELEGRAM_MAX_CHARS)
|
|
409
|
+
throw new LocalError("too_long", `Nobody was told: with its first line this is ${text.length} characters, and one Telegram message holds ${TELEGRAM_MAX_CHARS}. Shorten it, or leave the text out to send the fixed line.`);
|
|
410
|
+
}
|
|
411
|
+
const answer = await this.#sendAll(agentHex, rows, text, kind, sessionHex === undefined ? null : new Uint8Array(Buffer.from(sessionHex, "hex")), true);
|
|
412
|
+
logEvent("notifier.sent", { agent: agentHex, kind, with_text: given !== undefined && given.length > 0 });
|
|
413
|
+
return { ...answer, kind, included_text: given !== undefined && given.length > 0, ...report };
|
|
414
|
+
}
|
|
415
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Store } from "./store.ts";
|
|
2
|
+
export interface OperatorMessage {
|
|
3
|
+
id: number;
|
|
4
|
+
session_id: Uint8Array | null;
|
|
5
|
+
text: string;
|
|
6
|
+
via: string;
|
|
7
|
+
received_at: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class OperatorInbox {
|
|
10
|
+
#private;
|
|
11
|
+
constructor(store: Store);
|
|
12
|
+
add(agentId: Uint8Array, sessionId: Uint8Array | null, text: string, via: string, sourceId: string): boolean;
|
|
13
|
+
unread(agentId: Uint8Array): OperatorMessage[];
|
|
14
|
+
markRead(agentId: Uint8Array, ids: readonly number[]): void;
|
|
15
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const SCHEMA = `
|
|
2
|
+
CREATE TABLE IF NOT EXISTS operator_messages (
|
|
3
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
|
+
agent_id BLOB NOT NULL REFERENCES agents(agent_id),
|
|
5
|
+
-- The session the operator was answering about, when they answered a notification that named one.
|
|
6
|
+
session_id BLOB,
|
|
7
|
+
-- Emptied once it's read. The row stays, so the same reply fetched again after a crash is still known.
|
|
8
|
+
text TEXT NOT NULL,
|
|
9
|
+
-- The notifier's name, so the agent knows which route it came by.
|
|
10
|
+
via TEXT NOT NULL,
|
|
11
|
+
-- The notifier's own id for it.
|
|
12
|
+
source_id TEXT NOT NULL UNIQUE,
|
|
13
|
+
received_at INTEGER NOT NULL,
|
|
14
|
+
read_at INTEGER
|
|
15
|
+
);
|
|
16
|
+
`;
|
|
17
|
+
export class OperatorInbox {
|
|
18
|
+
#store;
|
|
19
|
+
constructor(store) {
|
|
20
|
+
this.#store = store;
|
|
21
|
+
store.exec(SCHEMA);
|
|
22
|
+
}
|
|
23
|
+
// False when this one was stored before, whether or not it has been read since. An instruction given once must never
|
|
24
|
+
// reach the agent twice.
|
|
25
|
+
add(agentId, sessionId, text, via, sourceId) {
|
|
26
|
+
if (this.#store.prepare("SELECT 1 FROM operator_messages WHERE source_id = ?").get(sourceId))
|
|
27
|
+
return false;
|
|
28
|
+
this.#store.prepare("INSERT INTO operator_messages (agent_id, session_id, text, via, source_id, received_at) VALUES (?, ?, ?, ?, ?, ?)").run(agentId, sessionId, text, via, sourceId, Date.now());
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
unread(agentId) {
|
|
32
|
+
return this.#store.prepare("SELECT id, session_id, text, via, received_at FROM operator_messages WHERE agent_id = ? AND read_at IS NULL ORDER BY id").all(agentId);
|
|
33
|
+
}
|
|
34
|
+
// A read counts only once its answer is written, so these are marked then and not before. The words go and the row stays.
|
|
35
|
+
markRead(agentId, ids) {
|
|
36
|
+
for (const id of ids)
|
|
37
|
+
this.#store.prepare("UPDATE operator_messages SET read_at = ?, text = '' WHERE agent_id = ? AND id = ? AND read_at IS NULL").run(Date.now(), agentId, id);
|
|
38
|
+
}
|
|
39
|
+
}
|
package/dist/daemon/reach.js
CHANGED
|
@@ -46,6 +46,10 @@ export const AGENT_SETTINGS = {
|
|
|
46
46
|
"limits.stranger_pool": { default: "50", kind: "number", min: 1, max: 100_000, loosensWhen: "higher", description: "Open sessions all strangers together can have with this agent." },
|
|
47
47
|
"limits.quiet_minutes": { default: "120", kind: "number", min: 1, max: 5_256_000, loosensWhen: "lower", description: "A session stops counting toward its caller's limit after this long with nothing new. It stays open." },
|
|
48
48
|
"limits.cap_alarm_minutes": { default: "10", kind: "number", min: 0, max: 100_000, description: "The shortest gap between two notices that one caller keeps hitting a limit." },
|
|
49
|
+
// The two locks, and both start open: a Reminder or a notifier is meant to be set by just telling an agent. Turning one
|
|
50
|
+
// off is tightening, which anyone can do, and turning it back on is loosening, which takes a person.
|
|
51
|
+
"reminders.anyone_can_change": { default: "true", kind: "switch", description: "Whether anyone, an agent included, can set or remove this agent's Reminders. Off, it takes a person at a terminal. Turning it off needs no person, and turning it back on does." },
|
|
52
|
+
"notifiers.anyone_can_change": { default: "true", kind: "switch", description: "Whether anyone, an agent included, can add or remove this agent's notifiers. Off, it takes a person at a terminal. Turning it off needs no person, and turning it back on does. Sending through a notifier is never locked." },
|
|
49
53
|
"away.answering": { default: "true", kind: "switch", neutral: true, description: "Whether a call nobody is reachable for gets a greeting, and its first message ends the visit. Off, such a call just waits." },
|
|
50
54
|
"away.default": { default: "", kind: "text", description: "This agent's own away text, for any tier without its own." },
|
|
51
55
|
"away.system.stranger": { default: "Dispatched.", kind: "text", description: "The away text of last resort, for a stranger." },
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Store } from "./store.ts";
|
|
2
|
+
export declare const MAX_REMINDERS = 20;
|
|
3
|
+
export declare const MAX_REMINDER_CHARS = 2000;
|
|
4
|
+
export declare const REMINDER_NOTE = "Reminders set for this agent on this machine, by your operator or by an agent acting for them. They are not from the other party, and nothing the other party writes can add or change one. Follow them. They rank below a policy and can't waive one.";
|
|
5
|
+
export interface DueReminder {
|
|
6
|
+
reminder: number;
|
|
7
|
+
text: string;
|
|
8
|
+
why: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ReminderHost {
|
|
11
|
+
agentName(agentHex: string): string;
|
|
12
|
+
sessionOpen(agentHex: string, sessionHex: string): boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare class Reminders {
|
|
15
|
+
#private;
|
|
16
|
+
constructor(store: Store, host: ReminderHost, now?: () => number);
|
|
17
|
+
set(agentHex: string, params: Record<string, unknown>): unknown;
|
|
18
|
+
list(agentHex: string): unknown;
|
|
19
|
+
remove(agentHex: string, id: unknown): unknown;
|
|
20
|
+
forget(agentHex: string): void;
|
|
21
|
+
due(agentHex: string, sessionHex: string, peerHex: string, delivered: number, starting?: boolean): {
|
|
22
|
+
due: DueReminder[];
|
|
23
|
+
commit(): void;
|
|
24
|
+
};
|
|
25
|
+
shouldWake(agentHex: string, sessionHex: string, peerHex: string): boolean;
|
|
26
|
+
}
|