@cello-protocol/cli 0.0.318 → 0.0.320
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/cli.js +2 -1
- package/dist/daemon/main.js +3 -2
- package/dist/daemon/notifiers.js +149 -13
- package/dist/daemon/telegram.d.ts +13 -1
- package/dist/daemon/telegram.js +22 -4
- package/dist/ipc/operations.js +4 -2
- package/hermes/plugin/__init__.py +6 -2
- package/hermes/plugin/__pycache__/__init__.cpython-314.pyc +0 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -187,7 +187,8 @@ function parse(op, args) {
|
|
|
187
187
|
const value = args[++i];
|
|
188
188
|
if (value === undefined)
|
|
189
189
|
usageError(`${arg} needs a value`, op);
|
|
190
|
-
|
|
190
|
+
// A secret given as - comes from standard input, so it isn't left in the shell's history or shown in a process list.
|
|
191
|
+
params[param.name] = param.name === "bot_token" && value === "-" ? readFileSync(0, "utf8").trim() : readValue(param, value);
|
|
191
192
|
}
|
|
192
193
|
if (given.length > positional.length)
|
|
193
194
|
usageError(`${op.command} takes ${positional.length} argument(s), got ${given.length}`, op);
|
package/dist/daemon/main.js
CHANGED
|
@@ -476,8 +476,9 @@ async function handle(socket, method, params) {
|
|
|
476
476
|
// Reaching the person. None of these acts as the agent in a conversation, so none takes the hold.
|
|
477
477
|
case "notifier_add": {
|
|
478
478
|
const agent = named(params);
|
|
479
|
-
unlessLocked(agent, "notifiers.anyone_can_change", params, `This adds a notifier for ${agent}, and that agent's notifiers are locked.`, `cello notifier-add ${shellQuoted(params["type"])} --bot-token <token
|
|
480
|
-
|
|
479
|
+
unlessLocked(agent, "notifiers.anyone_can_change", params, `This adds a notifier for ${agent}, and that agent's notifiers are locked.`, `cello notifier-add ${shellQuoted(params["type"])} ${params["same_as"] === undefined ? "--bot-token <token>" : `--same-as ${shellQuoted(params["same_as"])}`}${params["chat_id"] === undefined ? "" : ` --chat-id ${shellQuoted(params["chat_id"])}`}${params["name"] === undefined ? "" : ` --name ${shellQuoted(params["name"])}`} --agent ${agent}`);
|
|
480
|
+
// Named like any agent, and resolved here so the notifier only ever deals in ids.
|
|
481
|
+
return notifiers.add(agent, params["same_as"] === undefined ? params : { ...params, same_as_agent: engine.resolveAgent(text(params, "same_as")) });
|
|
481
482
|
}
|
|
482
483
|
case "notifier_list":
|
|
483
484
|
return notifiers.list(named(params));
|
package/dist/daemon/notifiers.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
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
2
|
// Telegram chat. The agent decides when to use one and what leaves the machine: a fixed line, or its own words.
|
|
3
3
|
// Anyone can set one up, agents included, because setting up a bot is hard enough already.
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
4
5
|
import { LocalError } from "./errors.js";
|
|
5
6
|
import { logEvent } from "./log.js";
|
|
6
|
-
import { TELEGRAM, TelegramError, botIdOf, botUsername, newestUpdate, sendText, updatesFrom } from "./telegram.js";
|
|
7
|
+
import { TELEGRAM, TelegramError, answerTap, botIdOf, botUsername, choiceIndex, clearButtons, newestUpdate, sendText, updatesFrom } from "./telegram.js";
|
|
7
8
|
const SCHEMA = `
|
|
8
9
|
CREATE TABLE IF NOT EXISTS notifiers (
|
|
9
10
|
agent_id BLOB NOT NULL REFERENCES agents(agent_id),
|
|
@@ -24,7 +25,12 @@ CREATE TABLE IF NOT EXISTS notifications (
|
|
|
24
25
|
-- 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
26
|
-- because each bot numbers its messages from one, so two bots in one person's chat share numbers.
|
|
26
27
|
remote_id TEXT NOT NULL,
|
|
27
|
-
sent_at INTEGER NOT NULL
|
|
28
|
+
sent_at INTEGER NOT NULL,
|
|
29
|
+
-- The choices offered as buttons, as JSON, and which was tapped. asked is the same on every row one notify call wrote,
|
|
30
|
+
-- so a question shown on two notifiers is still answered once.
|
|
31
|
+
choices TEXT,
|
|
32
|
+
chosen INTEGER,
|
|
33
|
+
asked TEXT
|
|
28
34
|
);
|
|
29
35
|
CREATE INDEX IF NOT EXISTS notifications_remote ON notifications (remote_id);
|
|
30
36
|
`;
|
|
@@ -32,6 +38,8 @@ export const NOTIFIER_TYPES = ["telegram"];
|
|
|
32
38
|
export const NOTIFY_KINDS = ["message", "request"];
|
|
33
39
|
// Telegram's own limit for one message.
|
|
34
40
|
const TELEGRAM_MAX_CHARS = 4096;
|
|
41
|
+
const MAX_CHOICES = 8;
|
|
42
|
+
const MAX_CHOICE_CHARS = 40;
|
|
35
43
|
const NAME_RULE = /^[A-Za-z0-9_-]{1,32}$/;
|
|
36
44
|
// The fixed lines. They say that something is waiting and nothing about what.
|
|
37
45
|
export function cannedLine(agentName, kind) {
|
|
@@ -67,6 +75,14 @@ export class Notifiers {
|
|
|
67
75
|
this.#store = store;
|
|
68
76
|
this.#host = host;
|
|
69
77
|
store.exec(SCHEMA);
|
|
78
|
+
// For a database from 0.0.317 to 0.0.319, whose table was made before choices existed.
|
|
79
|
+
const columns = store.prepare("PRAGMA table_info(notifications)").all().map((column) => column.name);
|
|
80
|
+
if (!columns.includes("choices"))
|
|
81
|
+
store.exec("ALTER TABLE notifications ADD COLUMN choices TEXT");
|
|
82
|
+
if (!columns.includes("chosen"))
|
|
83
|
+
store.exec("ALTER TABLE notifications ADD COLUMN chosen INTEGER");
|
|
84
|
+
if (!columns.includes("asked"))
|
|
85
|
+
store.exec("ALTER TABLE notifications ADD COLUMN asked TEXT");
|
|
70
86
|
}
|
|
71
87
|
// Starts listening for the operator's replies on every bot a notifier uses.
|
|
72
88
|
start() {
|
|
@@ -165,8 +181,83 @@ export class Notifiers {
|
|
|
165
181
|
logEvent("notifier.answer_failed", { bot: holder.botId, message: err instanceof Error ? err.message : String(err) });
|
|
166
182
|
}
|
|
167
183
|
}
|
|
184
|
+
// Takes the buttons off every message one notify call sent, on every notifier, and says in each chat what was decided.
|
|
185
|
+
// One question is answered once, wherever it was shown.
|
|
186
|
+
async #settleAsked(asked, tappedId, line, elsewhere) {
|
|
187
|
+
const rows = this.#store.prepare("SELECT id, agent_id, notifier, remote_id FROM notifications WHERE asked = ?").all(asked);
|
|
188
|
+
const holders = this.#holders();
|
|
189
|
+
for (const row of rows) {
|
|
190
|
+
const holder = holders.find((h) => h.name === row.notifier && h.agentHex === Buffer.from(row.agent_id).toString("hex"));
|
|
191
|
+
const messageId = Number(row.remote_id.split(":").at(-1));
|
|
192
|
+
if (!holder || !Number.isInteger(messageId))
|
|
193
|
+
continue;
|
|
194
|
+
try {
|
|
195
|
+
await clearButtons(this.#telegram, holder.token, holder.chat, messageId);
|
|
196
|
+
await sendText(this.#telegram, holder.token, holder.chat, row.id === tappedId ? line : elsewhere);
|
|
197
|
+
}
|
|
198
|
+
catch (err) {
|
|
199
|
+
logEvent("notifier.answer_failed", { bot: holder.botId, message: err instanceof Error ? err.message : String(err) });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
// A button was tapped. It answers one notification, so it goes to the agent and session that sent it, with no guessing.
|
|
204
|
+
// The same gate as a typed reply: only the exact bot and private chat a notifier holds.
|
|
205
|
+
async #onTap(botId, token, update) {
|
|
206
|
+
const tap = update.callback_query;
|
|
207
|
+
const under = tap?.message;
|
|
208
|
+
if (typeof tap?.id !== "string" || under?.chat?.id === undefined || typeof under.message_id !== "number")
|
|
209
|
+
return;
|
|
210
|
+
const chat = String(under.chat.id);
|
|
211
|
+
const holders = this.#holders().filter((h) => h.botId === botId && h.chat === chat);
|
|
212
|
+
const settle = async (line) => {
|
|
213
|
+
try {
|
|
214
|
+
await answerTap(this.#telegram, token, tap.id, line);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
logEvent("notifier.answer_failed", { bot: botId, message: err instanceof Error ? err.message : String(err) });
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
if (holders.length === 0 || under.chat.type !== "private") {
|
|
221
|
+
logEvent("notifier.reply_ignored", { bot: botId, reason: "a tap from a chat no notifier holds" });
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const sent = this.#store.prepare("SELECT id, agent_id, notifier, session_id, choices, asked FROM notifications WHERE remote_id = ? ORDER BY id DESC").get(`${botId}:${chat}:${under.message_id}`);
|
|
225
|
+
const holder = sent && holders.find((h) => h.name === sent.notifier && h.agentHex === Buffer.from(sent.agent_id).toString("hex"));
|
|
226
|
+
const choices = sent?.choices ? JSON.parse(sent.choices) : [];
|
|
227
|
+
if (!sent || !holder || sent.asked === null || choices.length === 0) {
|
|
228
|
+
await settle("This is no longer waiting for an answer.");
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const index = choiceIndex(tap.data);
|
|
232
|
+
const label = index === undefined ? undefined : choices[index];
|
|
233
|
+
if (label === undefined) {
|
|
234
|
+
await settle("That isn't one of the choices.");
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
// One question may have gone out on several notifiers. It's answered once, whichever chat the tap came from.
|
|
238
|
+
const answered = this.#store.prepare("SELECT chosen FROM notifications WHERE asked = ? AND chosen IS NOT NULL LIMIT 1").get(sent.asked);
|
|
239
|
+
if (answered) {
|
|
240
|
+
await settle(`Already answered: ${choices[answered.chosen] ?? "another choice"}.`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const outcome = this.#host.fromOperator(holder.agentHex, sent.session_id, label, holder.name, `telegram:${botId}:${update.update_id}`);
|
|
244
|
+
if (outcome === "no_agent") {
|
|
245
|
+
await settle("The agent this was for is no longer on this machine.");
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Marked before anything is said back, so a second tap in the same moment finds it answered.
|
|
249
|
+
this.#store.prepare("UPDATE notifications SET chosen = ? WHERE asked = ? AND chosen IS NULL").run(index, sent.asked);
|
|
250
|
+
const name = this.#host.agentName(holder.agentHex);
|
|
251
|
+
// "already" is this same tap fetched again after a restart: the agent has it, and the buttons may still be showing.
|
|
252
|
+
await settle(`Passed to ${name}.`);
|
|
253
|
+
await this.#settleAsked(sent.asked, sent.id, `You chose: ${label}. Passed to ${name}.`, `Answered on another of ${name}'s notifiers: ${label}.`);
|
|
254
|
+
}
|
|
168
255
|
// 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
256
|
async #onUpdate(botId, token, update) {
|
|
257
|
+
if (update.callback_query) {
|
|
258
|
+
await this.#onTap(botId, token, update);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
170
261
|
const message = update.message;
|
|
171
262
|
if (message?.chat?.id === undefined)
|
|
172
263
|
return;
|
|
@@ -241,9 +332,9 @@ export class Notifiers {
|
|
|
241
332
|
return row;
|
|
242
333
|
}
|
|
243
334
|
// One send through one notifier. Returns the notifier's own id for what it sent.
|
|
244
|
-
async #deliver(row, text) {
|
|
335
|
+
async #deliver(row, text, choices = []) {
|
|
245
336
|
const config = JSON.parse(row.config);
|
|
246
|
-
const sent = await sendText(this.#telegram, config.bot_token, config.chat_id, text);
|
|
337
|
+
const sent = await sendText(this.#telegram, config.bot_token, config.chat_id, text, choices);
|
|
247
338
|
return `${botIdOf(config.bot_token)}:${sent.chatId}:${sent.messageId}`;
|
|
248
339
|
}
|
|
249
340
|
// Proves the token and the chat with Telegram before anything is stored, so a mistake shows here and not at the first real notify.
|
|
@@ -255,9 +346,24 @@ export class Notifiers {
|
|
|
255
346
|
if (!NAME_RULE.test(name))
|
|
256
347
|
throw new LocalError("bad_argument", "name must be 1 to 32 letters, digits, underscores or dashes");
|
|
257
348
|
// A pasted token often carries a stray space or newline, which Telegram answers with a bare "Not Found".
|
|
258
|
-
|
|
349
|
+
let token = typeof params["bot_token"] === "string" ? params["bot_token"].trim() : "";
|
|
350
|
+
// Another agent on this machine already has the bot: take its notifier as it is, so the token is typed once, ever, and
|
|
351
|
+
// an agent can set this up for a new agent without being shown it.
|
|
352
|
+
let sameChat;
|
|
353
|
+
const sameAs = params["same_as_agent"];
|
|
354
|
+
if (typeof sameAs === "string") {
|
|
355
|
+
if (token.length > 0)
|
|
356
|
+
throw new LocalError("bad_argument", "give bot_token or same_as, not both");
|
|
357
|
+
const theirs = this.#rows(sameAs).filter((row) => row.type === type);
|
|
358
|
+
const source = theirs.find((row) => row.name === name) ?? (theirs.length === 1 ? theirs[0] : undefined);
|
|
359
|
+
if (!source)
|
|
360
|
+
throw new LocalError("no_such_notifier", `${this.#host.agentName(sameAs)} has ${theirs.length === 0 ? "no Telegram notifier to copy" : `${theirs.length} Telegram notifiers, so say which with name: ${theirs.map((row) => row.name).join(", ")}`}.`);
|
|
361
|
+
const config = JSON.parse(source.config);
|
|
362
|
+
token = config.bot_token;
|
|
363
|
+
sameChat = config.chat_number;
|
|
364
|
+
}
|
|
259
365
|
if (token.length === 0)
|
|
260
|
-
throw new LocalError("bad_argument", "A Telegram notifier needs bot_token
|
|
366
|
+
throw new LocalError("bad_argument", "A Telegram notifier needs bot_token, the token BotFather gave for the bot, or same_as, an agent on this machine that already has one.");
|
|
261
367
|
const agentName = this.#host.agentName(agentHex);
|
|
262
368
|
const existing = this.#rows(agentHex);
|
|
263
369
|
if (existing.some((r) => r.name === name))
|
|
@@ -270,7 +376,7 @@ export class Notifiers {
|
|
|
270
376
|
const sameBot = this.#holders().filter((h) => h.botId === botId);
|
|
271
377
|
const reading = sameBot.length > 0;
|
|
272
378
|
let bot;
|
|
273
|
-
let chatId = typeof params["chat_id"] === "string" && params["chat_id"].trim().length > 0 ? params["chat_id"].trim() :
|
|
379
|
+
let chatId = typeof params["chat_id"] === "string" && params["chat_id"].trim().length > 0 ? params["chat_id"].trim() : sameChat;
|
|
274
380
|
let chatWho;
|
|
275
381
|
let chatNumber;
|
|
276
382
|
let newest;
|
|
@@ -358,14 +464,16 @@ export class Notifiers {
|
|
|
358
464
|
return rows;
|
|
359
465
|
}
|
|
360
466
|
// 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) {
|
|
467
|
+
async #sendAll(agentHex, rows, text, kind, sessionId, record, choices = []) {
|
|
362
468
|
const reached = [];
|
|
363
469
|
const failed = [];
|
|
470
|
+
// The same on every notifier this one call reaches, so a question with choices is answered once across all of them.
|
|
471
|
+
const asked = choices.length > 0 ? randomBytes(12).toString("hex") : null;
|
|
364
472
|
for (const row of rows) {
|
|
365
473
|
try {
|
|
366
|
-
const remoteId = await this.#deliver(row, text);
|
|
474
|
+
const remoteId = await this.#deliver(row, text, choices);
|
|
367
475
|
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());
|
|
476
|
+
this.#store.prepare("INSERT INTO notifications (agent_id, notifier, session_id, kind, remote_id, sent_at, choices, asked) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(idOf(agentHex), row.name, sessionId, kind, remoteId, Date.now(), asked ? JSON.stringify(choices) : null, asked);
|
|
369
477
|
reached.push(row.name);
|
|
370
478
|
}
|
|
371
479
|
catch (err) {
|
|
@@ -408,8 +516,36 @@ export class Notifiers {
|
|
|
408
516
|
if (text.length > TELEGRAM_MAX_CHARS)
|
|
409
517
|
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
518
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
519
|
+
// Choices the person answers with one tap. They are the agent's words too, so they pass the same screen, together, and
|
|
520
|
+
// if the screen changes how many lines there are, nothing is sent: a button must mean what the agent meant by it.
|
|
521
|
+
let choices = [];
|
|
522
|
+
const offered = params["choices"];
|
|
523
|
+
if (offered !== undefined) {
|
|
524
|
+
if (typeof offered !== "string")
|
|
525
|
+
throw new LocalError("bad_argument", "choices must be text: the choices with | between them");
|
|
526
|
+
// A line break inside one would shift every choice after it when they're screened together, a line each.
|
|
527
|
+
if (/[\r\n]/.test(offered))
|
|
528
|
+
throw new LocalError("bad_argument", "a choice can't hold a line break. Put each on one line, with | between them.");
|
|
529
|
+
choices = offered.split("|").map((choice) => choice.trim()).filter((choice) => choice.length > 0);
|
|
530
|
+
if (choices.length < 2 || choices.length > MAX_CHOICES)
|
|
531
|
+
throw new LocalError("bad_argument", `choices takes 2 to ${MAX_CHOICES} choices with | between them, such as "Agree|Disagree". This has ${choices.length}.`);
|
|
532
|
+
const long = choices.find((choice) => choice.length > MAX_CHOICE_CHARS);
|
|
533
|
+
if (long !== undefined)
|
|
534
|
+
throw new LocalError("too_long", `A choice holds ${MAX_CHOICE_CHARS} characters, so it fits on a button, and "${long.slice(0, 30)}..." is ${long.length}. Put the detail in the text and keep the choice short.`);
|
|
535
|
+
if (new Set(choices).size !== choices.length)
|
|
536
|
+
throw new LocalError("bad_argument", "two of the choices are the same, so the answer wouldn't say which was meant");
|
|
537
|
+
const screened = await this.#host.screenOutbound(agentHex, choices.join("\n"), params, `cello notify --choices ... --allow-flagged --agent ${agentHex}`);
|
|
538
|
+
const after = screened.text.split("\n");
|
|
539
|
+
if (after.length !== choices.length || after.some((choice) => choice.trim().length === 0))
|
|
540
|
+
throw new LocalError("blocked_by_screening", "Nobody was told: the outbound screen changed the choices so they no longer line up. Reword them.");
|
|
541
|
+
choices = after.map((choice) => choice.trim());
|
|
542
|
+
// Two different choices can come out of the screen as the same words, and then a tap wouldn't say which was meant.
|
|
543
|
+
if (new Set(choices).size !== choices.length)
|
|
544
|
+
throw new LocalError("blocked_by_screening", "Nobody was told: after the outbound screen replaced part of them, two of the choices read the same. Reword them so each differs without what was replaced.");
|
|
545
|
+
report = { ...report, ...screened.report };
|
|
546
|
+
}
|
|
547
|
+
const answer = await this.#sendAll(agentHex, rows, text, kind, sessionHex === undefined ? null : new Uint8Array(Buffer.from(sessionHex, "hex")), true, choices);
|
|
548
|
+
logEvent("notifier.sent", { agent: agentHex, kind, with_text: given !== undefined && given.length > 0, choices: choices.length });
|
|
549
|
+
return { ...answer, kind, included_text: given !== undefined && given.length > 0, ...(choices.length > 0 ? { choices } : {}), ...report };
|
|
414
550
|
}
|
|
415
551
|
}
|
|
@@ -27,10 +27,22 @@ export interface TelegramUpdate {
|
|
|
27
27
|
message_id?: number;
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
|
+
callback_query?: {
|
|
31
|
+
id?: string;
|
|
32
|
+
data?: string;
|
|
33
|
+
message?: {
|
|
34
|
+
message_id?: number;
|
|
35
|
+
text?: string;
|
|
36
|
+
chat?: TelegramChat;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
30
39
|
}
|
|
40
|
+
export declare function choiceIndex(data: unknown): number | undefined;
|
|
31
41
|
export declare function newestUpdate(at: TelegramEndpoint, token: string): Promise<TelegramUpdate | undefined>;
|
|
32
42
|
export declare function updatesFrom(at: TelegramEndpoint, token: string, offset: number, stop: AbortSignal): Promise<TelegramUpdate[]>;
|
|
33
|
-
export declare function sendText(at: TelegramEndpoint, token: string, chatId: string, text: string): Promise<{
|
|
43
|
+
export declare function sendText(at: TelegramEndpoint, token: string, chatId: string, text: string, choices?: readonly string[]): Promise<{
|
|
34
44
|
chatId: string;
|
|
35
45
|
messageId: number;
|
|
36
46
|
}>;
|
|
47
|
+
export declare function answerTap(at: TelegramEndpoint, token: string, tapId: string, text: string): Promise<void>;
|
|
48
|
+
export declare function clearButtons(at: TelegramEndpoint, token: string, chatId: string, messageId: number): Promise<void>;
|
package/dist/daemon/telegram.js
CHANGED
|
@@ -100,22 +100,40 @@ export async function botUsername(at, token) {
|
|
|
100
100
|
throw new TelegramError("Telegram accepted the token but didn't name a bot.");
|
|
101
101
|
return me.username;
|
|
102
102
|
}
|
|
103
|
+
// What a button carries back when it's tapped: its place in the list. Telegram allows 64 bytes, so never the words.
|
|
104
|
+
const choiceData = (index) => `choice:${index}`;
|
|
105
|
+
export function choiceIndex(data) {
|
|
106
|
+
const match = typeof data === "string" ? /^choice:(\d+)$/.exec(data) : null;
|
|
107
|
+
return match ? Number(match[1]) : undefined;
|
|
108
|
+
}
|
|
103
109
|
// The newest thing sent to the bot, alone. Offset -1 asks for just that: without it Telegram gives the oldest hundred, and
|
|
104
110
|
// "last" would be wrong on a bot with a backlog. It also makes Telegram forget everything older.
|
|
105
111
|
export async function newestUpdate(at, token) {
|
|
106
|
-
|
|
112
|
+
// The same kinds the reader asks for: Telegram keeps whatever the last call named, so naming fewer here would switch taps off.
|
|
113
|
+
const updates = await call(at, token, "getUpdates", { offset: -1, timeout: 0, allowed_updates: ["message", "callback_query"] });
|
|
107
114
|
return updates.at(-1);
|
|
108
115
|
}
|
|
109
116
|
// Everything sent to the bot from this update on, waiting up to pollSeconds for the first. Stopping it ends the wait at once.
|
|
110
117
|
export async function updatesFrom(at, token, offset, stop) {
|
|
111
118
|
// One try: the reader calls again by itself, with a growing wait.
|
|
112
|
-
return await call(at, token, "getUpdates", { offset, timeout: at.pollSeconds, allowed_updates: ["message"] }, at.pollSeconds * 1000 + at.timeoutMs, stop, 1);
|
|
119
|
+
return await call(at, token, "getUpdates", { offset, timeout: at.pollSeconds, allowed_updates: ["message", "callback_query"] }, at.pollSeconds * 1000 + at.timeoutMs, stop, 1);
|
|
113
120
|
}
|
|
114
121
|
// Answers only once Telegram has accepted the message, with the ids Telegram gave: the chat's own number, which is what a
|
|
115
122
|
// reply will carry even if the chat was named as @something, and the message's.
|
|
116
|
-
|
|
117
|
-
|
|
123
|
+
// With choices, each becomes a button under the message, one to a row so a long one is never cut short.
|
|
124
|
+
export async function sendText(at, token, chatId, text, choices = []) {
|
|
125
|
+
const buttons = choices.length === 0 ? {} : { reply_markup: { inline_keyboard: choices.map((label, index) => [{ text: label, callback_data: choiceData(index) }]) } };
|
|
126
|
+
const sent = await call(at, token, "sendMessage", { chat_id: chatId, text, ...buttons });
|
|
118
127
|
if (typeof sent?.message_id !== "number" || sent.chat?.id === undefined)
|
|
119
128
|
throw new TelegramError("Telegram accepted the message but didn't say where it went.");
|
|
120
129
|
return { chatId: String(sent.chat.id), messageId: sent.message_id };
|
|
121
130
|
}
|
|
131
|
+
// Stops the tapped button's spinner, with a short line Telegram shows the person.
|
|
132
|
+
export async function answerTap(at, token, tapId, text) {
|
|
133
|
+
await call(at, token, "answerCallbackQuery", { callback_query_id: tapId, text });
|
|
134
|
+
}
|
|
135
|
+
// Takes the buttons off a message, so a choice that's been made can't be made again. The words are left alone: rewriting
|
|
136
|
+
// them can fail on a long message, and Telegram doesn't always give an old message's text back.
|
|
137
|
+
export async function clearButtons(at, token, chatId, messageId) {
|
|
138
|
+
await call(at, token, "editMessageReplyMarkup", { chat_id: chatId, message_id: messageId, reply_markup: { inline_keyboard: [] } });
|
|
139
|
+
}
|
package/dist/ipc/operations.js
CHANGED
|
@@ -921,6 +921,7 @@ The code stops agents that are simply trying commands, and pipes and scripts wit
|
|
|
921
921
|
params: [
|
|
922
922
|
{ name: "text", kind: "string", positional: true, description: "What to tell them. Leave out to send the fixed line and nothing else. On the command line, - reads it from standard input." },
|
|
923
923
|
{ name: "kind", kind: "string", allowed: ["message", "request"], description: "message: something to read. request: you need an answer. Left out: message." },
|
|
924
|
+
{ name: "choices", kind: "string", description: "Answers your operator can give with one tap, 2 to 8 of them with | between, such as \"Agree|Disagree|Ask me later\". Each is at most 40 characters and is shown as a button. The one they tap comes back under from_your_operator as its exact words, for this session. They can still type an answer instead. The choices leave this machine with the message, so they pass the outbound screen too." },
|
|
924
925
|
{ name: "session_id", kind: "string", description: "The session this is about, 32 hex characters, so an answer can be matched to it." },
|
|
925
926
|
{ name: "notifier", kind: "string", description: "Only this notifier. Left out: every notifier the agent has." },
|
|
926
927
|
{ name: "allow_flagged", kind: "boolean", description: "Send a value a guard held. Needs a person at a terminal, unless the autonomous_override guard is on." },
|
|
@@ -932,10 +933,11 @@ The code stops agents that are simply trying commands, and pipes and scripts wit
|
|
|
932
933
|
summary: "Set up a way to reach the agent's human operator, such as Telegram.",
|
|
933
934
|
scoped: true,
|
|
934
935
|
acts: false,
|
|
935
|
-
description: "Set up a notifier: a route notify uses to reach the agent's human operator. Anyone can do this, an agent included. For telegram, the person makes a bot with @BotFather, sends that bot any message, and gives you the bot's token. With no chat_id, it uses the chat that wrote to the bot last and says whose it is. One bot can serve all of a person's agents: for the next agent
|
|
936
|
+
description: "Set up a notifier: a route notify uses to reach the agent's human operator. Anyone can do this, an agent included. For telegram, the person makes a bot with @BotFather, sends that bot any message, and gives you the bot's token. With no chat_id, it uses the chat that wrote to the bot last and says whose it is. One bot can serve all of a person's agents: for the next agent, name one that already has it with same_as, and no token is needed. The token and the chat are checked with Telegram, and a test message is sent, before anything is saved. The token is kept in the encrypted database and never shown again. Notifiers the agent already had are told a new one was added. If the agent's setting notifiers.anyone_can_change is off, adding or removing one takes a person, and the refusal gives the command to relay.",
|
|
936
937
|
params: [
|
|
937
938
|
{ name: "type", kind: "string", required: true, positional: true, allowed: ["telegram"], description: "What kind of notifier." },
|
|
938
|
-
{ name: "bot_token", kind: "string", description: "telegram: the bot's token, from @BotFather." },
|
|
939
|
+
{ name: "bot_token", kind: "string", description: "telegram: the bot's token, from @BotFather. On the command line, - reads it from standard input, which keeps it out of the shell's history." },
|
|
940
|
+
{ name: "same_as", kind: "string", description: "An agent on this machine that already has a notifier: its name or agent_id. This agent gets the same bot and chat, with no token to give. Use it in place of bot_token." },
|
|
939
941
|
{ name: "chat_id", kind: "string", description: "telegram: the id of the chat to write to. Left out: the chat that wrote to the bot last." },
|
|
940
942
|
{ name: "name", kind: "string", description: "Your name for it, 1 to 32 letters, digits, underscores or dashes. Left out: its type." },
|
|
941
943
|
],
|
|
@@ -998,7 +998,9 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
998
998
|
line = "[CELLO notice] " + text
|
|
999
999
|
sid = _safe_scalar(notice.get("session_id"))
|
|
1000
1000
|
logger.info("[cello] Notice for session %s: %s", sid, text)
|
|
1001
|
-
|
|
1001
|
+
# Only a read of a session has a turn to put these in. A read of none has no turn, so nothing counts as "here":
|
|
1002
|
+
# with both ids empty they once matched, went into a list nobody used, and were never shown.
|
|
1003
|
+
if current_session is not None and (sid == current_session or (sid is None and self._session_scope == "agent")):
|
|
1002
1004
|
here.append(line)
|
|
1003
1005
|
continue
|
|
1004
1006
|
if sid is None:
|
|
@@ -1017,7 +1019,9 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
1017
1019
|
line = OPERATOR_HEADING + "\n" + reply["text"]
|
|
1018
1020
|
sid = _safe_scalar(reply.get("session_id"))
|
|
1019
1021
|
logger.info("[cello] The operator answered through %s, about session %s", reply.get("via"), sid)
|
|
1020
|
-
|
|
1022
|
+
# Only a read of a session has a turn to put these in. A read of none has no turn, so nothing counts as "here":
|
|
1023
|
+
# with both ids empty they once matched, went into a list nobody used, and were never shown.
|
|
1024
|
+
if current_session is not None and (sid == current_session or (sid is None and self._session_scope == "agent")):
|
|
1021
1025
|
here.append(line)
|
|
1022
1026
|
continue
|
|
1023
1027
|
if sid is None:
|
|
Binary file
|