@niwa-labs/telegram 0.0.0-stage → 0.0.0
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/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +18 -4
- package/src/bot.ts +212 -0
- package/src/index.ts +964 -0
- package/test/bot.test.ts +101 -0
- package/test/telegram.test.ts +1371 -0
- package/tsconfig.json +6 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,964 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* index.ts — the Telegram surface: the plugin and its actions.
|
|
3
|
+
*
|
|
4
|
+
* The service long-polls Telegram and writes each message of the owner's chat as a record. The
|
|
5
|
+
* id of a record is made from the bot, the run of update ids and the update id, and the offset to
|
|
6
|
+
* ask from is read back from the journal while it is recent, so a restart neither loses an update
|
|
7
|
+
* nor writes one twice. Only the owner's private chat, and the owner in it, is a way into niwa: a
|
|
8
|
+
* message or a press of a button from anywhere else is written down as ignored, without its
|
|
9
|
+
* text, and nothing it sends is done with the owner's rights.
|
|
10
|
+
*
|
|
11
|
+
* The surface speaks for the owner only as an instance configured with `speaksFor`, and then only
|
|
12
|
+
* for input from the owner's chat. Without it the surface is a plain client: an answer from the
|
|
13
|
+
* owner's chat is refused by the requests module, which lets only the addressee answer.
|
|
14
|
+
*
|
|
15
|
+
* What waits for the owner is one list, and this chat is one view of it. A request addressed to
|
|
16
|
+
* the owner is posted as a message, and the message is the way back to the request. The owner
|
|
17
|
+
* answers it by a button (a choice, a confirmation, a permission) or by replying to the message
|
|
18
|
+
* (a text, the numbers of a multiple choice, or a text of his own where the question allows one);
|
|
19
|
+
* the answer is given by calling "request.answer" as the owner. A form is not filled here: the
|
|
20
|
+
* message says where to answer it.
|
|
21
|
+
*
|
|
22
|
+
* A button carries the place of its answer and nothing else: Telegram gives a callback 64 bytes,
|
|
23
|
+
* and the id of a request is longer. A press is written down as it came, and a handler finds the
|
|
24
|
+
* request in the record of the message, by bot, chat and message.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { NotSent, OptionIdSchema, action, client, optionsOf, owner, providerWrote, questionLines, record } from "@niwa-labs/core";
|
|
28
|
+
import type { Action, ActionContext, Answer, Caller, JournalReader, Outcome, RecordType, SpeaksFor, StoredRecord } from "@niwa-labs/core";
|
|
29
|
+
import { AgentTurnFailed, AgentTurnQueued, AgentTurnReplied, agentTell } from "@niwa-labs/agent/records";
|
|
30
|
+
import { bindingOf, plugin } from "@niwa-labs/plugin";
|
|
31
|
+
import type { CallerBinding, Plugin, PluginApi, ServiceContext } from "@niwa-labs/plugin";
|
|
32
|
+
import { createHash } from "node:crypto";
|
|
33
|
+
|
|
34
|
+
import { z } from "zod";
|
|
35
|
+
|
|
36
|
+
import {
|
|
37
|
+
REQUEST_ANSWER,
|
|
38
|
+
RequestAnswered,
|
|
39
|
+
RequestCancelled,
|
|
40
|
+
RequestCancelledRecord,
|
|
41
|
+
RequestCreated,
|
|
42
|
+
RequestExpiredRecord,
|
|
43
|
+
RequestId,
|
|
44
|
+
answeredBy,
|
|
45
|
+
question,
|
|
46
|
+
operatorAnswered,
|
|
47
|
+
requestAsk,
|
|
48
|
+
} from "@niwa-labs/requests/records";
|
|
49
|
+
|
|
50
|
+
import {
|
|
51
|
+
chatSchema,
|
|
52
|
+
createBot,
|
|
53
|
+
messageSchema,
|
|
54
|
+
updateSchema,
|
|
55
|
+
type Bot,
|
|
56
|
+
type ChatId,
|
|
57
|
+
type InlineKeyboard,
|
|
58
|
+
type MessageId,
|
|
59
|
+
type Update,
|
|
60
|
+
type UserId,
|
|
61
|
+
type UpdateId,
|
|
62
|
+
} from "./bot.ts";
|
|
63
|
+
|
|
64
|
+
export const TELEGRAM_SEND = "telegram.send";
|
|
65
|
+
export const TELEGRAM_RECEIVED = "telegram.received";
|
|
66
|
+
export const TELEGRAM_IGNORED = "telegram.ignored";
|
|
67
|
+
export const TELEGRAM_REQUEST = "telegram.request";
|
|
68
|
+
export const TELEGRAM_PRESS = "telegram.press";
|
|
69
|
+
export const TELEGRAM_ACKNOWLEDGE = "telegram.acknowledge";
|
|
70
|
+
export const TELEGRAM_TO_AGENT = "telegram.to-agent";
|
|
71
|
+
export const TELEGRAM_POST_REQUEST = "telegram.post-request";
|
|
72
|
+
|
|
73
|
+
/** The options of what the owner is asked when his message did not reach the agent. */
|
|
74
|
+
const RETRY = OptionIdSchema.parse("retry");
|
|
75
|
+
const CANCEL = OptionIdSchema.parse("cancel");
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* What the owner is asked when his message did not reach the agent, or may not have.
|
|
79
|
+
*
|
|
80
|
+
* `mayHaveArrived` says whether the agent may already have taken the message: a delivery that was
|
|
81
|
+
* cut off, or that failed after it began, leaves that open, and a retry then repeats the command.
|
|
82
|
+
*/
|
|
83
|
+
function undelivered(text: string, mayHaveArrived: boolean) {
|
|
84
|
+
return question("telegram.undelivered", {
|
|
85
|
+
kind: "choice",
|
|
86
|
+
title: undeliveredText(text, mayHaveArrived),
|
|
87
|
+
options: [
|
|
88
|
+
{ id: RETRY, label: mayHaveArrived ? "send again" : "retry", flavor: "plain" },
|
|
89
|
+
{ id: CANCEL, label: "cancel", flavor: "plain" },
|
|
90
|
+
],
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** How much of the message the question quotes. */
|
|
95
|
+
const QUOTE_LENGTH = 80;
|
|
96
|
+
|
|
97
|
+
/** The words that tell the owner what became of his message, with the beginning of it. */
|
|
98
|
+
function undeliveredText(text: string, mayHaveArrived: boolean): string {
|
|
99
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
100
|
+
// By code points, so an emoji is never cut in half.
|
|
101
|
+
const points = Array.from(flat);
|
|
102
|
+
const quote = points.length > QUOTE_LENGTH ? `${points.slice(0, QUOTE_LENGTH).join("")}...` : flat;
|
|
103
|
+
return mayHaveArrived
|
|
104
|
+
? `Your message may already have reached the agent: "${quote}". Sending it again repeats it, and the agent may act on it twice. Send it again only if you know it did not arrive, or cancel.`
|
|
105
|
+
: `Your message was NOT delivered to the agent: "${quote}". Retry the delivery or cancel it.`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether a delivery that ended so may nevertheless have reached the agent. */
|
|
109
|
+
function mayHaveArrived(outcome: Outcome<unknown>): boolean {
|
|
110
|
+
switch (outcome.status) {
|
|
111
|
+
case "completed":
|
|
112
|
+
case "unknown":
|
|
113
|
+
return true;
|
|
114
|
+
case "failed":
|
|
115
|
+
return outcome.effectPossible;
|
|
116
|
+
case "denied":
|
|
117
|
+
case "cancelled":
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The name of the plugin: the handlers of the surface are the calls the owner makes here. */
|
|
123
|
+
const PLUGIN_NAME = "telegram";
|
|
124
|
+
|
|
125
|
+
/** The records that end a request: a request that is ended is not one the owner may answer. */
|
|
126
|
+
const END_TYPES = [
|
|
127
|
+
RequestAnswered.name,
|
|
128
|
+
RequestCancelledRecord.name,
|
|
129
|
+
RequestExpiredRecord.name,
|
|
130
|
+
];
|
|
131
|
+
|
|
132
|
+
/** How long the service waits for the record of a message that is not committed yet. */
|
|
133
|
+
const POSTED_WAIT_MS = 5_000;
|
|
134
|
+
|
|
135
|
+
/** How long the service waits between two looks for that record. */
|
|
136
|
+
const POSTED_POLL_MS = 50;
|
|
137
|
+
|
|
138
|
+
/** A request as it was created. */
|
|
139
|
+
type Created = z.infer<typeof RequestCreated.schema>;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Where an update came from: the bot, and the run of update ids it belongs to.
|
|
143
|
+
*
|
|
144
|
+
* Telegram numbers updates in sequence, but starts again from an arbitrary number after a week
|
|
145
|
+
* without any, and another bot has a numbering of its own. An update is told apart by its
|
|
146
|
+
* numbering and its number, so a number seen again in a new run is a new update, never a repeat.
|
|
147
|
+
*/
|
|
148
|
+
const Source = {
|
|
149
|
+
/** The id of the bot, the part of its token that is not secret. */
|
|
150
|
+
bot: z.string(),
|
|
151
|
+
/** The run of update ids: the moment it began. */
|
|
152
|
+
epoch: z.number(),
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** A message that came in from the owner's chat. */
|
|
156
|
+
export const Received = record(
|
|
157
|
+
TELEGRAM_RECEIVED,
|
|
158
|
+
z.object({
|
|
159
|
+
...Source,
|
|
160
|
+
update: updateSchema,
|
|
161
|
+
chat: chatSchema,
|
|
162
|
+
message: messageSchema,
|
|
163
|
+
text: z.string(),
|
|
164
|
+
/** Who wrote it, as Telegram names them. */
|
|
165
|
+
from: z.string().optional(),
|
|
166
|
+
/** The message it replies to, when it is a reply. */
|
|
167
|
+
reply: messageSchema.optional(),
|
|
168
|
+
}),
|
|
169
|
+
{ providerOnly: "telegram" },
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
/** A message from another chat: not the owner's, so only the fact of it is kept. */
|
|
173
|
+
export const Ignored = record(
|
|
174
|
+
TELEGRAM_IGNORED,
|
|
175
|
+
z.object({ ...Source, update: updateSchema, chat: chatSchema, message: messageSchema }),
|
|
176
|
+
{ providerOnly: "telegram" },
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
/** A request that was posted to the owner, with the buttons that answer it. */
|
|
180
|
+
export const Posted = record(
|
|
181
|
+
TELEGRAM_REQUEST,
|
|
182
|
+
z.object({
|
|
183
|
+
/** The bot that sent it: a message id is only unique within the chat of one bot. */
|
|
184
|
+
bot: z.string(),
|
|
185
|
+
/** The id of the request: the message is the way back to it. */
|
|
186
|
+
request: RequestId,
|
|
187
|
+
chat: chatSchema,
|
|
188
|
+
message: messageSchema,
|
|
189
|
+
/** The name of the question that was asked. */
|
|
190
|
+
question: z.string(),
|
|
191
|
+
/** The kind of the question: it says how a reply is read. */
|
|
192
|
+
kind: z.enum(["choice", "multi", "confirm", "text", "form", "permission"]),
|
|
193
|
+
/** Whether a text of the owner's own is an answer too. */
|
|
194
|
+
allowOther: z.boolean(),
|
|
195
|
+
/** The choices the buttons stand for, in the order of the buttons. */
|
|
196
|
+
choices: z.array(z.string()),
|
|
197
|
+
}),
|
|
198
|
+
{ providerOnly: "telegram" },
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The press of a button in the owner's chat, as it came: written before the offset passes it, so
|
|
203
|
+
* a press is never lost to the time it takes to find what it answers.
|
|
204
|
+
*/
|
|
205
|
+
export const Pressed = record(
|
|
206
|
+
TELEGRAM_PRESS,
|
|
207
|
+
z.object({
|
|
208
|
+
...Source,
|
|
209
|
+
update: updateSchema,
|
|
210
|
+
chat: chatSchema,
|
|
211
|
+
/** The message the button is under. */
|
|
212
|
+
message: messageSchema,
|
|
213
|
+
/** The id of the press, which the acknowledgement answers. */
|
|
214
|
+
query: z.string(),
|
|
215
|
+
/** What the button carried back. */
|
|
216
|
+
data: z.string(),
|
|
217
|
+
}),
|
|
218
|
+
{ providerOnly: "telegram" },
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
/** The poller writes directly from its installed service after validating the Bot API update. */
|
|
222
|
+
function fromPoller(record: StoredRecord): boolean {
|
|
223
|
+
return record.actor.kind === "host" && record.actor.issuedBy === undefined;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** A day, in milliseconds: how long Telegram keeps an update nobody confirmed. */
|
|
227
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
228
|
+
|
|
229
|
+
/** The record types the polling service restores its offset from. */
|
|
230
|
+
const OFFSET_TYPES = [Received, Ignored, Pressed];
|
|
231
|
+
|
|
232
|
+
export const TelegramReplyDelivery = record("telegram.reply.delivery", z.object({
|
|
233
|
+
turn: z.string(), bot: z.string(), chat: chatSchema, replyTo: messageSchema,
|
|
234
|
+
status: z.enum(["sent", "unsent", "possibly-sent"]), sentParts: z.number().int().nonnegative(),
|
|
235
|
+
reason: z.string().optional(),
|
|
236
|
+
}));
|
|
237
|
+
|
|
238
|
+
export interface TelegramOptions {
|
|
239
|
+
/** The agent whose conversations this bot delivers in both directions. */
|
|
240
|
+
readonly agent?: string;
|
|
241
|
+
/** The token of the bot: what Telegram gave it. */
|
|
242
|
+
readonly token: string;
|
|
243
|
+
/** The private chat of the owner: its id is the owner's user id, and it is positive. Only this chat is read. */
|
|
244
|
+
readonly owner: ChatId;
|
|
245
|
+
/**
|
|
246
|
+
* Speak for the owner: a press of a button in the owner's chat answers a request addressed to
|
|
247
|
+
* the owner. Without it the surface is a plain client, and the press is refused.
|
|
248
|
+
*/
|
|
249
|
+
readonly speaksFor?: SpeaksFor;
|
|
250
|
+
/** The base of the Bot API: the real one, unless a test says otherwise. */
|
|
251
|
+
readonly apiBase?: string;
|
|
252
|
+
/** How long one poll waits for an update, in seconds. */
|
|
253
|
+
readonly pollTimeout?: number;
|
|
254
|
+
/** How long the service waits after a failed poll, in milliseconds. */
|
|
255
|
+
readonly retryDelay?: number;
|
|
256
|
+
/** The bot, when the caller has one of its own. */
|
|
257
|
+
readonly bot?: Bot;
|
|
258
|
+
/**
|
|
259
|
+
* How long the offset of the polls is trusted after the last update it passed, in milliseconds.
|
|
260
|
+
* Telegram keeps an update for a day and starts its numbering anew only after a week without
|
|
261
|
+
* updates, so past a day the offset is dropped and a new run of numbers begins. Default: a day.
|
|
262
|
+
*/
|
|
263
|
+
readonly offsetTtl?: number;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export interface TelegramHooks {
|
|
267
|
+
/**
|
|
268
|
+
* Send a message to the owner's main agent, when the messages plugin is present.
|
|
269
|
+
*
|
|
270
|
+
* The hook runs inside the action that delivers the message, with its context. A call it makes
|
|
271
|
+
* with `ctx.step.outcome` is made by this surface, so with `speaksFor` it is the owner's, as long
|
|
272
|
+
* as the composition gives the modules that bind callers the binding of this instance.
|
|
273
|
+
*
|
|
274
|
+
* It returns what became of the delivery, the outcome of its last call: a call that failed, was
|
|
275
|
+
* denied or was cut short is reported to the owner, who is asked whether to send again. A hook
|
|
276
|
+
* that calls with `ctx.step` instead pauses the invocation on any outcome but success, and the
|
|
277
|
+
* owner is never told. A hook that returns nothing delivered; one that throws did not, though it
|
|
278
|
+
* may have got part of the way.
|
|
279
|
+
*
|
|
280
|
+
* Without it the message stays in the journal and the agent reads it there.
|
|
281
|
+
*/
|
|
282
|
+
toAgent?: (text: string, ctx: ActionContext) => Promise<Outcome<unknown> | void>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Where an update was numbered: what its record ids are made from. */
|
|
286
|
+
interface UpdateSource {
|
|
287
|
+
readonly bot: string;
|
|
288
|
+
readonly epoch: number;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The id of the record of an incoming message: its source and update id, so a repeat is harmless. */
|
|
292
|
+
export function receivedId(source: UpdateSource, update: UpdateId): string {
|
|
293
|
+
return `rec_telegram_${source.bot}_${String(source.epoch)}_${String(update)}`;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The id of the record of a message from another chat. */
|
|
297
|
+
function ignoredId(source: UpdateSource, update: UpdateId): string {
|
|
298
|
+
return `rec_telegram_ignored_${source.bot}_${String(source.epoch)}_${String(update)}`;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** The id of the record of a button press. */
|
|
302
|
+
function pressedId(source: UpdateSource, update: UpdateId): string {
|
|
303
|
+
return `rec_telegram_press_${source.bot}_${String(source.epoch)}_${String(update)}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* The id of a bot, as its records name it: the number its token starts with, which is public. A
|
|
308
|
+
* token of another shape is named by a digest, never by itself.
|
|
309
|
+
*/
|
|
310
|
+
export function botIdOf(token: string): string {
|
|
311
|
+
const head = token.split(":")[0] ?? "";
|
|
312
|
+
return /^\d+$/.test(head) ? head : `h${createHash("sha256").update(token).digest("hex").slice(0, 12)}`;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The callback data of a button: the place of its answer among the choices of the message.
|
|
317
|
+
*
|
|
318
|
+
* Telegram gives a callback 64 bytes, and an answer in text (encoded, a Cyrillic letter is twelve
|
|
319
|
+
* bytes) may not fit, so the button carries the place and the record of the message carries the
|
|
320
|
+
* choices.
|
|
321
|
+
*/
|
|
322
|
+
export function answerCallback(index: number): string {
|
|
323
|
+
return `answer:${String(index)}`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The place of the answer a callback carries, or undefined when it carries none. */
|
|
327
|
+
export function parseCallback(data: string | undefined): { index: number } | undefined {
|
|
328
|
+
const match = data === undefined ? null : /^answer:(\d+)$/.exec(data);
|
|
329
|
+
if (match === null) return undefined;
|
|
330
|
+
return { index: Number(match[1]) };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** The keyboard of a question: the answers the owner may choose. */
|
|
334
|
+
export function keyboardFor(answers: string[]): InlineKeyboard {
|
|
335
|
+
return {
|
|
336
|
+
inline_keyboard: answers.map((answer, index) => [{ text: answer, callback_data: answerCallback(index) }]),
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The part that talks to Telegram and writes what it says.
|
|
342
|
+
*
|
|
343
|
+
* It keeps no list of what waits: the requests module holds that, and the journal is its truth.
|
|
344
|
+
*/
|
|
345
|
+
export class TelegramService {
|
|
346
|
+
private readonly bot: Bot;
|
|
347
|
+
private readonly owner: ChatId;
|
|
348
|
+
private readonly pollTimeout: number;
|
|
349
|
+
private readonly retryDelay: number;
|
|
350
|
+
private readonly hooks: TelegramHooks;
|
|
351
|
+
readonly botId: string;
|
|
352
|
+
private readonly offsetTtl: number;
|
|
353
|
+
private emit: ServiceContext["emit"] | undefined;
|
|
354
|
+
private now: ServiceContext["now"] | undefined;
|
|
355
|
+
private journal: JournalReader | undefined;
|
|
356
|
+
private offset = 0;
|
|
357
|
+
/** The run of update ids the offset belongs to. */
|
|
358
|
+
private epoch = 0;
|
|
359
|
+
/** When the last update was handled, or the run began. */
|
|
360
|
+
private lastActivity = 0;
|
|
361
|
+
|
|
362
|
+
constructor(opts: TelegramOptions, hooks: TelegramHooks) {
|
|
363
|
+
this.bot =
|
|
364
|
+
opts.bot ??
|
|
365
|
+
createBot({ token: opts.token, ...(opts.apiBase === undefined ? {} : { apiBase: opts.apiBase }) });
|
|
366
|
+
this.owner = opts.owner;
|
|
367
|
+
this.botId = botIdOf(opts.token);
|
|
368
|
+
this.offsetTtl = opts.offsetTtl ?? DAY_MS;
|
|
369
|
+
this.pollTimeout = opts.pollTimeout ?? 25;
|
|
370
|
+
this.retryDelay = opts.retryDelay ?? 250;
|
|
371
|
+
this.hooks = hooks;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
get client(): Bot {
|
|
375
|
+
return this.bot;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Start polling. The offset continues after the newest update of this bot the journal holds, as
|
|
380
|
+
* long as that update is recent; the returned function stops the loop and the poll in flight.
|
|
381
|
+
*/
|
|
382
|
+
start(ctx: ServiceContext, journal: JournalReader | undefined): () => void {
|
|
383
|
+
this.emit = ctx.emit;
|
|
384
|
+
this.now = () => ctx.now();
|
|
385
|
+
this.journal = journal;
|
|
386
|
+
this.newRun();
|
|
387
|
+
if (journal !== undefined) {
|
|
388
|
+
const mine = journal
|
|
389
|
+
.since(0 as never, OFFSET_TYPES.map((type) => type.name))
|
|
390
|
+
.filter((stored) => fromPoller(stored) && (stored.data as { bot?: string }).bot === this.botId);
|
|
391
|
+
const newest = mine.at(-1);
|
|
392
|
+
if (newest !== undefined && ctx.now() - newest.at <= this.offsetTtl) {
|
|
393
|
+
const epoch = (newest.data as { epoch: number }).epoch;
|
|
394
|
+
const known = mine.filter((stored) => (stored.data as { epoch: number }).epoch === epoch);
|
|
395
|
+
this.epoch = epoch;
|
|
396
|
+
this.lastActivity = newest.at;
|
|
397
|
+
this.offset = Math.max(...known.map((stored) => (stored.data as { update: number }).update + 1));
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const abort = new AbortController();
|
|
401
|
+
void this.poll(abort.signal);
|
|
402
|
+
return () => {
|
|
403
|
+
abort.abort();
|
|
404
|
+
this.emit = undefined;
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Begin a run of update ids: nothing is known of them, so Telegram is asked from the first it holds. */
|
|
409
|
+
private newRun(): void {
|
|
410
|
+
const moment = this.now?.() ?? 0;
|
|
411
|
+
this.epoch = moment;
|
|
412
|
+
this.lastActivity = moment;
|
|
413
|
+
this.offset = 0;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** Drop an offset nobody has used for so long that Telegram may have numbered anew. */
|
|
417
|
+
private expire(): void {
|
|
418
|
+
if (this.offset !== 0 && this.now !== undefined && this.now() - this.lastActivity > this.offsetTtl) this.newRun();
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
private get source(): UpdateSource {
|
|
422
|
+
return { bot: this.botId, epoch: this.epoch };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private async poll(signal: AbortSignal): Promise<void> {
|
|
426
|
+
while (!signal.aborted) {
|
|
427
|
+
try {
|
|
428
|
+
this.expire();
|
|
429
|
+
const updates = await this.bot.getUpdates(this.offset, this.pollTimeout, signal);
|
|
430
|
+
for (const update of updates) {
|
|
431
|
+
// Below the offset is an update already handled: Telegram may hand it out again.
|
|
432
|
+
if (update.update_id < this.offset) continue;
|
|
433
|
+
await this.handle(update);
|
|
434
|
+
this.offset = update.update_id + 1;
|
|
435
|
+
this.lastActivity = this.now?.() ?? this.lastActivity;
|
|
436
|
+
}
|
|
437
|
+
} catch (error) {
|
|
438
|
+
if (signal.aborted) return;
|
|
439
|
+
console.error(`niwa: telegram: ${error instanceof Error ? error.message : String(error)}`);
|
|
440
|
+
await Bun.sleep(this.retryDelay);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** One update: a message, a press of a button, or something from a chat that is not the owner's. */
|
|
446
|
+
async handle(update: Update): Promise<void> {
|
|
447
|
+
if (update.callback_query !== undefined) {
|
|
448
|
+
await this.handleCallback(update.update_id, update.callback_query);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const message = update.message;
|
|
452
|
+
if (message === undefined) return;
|
|
453
|
+
|
|
454
|
+
// Who is speaking is the chat and the sender of the update, never anything the text says.
|
|
455
|
+
if (!this.isOwner(message.chat, message.from)) {
|
|
456
|
+
await this.write(
|
|
457
|
+
Ignored,
|
|
458
|
+
{ ...this.source, update: update.update_id, chat: message.chat.id, message: message.message_id },
|
|
459
|
+
ignoredId(this.source, update.update_id),
|
|
460
|
+
);
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const text = message.text ?? "";
|
|
465
|
+
await this.write(
|
|
466
|
+
Received,
|
|
467
|
+
{
|
|
468
|
+
...this.source,
|
|
469
|
+
update: update.update_id,
|
|
470
|
+
chat: message.chat.id,
|
|
471
|
+
message: message.message_id,
|
|
472
|
+
text,
|
|
473
|
+
...(message.from?.username === undefined ? {} : { from: message.from.username }),
|
|
474
|
+
...(message.reply_to_message === undefined ? {} : { reply: message.reply_to_message.message_id }),
|
|
475
|
+
},
|
|
476
|
+
receivedId(this.source, update.update_id),
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Whether the update comes from the owner: the owner's private chat, and the owner in it.
|
|
482
|
+
*
|
|
483
|
+
* A private chat has the id of the one who writes in it, so both must say the owner. A group
|
|
484
|
+
* that happens to be configured, or a message forwarded into one, is not the owner: the people
|
|
485
|
+
* in a group are not the owner, whatever the chat id.
|
|
486
|
+
*/
|
|
487
|
+
private isOwner(chat: { readonly id: ChatId; readonly type: string }, from: { readonly id: UserId } | undefined): boolean {
|
|
488
|
+
return chat.type === "private" && chat.id === this.owner && from !== undefined && (from.id as number) === (this.owner as number);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** A button was pressed: it is written down, and a handler makes it the owner's answer to the request the message shows. */
|
|
492
|
+
private async handleCallback(
|
|
493
|
+
update: UpdateId,
|
|
494
|
+
query: NonNullable<Update["callback_query"]>,
|
|
495
|
+
): Promise<void> {
|
|
496
|
+
const message = query.message;
|
|
497
|
+
if (message === undefined) return;
|
|
498
|
+
// The chat of the message and the one who pressed decide: a press of another is noted, never
|
|
499
|
+
// obeyed. (A message id is only unique within its chat, so it is not looked up before this check.)
|
|
500
|
+
if (!this.isOwner(message.chat, query.from)) {
|
|
501
|
+
await this.write(
|
|
502
|
+
Ignored,
|
|
503
|
+
{ ...this.source, update, chat: message.chat.id, message: message.message_id },
|
|
504
|
+
ignoredId(this.source, update),
|
|
505
|
+
);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
// The press is written down as it came, and the offset passes it only after that. What it
|
|
509
|
+
// answers is looked up by a handler, which may take as long as it must.
|
|
510
|
+
await this.write(
|
|
511
|
+
Pressed,
|
|
512
|
+
{
|
|
513
|
+
...this.source,
|
|
514
|
+
update,
|
|
515
|
+
chat: message.chat.id,
|
|
516
|
+
message: message.message_id,
|
|
517
|
+
query: query.id,
|
|
518
|
+
data: query.data ?? "",
|
|
519
|
+
},
|
|
520
|
+
pressedId(this.source, update),
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private async write<T>(type: RecordType<T>, data: T, id?: string): Promise<void> {
|
|
525
|
+
if (this.emit === undefined) throw new Error("the telegram service is not running");
|
|
526
|
+
await this.emit(type, data, id === undefined ? undefined : { id });
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** The input of the action that sends a message. */
|
|
531
|
+
const SendInput = z.object({ text: z.string(), replyTo: messageSchema.optional() });
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* The action that sends a message to the owner's chat.
|
|
535
|
+
*
|
|
536
|
+
* The message is plain text: the buttons of a message answer a request, and a request is posted by
|
|
537
|
+
* `telegram.post-request`, which also writes down which request the message shows.
|
|
538
|
+
*
|
|
539
|
+
* A send is not idempotent and Telegram takes no key: a call that was cut off may have been
|
|
540
|
+
* delivered, so it is not repeated.
|
|
541
|
+
*/
|
|
542
|
+
export function telegramSend(opts: {
|
|
543
|
+
bot: Bot;
|
|
544
|
+
owner: ChatId;
|
|
545
|
+
}): Action<z.infer<typeof SendInput>, { messageId: MessageId; chat: ChatId }, z.input<typeof SendInput>> {
|
|
546
|
+
return action(TELEGRAM_SEND, {
|
|
547
|
+
description: "Send a text message to the owner's Telegram chat.",
|
|
548
|
+
input: SendInput,
|
|
549
|
+
output: z.object({ messageId: messageSchema, chat: chatSchema }),
|
|
550
|
+
recovery: "do-not-repeat",
|
|
551
|
+
effect: "write",
|
|
552
|
+
world: "external",
|
|
553
|
+
run: async (input) => {
|
|
554
|
+
if (input.text.length === 0 || (input.text.length > MESSAGE_LIMIT && [...input.text].length > MESSAGE_LIMIT)) throw new NotSent("Telegram text must contain 1 to 4096 characters");
|
|
555
|
+
const sent = await opts.bot.sendMessage(opts.owner, input.text, undefined, input.replyTo);
|
|
556
|
+
return { messageId: sent.message_id, chat: opts.owner };
|
|
557
|
+
},
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** The plugin of the Telegram surface, with the service it runs. */
|
|
562
|
+
export interface TelegramPlugin extends Plugin {
|
|
563
|
+
readonly service: TelegramService;
|
|
564
|
+
/**
|
|
565
|
+
* The binding of this instance, for the composition to give the requests module.
|
|
566
|
+
*
|
|
567
|
+
* The requests module binds a caller to an address by the transport, never by a payload.
|
|
568
|
+
* With `speaksFor` the handlers of this surface are the owner, so a press of a button in the
|
|
569
|
+
* owner's chat is the owner's answer and nobody else's. Without it they are a plain client,
|
|
570
|
+
* which may not answer for the owner. Every other caller is bound by `fallback`, the default
|
|
571
|
+
* binding of the messages module unless the composition gives its own.
|
|
572
|
+
*/
|
|
573
|
+
bind(fallback?: CallerBinding): CallerBinding;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** The plugin of the Telegram surface. The service polls while the host serves. */
|
|
577
|
+
export function telegram(opts: TelegramOptions, hooks: TelegramHooks = {}): TelegramPlugin {
|
|
578
|
+
// Only a private chat is the owner's, and its id is a positive number: the id of a group is
|
|
579
|
+
// negative, and a surface told to speak for the owner in one would speak for everyone in it.
|
|
580
|
+
if (!Number.isSafeInteger(opts.owner) || opts.owner <= 0) {
|
|
581
|
+
throw new Error(`the owner of the telegram surface must be a private chat, whose id is positive: got ${String(opts.owner)}`);
|
|
582
|
+
}
|
|
583
|
+
if (opts.agent !== undefined && (opts.speaksFor !== "owner" || hooks.toAgent !== undefined)) {
|
|
584
|
+
throw new Error("A Telegram agent conversation requires an owner binding and a single delivery target");
|
|
585
|
+
}
|
|
586
|
+
const service = new TelegramService(opts, hooks);
|
|
587
|
+
const send = telegramSend({ bot: service.client, owner: opts.owner });
|
|
588
|
+
|
|
589
|
+
const acknowledge = action(TELEGRAM_ACKNOWLEDGE, {
|
|
590
|
+
description: "Tell Telegram that a press of a button was seen, with a word for the one who pressed it.",
|
|
591
|
+
input: z.object({ query: z.string(), text: z.string().max(200).optional() }),
|
|
592
|
+
output: z.object({}),
|
|
593
|
+
recovery: "do-not-repeat",
|
|
594
|
+
effect: "write",
|
|
595
|
+
world: "external",
|
|
596
|
+
run: async (input) => {
|
|
597
|
+
await service.client.answerCallbackQuery(input.query, input.text);
|
|
598
|
+
return {};
|
|
599
|
+
},
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
const toAgent = hooks.toAgent;
|
|
603
|
+
const deliver = action(TELEGRAM_TO_AGENT, {
|
|
604
|
+
description: "Hand a message of the owner's chat to the owner's main agent.",
|
|
605
|
+
input: z.object({ text: z.string() }),
|
|
606
|
+
output: z.object({}),
|
|
607
|
+
recovery: "do-not-repeat",
|
|
608
|
+
effect: "write",
|
|
609
|
+
world: "local",
|
|
610
|
+
run: async (input, ctx) => {
|
|
611
|
+
const outcome = await toAgent?.(input.text, ctx);
|
|
612
|
+
if (outcome === undefined || outcome.status === "completed") return {};
|
|
613
|
+
// The outcome of the call says whether the agent may have the message, and so does the
|
|
614
|
+
// outcome of this action: it is what the owner is told.
|
|
615
|
+
switch (outcome.status) {
|
|
616
|
+
case "denied":
|
|
617
|
+
case "cancelled":
|
|
618
|
+
throw new NotSent(outcome.reason);
|
|
619
|
+
case "failed":
|
|
620
|
+
throw outcome.effectPossible ? new Error(outcome.error) : new NotSent(outcome.error);
|
|
621
|
+
case "unknown":
|
|
622
|
+
throw new Error("it is not known whether the agent took the message");
|
|
623
|
+
}
|
|
624
|
+
},
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
/** The journal, when the host gives the plugin one: the requests are read from it. */
|
|
628
|
+
let journal: (() => JournalReader | undefined) | undefined;
|
|
629
|
+
|
|
630
|
+
/** Post a request addressed to the owner: what it asks, as the message and the buttons that answer it. */
|
|
631
|
+
const postRequest = action(TELEGRAM_POST_REQUEST, {
|
|
632
|
+
description: "Show an open request addressed to the owner in the owner's Telegram chat.",
|
|
633
|
+
input: z.object({ request: RequestId }),
|
|
634
|
+
output: z.object({ messageId: messageSchema, chat: chatSchema }),
|
|
635
|
+
recovery: "do-not-repeat",
|
|
636
|
+
effect: "write",
|
|
637
|
+
world: "external",
|
|
638
|
+
run: async (input, ctx) => {
|
|
639
|
+
const reader = journal?.();
|
|
640
|
+
const created = reader === undefined ? undefined : createdOf(reader, input.request);
|
|
641
|
+
if (created === undefined) throw new NotSent(`there is no request "${input.request}"`);
|
|
642
|
+
if (created.to.kind !== "owner") throw new NotSent(`the request "${input.request}" is not addressed to the owner`);
|
|
643
|
+
if (reader !== undefined && endedIn(reader, input.request)) throw new NotSent(`the request "${input.request}" is ended`);
|
|
644
|
+
const options = optionsOf(created.input);
|
|
645
|
+
const shown = render(created);
|
|
646
|
+
const sent = await service.client.sendMessage(opts.owner, shown.text, shown.keyboard);
|
|
647
|
+
await ctx.emit(Posted, {
|
|
648
|
+
bot: service.botId,
|
|
649
|
+
request: created.id,
|
|
650
|
+
chat: opts.owner,
|
|
651
|
+
message: sent.message_id,
|
|
652
|
+
question: created.question,
|
|
653
|
+
kind: created.input.kind,
|
|
654
|
+
allowOther: "allowOther" in created.input && created.input.allowOther,
|
|
655
|
+
choices: options.map((option) => option.id),
|
|
656
|
+
});
|
|
657
|
+
return { messageId: sent.message_id, chat: opts.owner };
|
|
658
|
+
},
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
const built = plugin(PLUGIN_NAME, (api: PluginApi) => {
|
|
662
|
+
journal = () => api.journal?.();
|
|
663
|
+
api.declare(Received, Ignored, Posted, Pressed, TelegramReplyDelivery);
|
|
664
|
+
if (opts.agent !== undefined) {
|
|
665
|
+
api.needs({ actions: [agentTell], types: [AgentTurnQueued, AgentTurnFailed, AgentTurnReplied] });
|
|
666
|
+
api.on(AgentTurnFailed, { id: "inbox-failure", from: "start" }, async (failed, step, record) => {
|
|
667
|
+
if (!providerWrote(record, "agents") || failed.agent !== opts.agent) return;
|
|
668
|
+
const row = api.journal?.()?.find({ type: AgentTurnQueued.name, field: "turn", equals: failed.turn }).find((row) => providerWrote(row, "agents"));
|
|
669
|
+
const route = AgentTurnQueued.schema.safeParse(row?.data).data?.replyTo;
|
|
670
|
+
if (route?.channel !== "telegram" || route.bot !== service.botId || route.chat !== opts.owner) return;
|
|
671
|
+
const status = failed.status === "unsent" ? "The agent did not receive this message" : "Delivery to the agent is uncertain";
|
|
672
|
+
await step.outcome(send, { text: fit(`${status}: ${failed.reason}`), replyTo: messageSchema.parse(route.message) });
|
|
673
|
+
});
|
|
674
|
+
api.on(AgentTurnReplied, { id: "reply", from: "start", concurrency: Number.POSITIVE_INFINITY }, async (reply, step, record) => {
|
|
675
|
+
if (!providerWrote(record, "agents")) return;
|
|
676
|
+
const route = reply.replyTo;
|
|
677
|
+
if (reply.agent !== opts.agent || route.channel !== "telegram" || route.bot !== service.botId || route.chat !== opts.owner) return;
|
|
678
|
+
const replyTo = messageSchema.parse(route.message);
|
|
679
|
+
const destination = { turn: reply.turn, bot: route.bot, chat: opts.owner, replyTo };
|
|
680
|
+
let sentParts = 0;
|
|
681
|
+
for (const text of telegramParts(reply.text)) {
|
|
682
|
+
const outcome = await step.outcome(send, { text, replyTo }, { key: `part-${sentParts}` });
|
|
683
|
+
if (outcome.status !== "completed") {
|
|
684
|
+
await step.emit(TelegramReplyDelivery, { ...destination, sentParts, status: mayHaveArrived(outcome) ? "possibly-sent" : "unsent", reason: reasonOf(outcome) });
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
sentParts++;
|
|
688
|
+
}
|
|
689
|
+
await step.emit(TelegramReplyDelivery, { ...destination, sentParts, status: "sent" });
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
api.action(send);
|
|
693
|
+
api.action(postRequest);
|
|
694
|
+
api.action(acknowledge);
|
|
695
|
+
// Without a hook nothing is delivered, so no action says that something was.
|
|
696
|
+
if (toAgent !== undefined) api.action(deliver);
|
|
697
|
+
|
|
698
|
+
// The poll loop only records. Delivery is a step of this handler, so it never holds up the
|
|
699
|
+
// messages after it. A delivery that failed, or was cut off by a restart, is never resent by
|
|
700
|
+
// itself: the owner is asked, and only his "retry" delivers again.
|
|
701
|
+
// A message the agent cannot take waits for the owner's word: the messages after it do not.
|
|
702
|
+
api.on(Received, { id: "agent", concurrency: Number.POSITIVE_INFINITY }, async (data, step, record) => {
|
|
703
|
+
if (!fromPoller(record) || data.bot !== service.botId || data.chat !== opts.owner || data.text.trim() === "") return;
|
|
704
|
+
// A reply to the message that shows a request answers it: it is the owner's answer, not a
|
|
705
|
+
// word to the agent.
|
|
706
|
+
const shown =
|
|
707
|
+
data.reply === undefined ? undefined : await postedFor(api, { bot: data.bot, chat: data.chat, message: data.reply }, 0);
|
|
708
|
+
if (shown !== undefined) {
|
|
709
|
+
const read = answerFromReply(shown, data.text);
|
|
710
|
+
if ("problem" in read) return void (await step.outcome(send, { text: fit(read.problem) }));
|
|
711
|
+
const outcome = await step.outcome(REQUEST_ANSWER, { id: shown.request, answer: read.answer });
|
|
712
|
+
if (outcome.status === "completed") return void (await step.outcome(send, { text: `Answered: ${shown.question}` }));
|
|
713
|
+
const reason = reasonOf(outcome);
|
|
714
|
+
console.error(`niwa: telegram: the request "${shown.request}" was not answered: ${reason}`);
|
|
715
|
+
return void (await step.outcome(send, { text: fit(`Your answer was not accepted: ${reason}`) }));
|
|
716
|
+
}
|
|
717
|
+
const agent = opts.agent;
|
|
718
|
+
if (agent === undefined && toAgent === undefined) return;
|
|
719
|
+
for (;;) {
|
|
720
|
+
const outcome = agent === undefined
|
|
721
|
+
? await step.outcome(deliver, { text: data.text })
|
|
722
|
+
: await step.outcome(agentTell, {
|
|
723
|
+
agent, text: data.text, replyTo: { channel: "telegram", bot: data.bot, chat: data.chat, message: data.message },
|
|
724
|
+
});
|
|
725
|
+
if (outcome.status === "completed") return;
|
|
726
|
+
let answer: Answer;
|
|
727
|
+
try {
|
|
728
|
+
({ answer } = answeredBy(
|
|
729
|
+
await step(requestAsk, { to: { kind: "owner" }, answerPolicy: "owner-only", ...undelivered(data.text, mayHaveArrived(outcome)) }),
|
|
730
|
+
));
|
|
731
|
+
} catch (error) {
|
|
732
|
+
if (error instanceof RequestCancelled) return;
|
|
733
|
+
throw error;
|
|
734
|
+
}
|
|
735
|
+
if (!("ids" in answer) || answer.ids[0] !== RETRY) return;
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
api.service((ctx) => service.start(ctx, api.journal?.()));
|
|
739
|
+
|
|
740
|
+
// A request addressed to the owner is shown to him: a message with the choices as buttons.
|
|
741
|
+
// Each request is posted on its own: a post that fails is reported and leaves the requests
|
|
742
|
+
// after it alone. A new subscription reads from the start, so a request that was open before
|
|
743
|
+
// this surface was installed is posted too; one that is ended or already shown is passed over.
|
|
744
|
+
api.on(RequestCreated, { id: "request", from: "start" }, async (data: Created, step, record) => {
|
|
745
|
+
if (!providerWrote(record, "requests") || data.to.kind !== "owner") return;
|
|
746
|
+
if (ended(api, data.id) || postedTo(api, data.id, service.botId, opts.owner)) return;
|
|
747
|
+
const outcome = await step.outcome(postRequest, { request: data.id });
|
|
748
|
+
if (outcome.status === "completed") return;
|
|
749
|
+
console.error(`niwa: telegram: the request "${data.id}" was not posted: ${reasonOf(outcome)}`);
|
|
750
|
+
});
|
|
751
|
+
|
|
752
|
+
// A press of a button is the owner's answer: the request is answered, and the one who asked
|
|
753
|
+
// goes on. The press says at once what became of it: a toast on the button, and a message
|
|
754
|
+
// when the answer was not taken, so a refusal is never mistaken for an answer. A press on a
|
|
755
|
+
// request that is not open any more is refused, and nothing waits for a decision.
|
|
756
|
+
api.on(Pressed, { id: "press", concurrency: Number.POSITIVE_INFINITY }, async (data, step, record) => {
|
|
757
|
+
if (!fromPoller(record) || data.bot !== service.botId || data.chat !== opts.owner) return;
|
|
758
|
+
const told = async (toast: string, notice?: string): Promise<void> => {
|
|
759
|
+
await step.outcome(acknowledge, { query: data.query, text: toast });
|
|
760
|
+
if (notice !== undefined) await step.outcome(send, { text: fit(notice) });
|
|
761
|
+
};
|
|
762
|
+
const parsed = parseCallback(data.data);
|
|
763
|
+
if (parsed === undefined) return void (await told("Unknown button"));
|
|
764
|
+
const posted = await postedFor(api, { bot: data.bot, chat: data.chat, message: data.message }, POSTED_WAIT_MS);
|
|
765
|
+
const answer = posted?.choices[parsed.index];
|
|
766
|
+
if (posted === undefined || answer === undefined) {
|
|
767
|
+
return void (await told("Not accepted", "That button does not belong to a request that is open here."));
|
|
768
|
+
}
|
|
769
|
+
const outcome = await step.outcome(REQUEST_ANSWER, { id: posted.request, answer: { ids: [OptionIdSchema.parse(answer)] } });
|
|
770
|
+
if (outcome.status === "completed") return void (await told("Answer sent"));
|
|
771
|
+
const reason = reasonOf(outcome);
|
|
772
|
+
console.error(`niwa: telegram: the request "${posted.request}" was not answered: ${reason}`);
|
|
773
|
+
await told("Not accepted", `Your answer was not accepted: ${reason}`);
|
|
774
|
+
});
|
|
775
|
+
});
|
|
776
|
+
const ownerHandlers = new Set([`${PLUGIN_NAME}/agent`, `${PLUGIN_NAME}/press`]);
|
|
777
|
+
const bind = (fallback: CallerBinding = bindingOf()): CallerBinding => {
|
|
778
|
+
return (caller: Caller) => {
|
|
779
|
+
if (caller.kind === "handler" && ownerHandlers.has(caller.handler)) {
|
|
780
|
+
return opts.speaksFor === "owner" ? owner : client(PLUGIN_NAME);
|
|
781
|
+
}
|
|
782
|
+
return fallback(caller);
|
|
783
|
+
};
|
|
784
|
+
};
|
|
785
|
+
return { ...built, service, bind };
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** Whether the request is already ended: an ended request is not one the owner may answer. */
|
|
789
|
+
function ended(api: PluginApi, request: string): boolean {
|
|
790
|
+
const journal = api.journal?.();
|
|
791
|
+
return journal !== undefined && endedIn(journal, request);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function endedIn(journal: JournalReader, request: string): boolean {
|
|
795
|
+
const onlyOwner = createdOf(journal, request)?.answerPolicy === "owner-only";
|
|
796
|
+
return END_TYPES.some((type) => journal.find({ type, field: "id", equals: request }).some((row) =>
|
|
797
|
+
providerWrote(row, "requests") && (!onlyOwner || type !== RequestAnswered.name || operatorAnswered(row))));
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** The request as it was created, when the journal holds it. */
|
|
801
|
+
function createdOf(journal: JournalReader, request: string): Created | undefined {
|
|
802
|
+
const found = journal.find({ type: RequestCreated.name, field: "id", equals: request }).find((row) => providerWrote(row, "requests"));
|
|
803
|
+
if (found === undefined) return undefined;
|
|
804
|
+
const parsed = RequestCreated.schema.safeParse(found.data);
|
|
805
|
+
return parsed.success ? parsed.data : undefined;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** Whether the request is already shown in the chat of the bot: one message of it is enough. */
|
|
809
|
+
function postedTo(api: PluginApi, request: string, bot: string, chat: ChatId): boolean {
|
|
810
|
+
const journal = api.journal?.();
|
|
811
|
+
if (journal === undefined) return false;
|
|
812
|
+
return journal.find({ type: Posted.name, field: "request", equals: request }).some((stored) => {
|
|
813
|
+
const parsed = Posted.schema.safeParse(stored.data);
|
|
814
|
+
return providerWrote(stored, "telegram") && parsed.success && parsed.data.bot === bot && parsed.data.chat === chat;
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** A message of a chat of a bot: a message id alone is not unique. */
|
|
819
|
+
interface MessageAddress {
|
|
820
|
+
readonly bot: string;
|
|
821
|
+
readonly chat: ChatId;
|
|
822
|
+
readonly message: MessageId;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* The request a message shows, when the record of that message is committed.
|
|
827
|
+
*
|
|
828
|
+
* The record is written right after the message is sent, so a press that arrives before it is
|
|
829
|
+
* committed waits for it up to `waitMs`: the owner pressed a button, and the press is not lost.
|
|
830
|
+
*/
|
|
831
|
+
async function postedFor(
|
|
832
|
+
api: PluginApi,
|
|
833
|
+
at: MessageAddress,
|
|
834
|
+
waitMs: number,
|
|
835
|
+
): Promise<z.infer<typeof Posted.schema> | undefined> {
|
|
836
|
+
const deadline = Date.now() + waitMs;
|
|
837
|
+
for (;;) {
|
|
838
|
+
const found = api
|
|
839
|
+
.journal?.()
|
|
840
|
+
?.find({ type: Posted.name, field: "message", equals: at.message })
|
|
841
|
+
.flatMap((stored) => {
|
|
842
|
+
const parsed = Posted.schema.safeParse(stored.data);
|
|
843
|
+
return providerWrote(stored, "telegram") && parsed.success && parsed.data.bot === at.bot && parsed.data.chat === at.chat ? [parsed.data] : [];
|
|
844
|
+
})
|
|
845
|
+
.at(-1);
|
|
846
|
+
if (found !== undefined) return found;
|
|
847
|
+
if (Date.now() >= deadline) return undefined;
|
|
848
|
+
await Bun.sleep(POSTED_POLL_MS);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/** The most a message of Telegram holds, in the units Telegram counts: UTF-16 code units. */
|
|
853
|
+
const MESSAGE_LIMIT = 4096;
|
|
854
|
+
|
|
855
|
+
/** Split long replies without losing text or cutting a surrogate pair. */
|
|
856
|
+
function* telegramParts(text: string): Generator<string> {
|
|
857
|
+
let start = 0;
|
|
858
|
+
while (start < text.length) {
|
|
859
|
+
let end = Math.min(start + MESSAGE_LIMIT, text.length);
|
|
860
|
+
const last = text.charCodeAt(end - 1);
|
|
861
|
+
if (end < text.length && last >= 0xd800 && last <= 0xdbff) end--;
|
|
862
|
+
yield text.slice(start, end);
|
|
863
|
+
start = end;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** The text, cut to fit `room` units, with a note where it was cut. */
|
|
868
|
+
export function fit(text: string, room: number = MESSAGE_LIMIT): string {
|
|
869
|
+
if (text.length <= room) return text;
|
|
870
|
+
const note = "\n[cut]";
|
|
871
|
+
let end = room - note.length;
|
|
872
|
+
// Never between the two halves of a character outside the basic plane.
|
|
873
|
+
const last = text.charCodeAt(end - 1);
|
|
874
|
+
if (last >= 0xd800 && last <= 0xdbff) end -= 1;
|
|
875
|
+
return `${text.slice(0, end)}${note}`;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/** Why a step did not complete, in a few words. */
|
|
879
|
+
function reasonOf(outcome: Exclude<Outcome<unknown>, { status: "completed" }>): string {
|
|
880
|
+
switch (outcome.status) {
|
|
881
|
+
case "denied":
|
|
882
|
+
case "cancelled":
|
|
883
|
+
return outcome.reason;
|
|
884
|
+
case "failed":
|
|
885
|
+
return outcome.error;
|
|
886
|
+
case "unknown":
|
|
887
|
+
return "the outcome is not known";
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** A request as the owner sees it: the message, and the buttons when its answers are buttons. */
|
|
892
|
+
function render(created: Created): { text: string; keyboard?: InlineKeyboard } {
|
|
893
|
+
const asked = created.input;
|
|
894
|
+
const options = optionsOf(asked);
|
|
895
|
+
const other = "allowOther" in asked && asked.allowOther;
|
|
896
|
+
const body = [created.question, ...questionLines(asked)].join("\n");
|
|
897
|
+
let footer: string;
|
|
898
|
+
let keyboard: InlineKeyboard | undefined;
|
|
899
|
+
switch (asked.kind) {
|
|
900
|
+
case "choice":
|
|
901
|
+
case "confirm":
|
|
902
|
+
case "permission":
|
|
903
|
+
keyboard = keyboardFor(options.map((option) => option.label));
|
|
904
|
+
footer = other ? "Or reply to this message with your own answer." : "";
|
|
905
|
+
break;
|
|
906
|
+
case "multi":
|
|
907
|
+
footer = [
|
|
908
|
+
...options.map((option, index) => `${String(index + 1)}. ${option.label}`),
|
|
909
|
+
other
|
|
910
|
+
? "Reply to this message with the numbers of your choices, for example 1, 3, or with your own answer."
|
|
911
|
+
: "Reply to this message with the numbers of your choices, for example 1, 3.",
|
|
912
|
+
].join("\n");
|
|
913
|
+
break;
|
|
914
|
+
case "text":
|
|
915
|
+
footer = "Reply to this message with your answer.";
|
|
916
|
+
break;
|
|
917
|
+
case "form":
|
|
918
|
+
footer = `This asks for a form, which cannot be filled in here: answer request ${created.id} in the cockpit or with the CLI.`;
|
|
919
|
+
break;
|
|
920
|
+
}
|
|
921
|
+
if (footer === "") return { text: fit(body), ...(keyboard === undefined ? {} : { keyboard }) };
|
|
922
|
+
// The footer says how to answer: it stays whole when the question is cut.
|
|
923
|
+
const room = MESSAGE_LIMIT - Math.min(footer.length, MESSAGE_LIMIT / 2) - 1;
|
|
924
|
+
return { text: fit(`${fit(body, room)}\n${footer}`), ...(keyboard === undefined ? {} : { keyboard }) };
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/** What a request is, as the record of its post keeps it. */
|
|
928
|
+
type PostedData = z.infer<typeof Posted.schema>;
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* The answer a reply to a posted request makes, or why it makes none.
|
|
932
|
+
*
|
|
933
|
+
* A text question takes the text. A question with options takes the numbers of the options the
|
|
934
|
+
* message lists (one for a choice, any for a multi), or the text itself when it allows another
|
|
935
|
+
* answer. A form cannot be filled in a chat: the owner is told where to answer it.
|
|
936
|
+
*/
|
|
937
|
+
export function answerFromReply(posted: PostedData, text: string): { answer: Answer } | { problem: string } {
|
|
938
|
+
const said = text.trim();
|
|
939
|
+
switch (posted.kind) {
|
|
940
|
+
case "text":
|
|
941
|
+
return { answer: { text: said } };
|
|
942
|
+
case "form":
|
|
943
|
+
return { problem: `That request is a form, which cannot be filled in here: answer request ${posted.request} in the cockpit or with the CLI.` };
|
|
944
|
+
case "choice":
|
|
945
|
+
case "multi":
|
|
946
|
+
case "confirm":
|
|
947
|
+
case "permission": {
|
|
948
|
+
const count = posted.choices.length;
|
|
949
|
+
if (/^\d+(?:[\s,]+\d+)*$/.test(said)) {
|
|
950
|
+
const places = [...new Set(said.split(/[\s,]+/).map(Number))];
|
|
951
|
+
const ids = places.map((place) => posted.choices[place - 1]);
|
|
952
|
+
const bad = places.find((_, index) => ids[index] === undefined);
|
|
953
|
+
if (bad !== undefined) return { problem: `There is no option ${String(bad)}: reply with a number from 1 to ${String(count)}.` };
|
|
954
|
+
if (posted.kind !== "multi" && ids.length !== 1) return { problem: "Reply with the number of one option." };
|
|
955
|
+
return { answer: { ids: ids.map((id) => OptionIdSchema.parse(id)) } };
|
|
956
|
+
}
|
|
957
|
+
if (posted.allowOther) return { answer: { text: said } };
|
|
958
|
+
return { problem: `Reply with the number of an option, from 1 to ${String(count)}.` };
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
export { createBot, chatId } from "./bot.ts";
|
|
964
|
+
export type { Bot, ChatId, InlineKeyboard, InlineButton, MessageId, Update, UpdateId, UserId } from "./bot.ts";
|