pi-durable-bot 0.8.3 → 0.8.5

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.
@@ -0,0 +1,1337 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createServer } from "node:http";
4
+ import { dirname, join } from "node:path";
5
+ import { Readable } from "node:stream";
6
+ import { setTimeout as sleep } from "node:timers/promises";
7
+ import { TeamsFormatConverter } from "@chat-adapter/teams";
8
+ import { convertEmojiPlaceholders } from "chat";
9
+ import { expandHome, readSecrets } from "../../core/env-file.js";
10
+ import { quietLogger, RouteAdapter, TeamsApp, useSocketConnections } from "./sdk.js";
11
+ /** About 28 KB is the largest message Teams takes (Microsoft Learn: "Send and receive messages"); counted as UTF-8. */
12
+ const MAX_BYTES = 28_000;
13
+ /** Teams' Bot Connector, where a message goes when no event has given its service URL yet. */
14
+ const DEFAULT_SERVICE_URL = "https://smba.trafficmanager.net/teams";
15
+ const GRAPH = "https://graph.microsoft.com/v1.0";
16
+ /** Responses worth trying again, as Microsoft's rate-limit page says: too many requests, and the service busy. */
17
+ const RETRY_STATUS = new Set([412, 429, 502, 503, 504]);
18
+ /** A request is tried again until a try fails a minute or more after the first began, as on Slack. */
19
+ const RETRY_MS = 60_000;
20
+ /** One try of a request, its token included. */
21
+ const REQUEST_TIMEOUT_MS = 30_000;
22
+ /** Where Microsoft 365 Agents Playground sends by default: http://localhost:3978/api/messages. */
23
+ const PLAYGROUND_PORT = 3978;
24
+ const PLAYGROUND_PATH = "/api/messages";
25
+ const MAX_PLAYGROUND_BODY = 1024 * 1024;
26
+ /** Activities that are not stored: nobody needs them. */
27
+ const SKIPPED = new Set(["typing"]);
28
+ /**
29
+ * The reactions Teams lets a bot set, by the emoji and the names people give them. Teams takes other reaction IDs as
30
+ * well (as "<code point>_<name>", for example 1f440_eyes), which pass as they are.
31
+ */
32
+ const REACTIONS = {
33
+ "👍": "like",
34
+ "❤️": "heart",
35
+ "❤": "heart",
36
+ "😆": "laugh",
37
+ "😮": "surprised",
38
+ "😢": "sad",
39
+ "😠": "angry",
40
+ "👀": "1f440_eyes",
41
+ "✅": "2705_whiteheavycheckmark",
42
+ "🚀": "launch",
43
+ "📌": "1f4cc_pushpin",
44
+ };
45
+ const REACTION_NAMES = {
46
+ like: "like",
47
+ thumbsup: "like",
48
+ "+1": "like",
49
+ heart: "heart",
50
+ laugh: "laugh",
51
+ laughing: "laugh",
52
+ surprised: "surprised",
53
+ open_mouth: "surprised",
54
+ sad: "sad",
55
+ cry: "sad",
56
+ angry: "angry",
57
+ eyes: "1f440_eyes",
58
+ white_check_mark: "2705_whiteheavycheckmark",
59
+ rocket: "launch",
60
+ launch: "launch",
61
+ pushpin: "1f4cc_pushpin",
62
+ };
63
+ const REACTION_EMOJI = Object.fromEntries(Object.entries(REACTIONS).filter(([emoji]) => emoji !== "❤").map(([emoji, id]) => [id, emoji]));
64
+ /** Headers that a proxy adds: a request with one came from outside this computer. */
65
+ const PROXY_HEADERS = ["x-forwarded-for", "forwarded", "cf-connecting-ip", "x-real-ip", "tailscale-user-login"];
66
+ /** Chat SDK's Teams converter: Markdown as Teams' Markdown, and Teams' HTML as Markdown. */
67
+ const converter = new TeamsFormatConverter();
68
+ export function createChannel(config, env) {
69
+ const mode = config.mode ?? "socket";
70
+ if (mode !== "socket" && mode !== "http")
71
+ throw new Error(`channel ${config.id}: "mode" must be "socket" (the default) or "http"`);
72
+ const playground = config.playground === true;
73
+ if (config.playground !== undefined && typeof config.playground !== "boolean")
74
+ throw new Error(`channel ${config.id}: "playground" must be true or false`);
75
+ if (playground && mode !== "http")
76
+ throw new Error(`channel ${config.id}: "playground" needs "mode": "http"`);
77
+ if (playground && config.secrets !== undefined)
78
+ throw new Error(`channel ${config.id}: "playground" takes no "secrets": it is only for Agents Playground on this computer, never with a real app`);
79
+ if (!playground && config.port !== undefined)
80
+ throw new Error(`channel ${config.id}: "port" is only for "playground"`);
81
+ if (config.port !== undefined && !(Number.isInteger(config.port) && config.port >= 0 && config.port < 65536))
82
+ throw new Error(`channel ${config.id}: "port" must be a port number`);
83
+ if (!playground && typeof config.secrets !== "string")
84
+ throw new Error(`channel ${config.id}: "secrets" must name the env file with CLIENT_ID, CLIENT_SECRET and TENANT_ID`);
85
+ return new TeamsChannel(config.id, { ...(typeof config.secrets === "string" ? { secrets: expandHome(config.secrets) } : {}), mode, playground, ...(typeof config.port === "number" ? { port: config.port } : {}) }, env);
86
+ }
87
+ export class TeamsChannel {
88
+ id;
89
+ #options;
90
+ #env;
91
+ #endpoints;
92
+ #graph;
93
+ #stateFile;
94
+ #state;
95
+ #app;
96
+ #sink;
97
+ #route;
98
+ /** Playground mode's own server, on 127.0.0.1. */
99
+ #playground;
100
+ #clientId;
101
+ #tenantId;
102
+ /** The bot's Teams ID, 28:<client ID>. */
103
+ #botId;
104
+ /** Activities are stored one after another, in the order they came. */
105
+ #storing = Promise.resolve();
106
+ #refilling = Promise.resolve();
107
+ /** The backfills that run: stop waits for them. */
108
+ #backfills = new Set();
109
+ /** Aborted by stop: requests, their waits and the backfill end. */
110
+ #stopping = new AbortController();
111
+ /** When each region's socket dropped, in Unix ms: where the backfill after its reconnect starts. */
112
+ #droppedAt = new Map();
113
+ /** Where the backfill starts in each known place, by conversation: read before the channel connects. */
114
+ #starts = new Map();
115
+ /** The token being got, for each kind, and when it began. */
116
+ #tokens = new Map();
117
+ constructor(id, options, env, endpoints = {}) {
118
+ this.id = id;
119
+ this.#options = options;
120
+ this.#env = env;
121
+ this.#endpoints = endpoints;
122
+ this.#graph = endpoints.graph ?? GRAPH;
123
+ // What playground mode learns comes from requests nobody signed: never mixed with a real app's.
124
+ this.#stateFile = join(env.botDir, "channels", options.playground ? `${id}.playground.json` : `${id}.json`);
125
+ this.#state = readState(this.#stateFile);
126
+ }
127
+ get me() {
128
+ return this.#botId ? { address: this.person(this.#botId), name: this.#env.botName } : undefined;
129
+ }
130
+ /** The path Teams posts to in HTTP mode, once started. */
131
+ get path() {
132
+ return this.#route?.path;
133
+ }
134
+ /** Where Agents Playground posts to in playground mode, once started. */
135
+ get playgroundUrl() {
136
+ return this.#playground?.url;
137
+ }
138
+ // ---- Connect ----
139
+ /**
140
+ * Connect: in Socket Mode, open the sockets (the SDK keeps them open and reconnects by itself); in HTTP mode, serve
141
+ * the channel's path on the page server; in playground mode, serve Agents Playground on 127.0.0.1. Every activity is
142
+ * stored before Teams gets its answer.
143
+ */
144
+ async start(sink) {
145
+ const { mode, playground } = this.#options;
146
+ if (playground && this.#options.secrets)
147
+ throw new Error(`channel ${this.id}: playground mode takes no secrets`);
148
+ this.#stopping = new AbortController();
149
+ this.#droppedAt.clear();
150
+ const secrets = this.#options.secrets ? readSecrets(this.#options.secrets, ["CLIENT_ID", "CLIENT_SECRET", "TENANT_ID"]) : undefined;
151
+ this.#clientId = secrets?.CLIENT_ID;
152
+ this.#tenantId = secrets?.TENANT_ID;
153
+ if (this.#clientId)
154
+ this.#botId = `28:${this.#clientId}`;
155
+ this.#sink = sink;
156
+ this.#starts = new Map();
157
+ for (const place of await sink.places()) {
158
+ const parsed = this.#tryParse(place);
159
+ if (!parsed || !("conversation" in parsed))
160
+ continue;
161
+ const newest = await sink.newestMessage(place);
162
+ const message = newest ? this.#tryParse(newest) : undefined;
163
+ const at = message && "message" in message ? messageTime(message.message) : undefined;
164
+ if (at !== undefined)
165
+ this.#starts.set(parsed.conversation, at);
166
+ }
167
+ const app = new TeamsApp((activity) => this.#receive(sink, activity), {
168
+ // A test's token, in place of the secret: the SDK would sign in with a secret first.
169
+ ...(secrets ? { clientId: secrets.CLIENT_ID, tenantId: secrets.TENANT_ID, ...(this.#endpoints.token ? { token: this.#endpoints.token } : { clientSecret: secrets.CLIENT_SECRET }) } : {}),
170
+ logger: quietLogger(sink.log),
171
+ serviceUrl: this.#endpoints.serviceUrl ?? DEFAULT_SERVICE_URL,
172
+ ...(mode === "socket" ? { socketMode: true } : { httpServerAdapter: new RouteAdapter(), dangerouslyAllowUnauthenticatedRequests: playground }),
173
+ });
174
+ this.#app = app;
175
+ if (mode === "socket") {
176
+ if (this.#endpoints.socket)
177
+ useSocketConnections(app, this.#endpoints.socket);
178
+ // Each region has its own socket, which drops and comes back on its own.
179
+ app.socketMode?.events.on("disconnected", ({ geo, error, terminal }) => {
180
+ if (!this.#droppedAt.has(geo))
181
+ this.#droppedAt.set(geo, Date.now());
182
+ sink.log(terminal ? "Teams refused the socket, and it will not reconnect" : "socket dropped", { region: geo, ...(error ? { error: error.message } : {}) });
183
+ });
184
+ app.socketMode?.events.on("reconnected", ({ geo }) => {
185
+ // Teams is not known to keep events while a socket is down: read what came meanwhile, from a minute before the drop.
186
+ const since = (this.#droppedAt.get(geo) ?? Date.now()) - 60_000;
187
+ this.#droppedAt.delete(geo);
188
+ sink.log("socket reconnected", { region: geo });
189
+ this.#recover(sink, () => since).catch((error) => sink.log("backfill failed", { error: String(error) }));
190
+ });
191
+ try {
192
+ await app.start();
193
+ }
194
+ catch (error) {
195
+ throw new Error(`Teams did not open the socket (Socket Mode): ${errorText(error)}. If the app was made without Socket Mode, set "mode": "http" (the teams-channel skill says how).`, { cause: error });
196
+ }
197
+ return;
198
+ }
199
+ await app.initialize();
200
+ const adapter = app.server.adapter;
201
+ if (playground) {
202
+ this.#playground = await this.#servePlayground(adapter);
203
+ sink.log("taking Agents Playground requests, only from this computer", { endpoint: this.#playground.url });
204
+ return;
205
+ }
206
+ const http = this.#env.http;
207
+ if (!http)
208
+ throw new Error(`channel ${this.id}: HTTP mode needs Pots' page server`);
209
+ this.#route = http.serve((request) => this.#request(request, adapter));
210
+ const base = http.publicUrl();
211
+ sink.log("taking Teams requests", {
212
+ path: this.#route.path,
213
+ ...(base ? { endpoint: `${base.replace(/\/+$/, "")}${this.#route.path}` } : { problem: "settings.json has no publicUrl, so Teams cannot reach this computer" }),
214
+ });
215
+ }
216
+ /**
217
+ * Take no more activities, end the requests and backfills that run, and wait for them and for the activities already
218
+ * taken to be stored.
219
+ */
220
+ async stop() {
221
+ this.#stopping.abort(new Error(`channel ${this.id} stopped`));
222
+ this.#route?.close();
223
+ this.#route = undefined;
224
+ const playground = this.#playground;
225
+ this.#playground = undefined;
226
+ if (playground) {
227
+ playground.server.closeAllConnections();
228
+ await new Promise((resolve) => playground.server.close(() => resolve()));
229
+ }
230
+ const app = this.#app;
231
+ this.#app = undefined;
232
+ this.#tokens.clear();
233
+ await app?.stop().catch(() => { });
234
+ await Promise.allSettled([...this.#backfills]);
235
+ await this.#storing.catch(() => { });
236
+ }
237
+ /** Keep a backfill until it ends, for stop. */
238
+ #track(work) {
239
+ this.#backfills.add(work);
240
+ void work.finally(() => this.#backfills.delete(work)).catch(() => { });
241
+ return work;
242
+ }
243
+ /**
244
+ * Playground mode's server: the playground port on 127.0.0.1, which nothing outside this computer reaches. A request
245
+ * must name this computer as its host (a page that points a name of its own at 127.0.0.1 cannot send), come from no
246
+ * proxy and no browser page, and be JSON.
247
+ */
248
+ async #servePlayground(adapter) {
249
+ const server = createServer((incoming, response) => {
250
+ void this.#playgroundRequest(incoming, adapter).then((answer) => {
251
+ response.writeHead(answer.status, { "content-type": "application/json", "cache-control": "no-store" });
252
+ response.end(answer.body === undefined ? undefined : JSON.stringify(answer.body));
253
+ }, () => {
254
+ response.writeHead(500).end();
255
+ });
256
+ });
257
+ await new Promise((resolve, reject) => {
258
+ server.once("error", reject);
259
+ server.listen(this.#options.port ?? PLAYGROUND_PORT, "127.0.0.1", () => {
260
+ server.off("error", reject);
261
+ resolve();
262
+ });
263
+ });
264
+ const { port } = server.address();
265
+ return { server, url: `http://127.0.0.1:${port}${PLAYGROUND_PATH}` };
266
+ }
267
+ async #playgroundRequest(incoming, adapter) {
268
+ const refuse = (status, error) => {
269
+ incoming.resume();
270
+ return { status, body: { error } };
271
+ };
272
+ if ((incoming.url ?? "").split("?")[0] !== PLAYGROUND_PATH)
273
+ return refuse(404, "not found");
274
+ const host = (incoming.headers.host ?? "").replace(/:\d+$/, "").toLowerCase();
275
+ const local = host === "127.0.0.1" || host === "localhost" || host === "[::1]";
276
+ if (!local || PROXY_HEADERS.some((name) => incoming.headers[name] !== undefined) || incoming.headers.origin !== undefined) {
277
+ return refuse(403, "playground mode takes requests only from this computer");
278
+ }
279
+ if (!/^application\/json\b/i.test(incoming.headers["content-type"] ?? ""))
280
+ return refuse(415, "send JSON");
281
+ const chunks = [];
282
+ let size = 0;
283
+ for await (const chunk of incoming) {
284
+ size += chunk.length;
285
+ if (size > MAX_PLAYGROUND_BODY)
286
+ return { status: 413, body: { error: "too large" } };
287
+ chunks.push(chunk);
288
+ }
289
+ return this.#request({ method: incoming.method ?? "GET", headers: incoming.headers, body: Buffer.concat(chunks) }, adapter);
290
+ }
291
+ /**
292
+ * A request in HTTP mode, from the page server or (in playground mode) the channel's own server: the SDK checks
293
+ * Microsoft's signature, except in playground mode, then #receive runs.
294
+ */
295
+ async #request(request, adapter) {
296
+ if (request.method !== "POST")
297
+ return { status: 405, body: { error: "Use POST." } };
298
+ let body;
299
+ try {
300
+ body = JSON.parse(request.body.toString("utf8"));
301
+ }
302
+ catch {
303
+ return { status: 400, body: { error: "not JSON" } };
304
+ }
305
+ if (!adapter.handler)
306
+ return { status: 503, body: { error: "not ready" } };
307
+ const headers = Object.fromEntries(Object.entries(request.headers).filter((entry) => entry[1] !== undefined));
308
+ const answer = await adapter.handler({ body, headers });
309
+ return { status: answer.status, ...(answer.body !== undefined ? { body: answer.body } : {}) };
310
+ }
311
+ /**
312
+ * One activity from Teams: learn what sending and Graph need from it, store it, then answer. A store that fails
313
+ * throws, and Teams gets an error. A click on a card (an invoke) gets "OK" as soon as it is stored; the bot changes
314
+ * the card later.
315
+ */
316
+ async #receive(sink, activity) {
317
+ if (SKIPPED.has(activity.type))
318
+ return { status: 200 };
319
+ this.#learn(activity);
320
+ const eventId = activityEventId(activity);
321
+ const stored = this.#storing.then(() => sink.receive(eventId, { source: "activity", at: Date.now(), activity }));
322
+ this.#storing = stored.catch(() => { });
323
+ try {
324
+ await stored;
325
+ }
326
+ catch (error) {
327
+ sink.log("activity not stored; Teams gets an error", { event: eventId, error: String(error) });
328
+ throw error;
329
+ }
330
+ if (activity.type === "invoke" && activity.name === "adaptiveCard/action") {
331
+ return { status: 200, body: { statusCode: 200, type: "application/vnd.microsoft.activity.message", value: "OK" } };
332
+ }
333
+ return { status: 200 };
334
+ }
335
+ /** What an activity tells about its conversation and its people, kept for sending, names and Graph. */
336
+ #learn(activity) {
337
+ const before = JSON.stringify(this.#state);
338
+ const recipient = activity.recipient;
339
+ // Teams gives the bot's ID as 28:<client ID>; Agents Playground gives an ID of its own.
340
+ if (!this.#botId && recipient?.id && (recipient.id.startsWith("28:") || this.#options.playground))
341
+ this.#botId = recipient.id;
342
+ const where = whereOf(activity);
343
+ if (where) {
344
+ const conversation = (this.#state.conversations[where.conversation] ??= {});
345
+ const data = activity.channelData ?? {};
346
+ if (activity.conversation?.conversationType)
347
+ conversation.type = activity.conversation.conversationType;
348
+ if (typeof activity.serviceUrl === "string")
349
+ conversation.serviceUrl = activity.serviceUrl.replace(/\/+$/, "");
350
+ const tenant = activity.conversation?.tenantId ?? data.tenant?.id;
351
+ if (tenant)
352
+ conversation.tenant = tenant;
353
+ if (activity.conversation?.name)
354
+ conversation.name = activity.conversation.name;
355
+ if (data.team?.id) {
356
+ conversation.team = {
357
+ ...conversation.team,
358
+ id: data.team.id,
359
+ ...(data.team.aadGroupId ? { aadGroupId: data.team.aadGroupId } : {}),
360
+ ...(data.team.name ? { name: data.team.name } : {}),
361
+ };
362
+ }
363
+ // channelData.channel is the channel the event is about: a new or renamed one comes in the General channel. The
364
+ // General channel has the team's ID, and Teams gives it no name.
365
+ const named = data.channel?.id ? (this.#state.conversations[data.channel.id] ??= {}) : undefined;
366
+ if (named && data.channel.name)
367
+ named.channelName = data.channel.name;
368
+ if (named && data.team && named !== conversation)
369
+ named.team = { ...conversation.team };
370
+ if (where.conversation === data.team?.id)
371
+ conversation.channelName ??= "General";
372
+ // The team's Entra group ID, for Graph, comes with some events only: every channel of the team gets it.
373
+ if (data.team?.id && data.team.aadGroupId)
374
+ this.#knowTeam(data.team.id, data.team.aadGroupId);
375
+ const from = activity.from;
376
+ if (conversation.type === "personal" && from?.id && from.id !== this.#botId) {
377
+ this.#state.dms[from.aadObjectId ?? from.id] = where.conversation;
378
+ if (from.name)
379
+ conversation.name = from.name;
380
+ }
381
+ }
382
+ for (const account of [activity.from, ...(activity.membersAdded ?? [])]) {
383
+ if (!account?.aadObjectId || account.id === this.#botId)
384
+ continue;
385
+ const person = (this.#state.people[account.aadObjectId] ??= {});
386
+ if (account.id)
387
+ person.id = account.id;
388
+ if (account.name)
389
+ person.name = account.name;
390
+ }
391
+ if (JSON.stringify(this.#state) !== before)
392
+ this.#save();
393
+ }
394
+ /** A team's Entra group ID, for every conversation of the team the channel knows. */
395
+ #knowTeam(team, group) {
396
+ for (const conversation of Object.values(this.#state.conversations)) {
397
+ if (conversation.team?.id === team)
398
+ conversation.team = { ...conversation.team, aadGroupId: group };
399
+ }
400
+ }
401
+ #save() {
402
+ try {
403
+ writeState(this.#stateFile, this.#state);
404
+ }
405
+ catch (error) {
406
+ this.#env.log("could not keep what the channel learned", { error: String(error) });
407
+ }
408
+ }
409
+ owns(address) {
410
+ return address.startsWith(`${this.id}:`);
411
+ }
412
+ // ---- Addresses ----
413
+ placeOf(address) {
414
+ const parsed = this.#parse(address);
415
+ return "conversation" in parsed ? this.place(parsed.conversation) : undefined;
416
+ }
417
+ place(conversation) {
418
+ return `${this.id}:#${conversation}`;
419
+ }
420
+ person(id) {
421
+ return `${this.id}:@${id}`;
422
+ }
423
+ /** A message's address. A root message of a channel's thread is the thread's address. */
424
+ #messageAt(where, message) {
425
+ if (!where.root || where.root === message)
426
+ return `${this.id}:#${where.conversation}/${message}`;
427
+ return `${this.id}:#${where.conversation}/${where.root}/${message}`;
428
+ }
429
+ #threadAt(where) {
430
+ return where.root ? `${this.id}:#${where.conversation}/${where.root}` : undefined;
431
+ }
432
+ #parse(address) {
433
+ if (!this.owns(address))
434
+ throw new Error(`not a ${this.id} address: ${address}`);
435
+ const rest = address.slice(this.id.length + 1);
436
+ const place = /^#([^/\s]+)(?:\/([^/\s]+))?(?:\/([^/\s]+))?$/.exec(rest);
437
+ if (place) {
438
+ if (place[3])
439
+ return { conversation: place[1], root: place[2], message: place[3] };
440
+ return { conversation: place[1], ...(place[2] ? { message: place[2] } : {}) };
441
+ }
442
+ const person = /^@([^/\s]+)$/.exec(rest);
443
+ if (person)
444
+ return { user: person[1] };
445
+ throw new Error(`bad ${this.id} address: ${address}`);
446
+ }
447
+ #tryParse(address) {
448
+ try {
449
+ return this.#parse(address);
450
+ }
451
+ catch {
452
+ return undefined;
453
+ }
454
+ }
455
+ // ---- Translate ----
456
+ async translate(value) {
457
+ const raw = value;
458
+ if (raw.source === "history")
459
+ return this.#history(raw.conversation, raw.message, raw.since);
460
+ if (raw.source === "sent")
461
+ return this.#sent(raw);
462
+ const { activity, at } = raw;
463
+ const where = whereOf(activity);
464
+ const time = Date.parse(activity.timestamp ?? "");
465
+ const when = Number.isFinite(time) ? time : at;
466
+ switch (activity.type) {
467
+ case "message":
468
+ if (!where)
469
+ return [];
470
+ return activity.value !== undefined && !activity.text ? [this.#submit(activity, where, when)] : [this.#message("message", activity, where, when)];
471
+ case "messageUpdate":
472
+ // An edit, or a deleted message brought back (undeleteMessage): either way the message as it is now.
473
+ return where ? [this.#message("edit", activity, where, when)] : [];
474
+ case "messageDelete":
475
+ if (!where || !activity.id)
476
+ return [];
477
+ return [{ kind: "delete", at: when, place: this.#placeInfo(where.conversation), message: this.#messageAt(where, activity.id), ...this.#thread(where), fromMe: false, raw: activity }];
478
+ case "messageReaction":
479
+ return where ? this.#reactions(activity, where, when) : [];
480
+ case "conversationUpdate":
481
+ return where ? this.#conversationUpdate(activity, where, when) : [];
482
+ case "installationUpdate": {
483
+ const added = String(activity.action ?? "").startsWith("add");
484
+ const place = where ? this.#placeInfo(where.conversation) : undefined;
485
+ return [
486
+ {
487
+ kind: added ? "join" : "leave",
488
+ at: when,
489
+ ...(place ? { place } : {}),
490
+ ...this.#meAsPerson(),
491
+ fromMe: false,
492
+ text: `${added ? "the app was added to" : "the app was removed from"} ${place?.name ? `"${place.name}"` : "this place"}${activity.from?.name ? ` by ${activity.from.name}` : ""}`,
493
+ raw: activity,
494
+ },
495
+ ];
496
+ }
497
+ case "invoke":
498
+ return [this.#invoke(activity, where, when)];
499
+ default:
500
+ if (!where)
501
+ return [];
502
+ return [{ kind: "system", at: when, place: this.#placeInfo(where.conversation), ...this.#personOf(activity.from), fromMe: false, text: `Teams activity ${activity.type}${activity.name ? ` ${activity.name}` : ""}`, raw: activity }];
503
+ }
504
+ }
505
+ /** A message or an edit, as an activity gives it. */
506
+ #message(kind, activity, where, at) {
507
+ const mentioned = (activity.entities ?? []).filter((entity) => entity?.type === "mention" && entity.mentioned?.id);
508
+ const from = activity.from;
509
+ const thread = this.#threadAt(where);
510
+ const isReply = thread !== undefined && where.root !== activity.id;
511
+ return {
512
+ kind,
513
+ at,
514
+ place: this.#placeInfo(where.conversation),
515
+ message: this.#messageAt(where, activity.id),
516
+ ...(isReply ? { thread, ...(kind === "message" ? { threadRoot: thread } : {}) } : {}),
517
+ ...this.#personOf(from),
518
+ fromMe: from?.id !== undefined && from.id === this.#botId,
519
+ mentionsMe: mentioned.some((entity) => entity.mentioned.id === (activity.recipient?.id ?? this.#botId)),
520
+ text: activityText(activity),
521
+ mentions: mentioned.filter((entity) => entity.mentioned.id !== this.#botId).map((entity) => this.person(this.#personId(entity.mentioned))),
522
+ ...activityFiles(activity),
523
+ raw: activity,
524
+ };
525
+ }
526
+ /** A click on an Action.Submit button of a card: a message with the card's values and no text. */
527
+ #submit(activity, where, at) {
528
+ return {
529
+ kind: "interaction",
530
+ at,
531
+ place: this.#placeInfo(where.conversation),
532
+ ...(activity.replyToId ? { message: this.#messageAt(where, activity.replyToId) } : {}),
533
+ ...this.#thread(where),
534
+ ...this.#personOf(activity.from),
535
+ fromMe: false,
536
+ text: `clicked a card's Action.Submit button${valuesText(activity.value)}`,
537
+ raw: activity,
538
+ };
539
+ }
540
+ /** An invoke: a click on a card's Action.Execute button, or another request of Teams to the app. */
541
+ #invoke(activity, where, at) {
542
+ const action = activity.value?.action ?? {};
543
+ const text = activity.name === "adaptiveCard/action"
544
+ ? `clicked card button${action.title ? ` "${action.title}"` : ""}${action.verb ? ` (verb ${action.verb})` : ""}${valuesText(action.data)}`
545
+ : `Teams sent the request ${activity.name ?? "invoke"}${valuesText(activity.value)}`;
546
+ return {
547
+ kind: "interaction",
548
+ at,
549
+ ...(where ? { place: this.#placeInfo(where.conversation) } : {}),
550
+ ...(where && activity.replyToId ? { message: this.#messageAt(where, activity.replyToId) } : {}),
551
+ ...(where ? this.#thread(where) : {}),
552
+ ...this.#personOf(activity.from),
553
+ fromMe: false,
554
+ text,
555
+ raw: activity,
556
+ };
557
+ }
558
+ /** Reactions: Teams sends them only on the bot's own messages. */
559
+ #reactions(activity, where, at) {
560
+ if (!activity.replyToId)
561
+ return [];
562
+ const happenings = [];
563
+ for (const [list, kind] of [
564
+ [activity.reactionsAdded, "reaction_added"],
565
+ [activity.reactionsRemoved, "reaction_removed"],
566
+ ]) {
567
+ for (const reaction of (list ?? [])) {
568
+ happenings.push({
569
+ kind,
570
+ at,
571
+ place: this.#placeInfo(where.conversation),
572
+ message: this.#messageAt(where, activity.replyToId),
573
+ ...this.#thread(where),
574
+ ...this.#personOf(activity.from),
575
+ fromMe: activity.from?.id === this.#botId,
576
+ text: REACTION_EMOJI[reaction.type ?? ""] ?? reaction.type ?? "?",
577
+ raw: activity,
578
+ });
579
+ }
580
+ }
581
+ return happenings;
582
+ }
583
+ /** People who joined or left, the bot added or removed, and changes to a team, its channels or a chat. */
584
+ #conversationUpdate(activity, where, at) {
585
+ const place = this.#placeInfo(where.conversation);
586
+ const happenings = [];
587
+ for (const [list, kind] of [
588
+ [activity.membersAdded, "join"],
589
+ [activity.membersRemoved, "leave"],
590
+ ]) {
591
+ for (const member of (list ?? [])) {
592
+ const mine = member.id === this.#botId || member.id === activity.recipient?.id;
593
+ happenings.push({
594
+ kind,
595
+ at,
596
+ place,
597
+ ...(mine ? this.#meAsPerson() : this.#personOf(member)),
598
+ fromMe: false,
599
+ ...(mine ? { text: `${kind === "join" ? "added to" : "removed from"} ${place.name ? `"${place.name}"` : "this place"}` } : {}),
600
+ raw: activity,
601
+ });
602
+ }
603
+ }
604
+ const event = activity.channelData?.eventType;
605
+ const text = event ? updateText(event, activity) : activity.topicName ? `the chat's name changed to "${activity.topicName}"` : undefined;
606
+ if (text)
607
+ happenings.push({ kind: "system", at, place, ...this.#personOf(activity.from), fromMe: false, text, raw: activity });
608
+ return happenings;
609
+ }
610
+ /**
611
+ * A message the backfill read from Graph, as it is now. System messages (a member added, a call) are not read as
612
+ * messages. One edited after the backfill's start is also an edit, at its edit time: the log keeps a message it has
613
+ * and takes the edit, and an older edit never replaces a newer one.
614
+ */
615
+ #history(conversation, message, since) {
616
+ if (message.messageType && message.messageType !== "message")
617
+ return [];
618
+ const where = { conversation, ...(message.replyToId ? { root: message.replyToId } : {}) };
619
+ const created = Date.parse(message.createdDateTime ?? "");
620
+ const at = Number.isFinite(created) ? created : Date.now();
621
+ const address = this.#messageAt(where, message.id);
622
+ const thread = this.#threadAt(where);
623
+ const place = this.#placeInfo(conversation);
624
+ if (message.deletedDateTime) {
625
+ return [{ kind: "delete", at: Date.parse(message.deletedDateTime) || at, place, message: address, ...(thread ? { thread } : {}), fromMe: false, raw: message }];
626
+ }
627
+ const user = message.from?.user;
628
+ const application = message.from?.application;
629
+ const fromMe = application?.id !== undefined && application.id === this.#clientId;
630
+ const person = fromMe ? this.me : user?.id ? { address: this.person(user.id), ...(user.displayName ? { name: user.displayName } : {}) } : undefined;
631
+ const content = message.body?.content ?? "";
632
+ const files = (message.attachments ?? []).filter((file) => file.contentType === "reference" && file.contentUrl);
633
+ const common = {
634
+ place,
635
+ message: address,
636
+ ...(person ? { person } : {}),
637
+ fromMe,
638
+ mentionsMe: (message.mentions ?? []).some((mention) => mention.mentioned?.application?.id !== undefined && mention.mentioned.application.id === this.#clientId),
639
+ text: message.body?.contentType === "html" ? htmlToMarkdown(content) : content,
640
+ mentions: (message.mentions ?? []).flatMap((mention) => (mention.mentioned?.user?.id ? [this.person(mention.mentioned.user.id)] : [])),
641
+ ...(files.length ? { files: files.map((file) => ({ ...(file.name ? { name: file.name } : {}), url: file.contentUrl })) } : {}),
642
+ raw: message,
643
+ };
644
+ const happenings = [{ kind: "message", at, ...common, ...(thread ? { thread, threadRoot: thread } : {}) }];
645
+ const edited = Date.parse(message.lastEditedDateTime ?? "");
646
+ if (Number.isFinite(edited) && (since === undefined || edited > since))
647
+ happenings.push({ kind: "edit", at: edited, ...common, ...(thread ? { thread } : {}) });
648
+ return happenings;
649
+ }
650
+ /** A message this channel posted: from send, with its send ID, or from call. */
651
+ #sent(raw) {
652
+ const activity = raw.activity;
653
+ const where = whereOf(activity);
654
+ if (!where || !activity.id)
655
+ return [];
656
+ const thread = this.#threadAt(where);
657
+ const isReply = thread !== undefined && where.root !== activity.id;
658
+ const at = Date.parse(activity.timestamp ?? "");
659
+ return [
660
+ {
661
+ kind: "message",
662
+ at: Number.isFinite(at) ? at : Date.now(),
663
+ place: this.#placeInfo(where.conversation),
664
+ message: this.#messageAt(where, activity.id),
665
+ ...(isReply ? { thread, threadRoot: thread } : {}),
666
+ ...this.#meAsPerson(),
667
+ fromMe: true,
668
+ text: raw.markdown ?? activityText(activity),
669
+ ...(raw.sendId ? { sendId: raw.sendId } : {}),
670
+ raw: activity,
671
+ },
672
+ ];
673
+ }
674
+ #thread(where) {
675
+ const thread = this.#threadAt(where);
676
+ return thread ? { thread } : {};
677
+ }
678
+ #meAsPerson() {
679
+ const me = this.me;
680
+ return me ? { person: me } : {};
681
+ }
682
+ /** A Teams account as a person: by Entra object ID, or the Teams ID when Teams did not give one. */
683
+ #personOf(account) {
684
+ if (!account?.id && !account?.aadObjectId)
685
+ return {};
686
+ if (account.id !== undefined && account.id === this.#botId)
687
+ return this.#meAsPerson();
688
+ const id = this.#personId(account);
689
+ const name = account.name || this.#state.people[id]?.name;
690
+ return { person: { address: this.person(id), ...(name ? { name } : {}) } };
691
+ }
692
+ /** The ID in a person's address: the Entra object ID, also when only the Teams ID came and the channel has seen both. */
693
+ #personId(account) {
694
+ if (account.aadObjectId)
695
+ return account.aadObjectId;
696
+ const known = Object.entries(this.#state.people).find(([, person]) => person.id === account.id)?.[0];
697
+ return known ?? account.id;
698
+ }
699
+ #placeInfo(conversation) {
700
+ const known = this.#state.conversations[conversation];
701
+ const kind = placeKind(conversation, known?.type);
702
+ const name = kind === "channel"
703
+ ? [known?.team?.name, known?.channelName ? `#${known.channelName}` : undefined].filter(Boolean).join(" ") || undefined
704
+ : known?.name;
705
+ return { address: this.place(conversation), kind, ...(name ? { name } : {}) };
706
+ }
707
+ // ---- Backfill ----
708
+ /**
709
+ * Store the messages that came while Pots was down, from Microsoft Graph, in every channel and group chat the log
710
+ * knows: each from its newest logged message, or else from when Pots last ran. DMs are not read: they need a
711
+ * permission for every chat of the organisation. Oldest first in each place.
712
+ */
713
+ async backfill(sink) {
714
+ const lastAlive = sink.lastAlive();
715
+ if (lastAlive === undefined || this.#options.playground)
716
+ return;
717
+ const starts = this.#starts;
718
+ await this.#recover(sink, (conversation) => starts.get(conversation) ?? lastAlive);
719
+ }
720
+ /** A backfill after the ones under way: one at a time, so each place's recovery start is kept by one of them. */
721
+ #recover(sink, startOf) {
722
+ const run = this.#refilling.then(() => this.#backfill(sink, startOf));
723
+ this.#refilling = run.catch(() => { });
724
+ return this.#track(run);
725
+ }
726
+ /**
727
+ * Each place is read whole before anything of it is stored. Before any place is read, the start of each is kept in
728
+ * the state file (or an earlier start kept there, by a backfill that did not end well), and only a whole reading of
729
+ * the place removes it: live messages that came meanwhile do not move where the next backfill starts. stop ends it.
730
+ */
731
+ async #backfill(sink, startOf) {
732
+ const stopping = this.#stopping.signal;
733
+ const recovering = this.#state.recovering;
734
+ const places = [];
735
+ for (const place of await sink.places()) {
736
+ const parsed = this.#tryParse(place);
737
+ if (!parsed || !("conversation" in parsed))
738
+ continue;
739
+ const conversation = parsed.conversation;
740
+ const kind = placeKind(conversation, this.#state.conversations[conversation]?.type);
741
+ if (kind === "dm")
742
+ continue;
743
+ const since = Math.min(startOf(conversation), recovering[conversation] ?? Infinity);
744
+ recovering[conversation] = since;
745
+ places.push({ place, conversation, kind, since });
746
+ }
747
+ if (places.length)
748
+ this.#save();
749
+ let added = 0;
750
+ for (const { place, conversation, kind, since } of places) {
751
+ if (stopping.aborted)
752
+ return;
753
+ try {
754
+ const messages = kind === "channel" ? await this.#channelHistory(conversation, since) : await this.#chatHistory(conversation, since);
755
+ messages.sort((a, b) => (Date.parse(a.createdDateTime ?? "") || 0) - (Date.parse(b.createdDateTime ?? "") || 0));
756
+ for (const message of messages) {
757
+ if (stopping.aborted)
758
+ return;
759
+ const where = { conversation, ...(message.replyToId ? { root: message.replyToId } : {}) };
760
+ await sink.receive(`history:${messageKey(where, message.id)}:${message.lastModifiedDateTime ?? ""}`, { source: "history", conversation, message, since });
761
+ added++;
762
+ }
763
+ if (stopping.aborted)
764
+ return;
765
+ delete recovering[conversation];
766
+ this.#save();
767
+ }
768
+ catch (error) {
769
+ if (stopping.aborted)
770
+ return;
771
+ sink.log("backfill skipped a place; it is read again from the same start next time", { place, error: errorText(error) });
772
+ }
773
+ }
774
+ sink.log("backfill done", { messages: added });
775
+ }
776
+ /**
777
+ * A channel's messages changed after since, from Graph: root messages with their replies. Graph gives the roots
778
+ * newest first by the last change in the whole thread, its replies included, and filters nothing by time: read pages
779
+ * until one has no thread changed after since. Graph gives no such order for a thread's replies, so every page of the
780
+ * replies of each root read is read.
781
+ */
782
+ async #channelHistory(channel, since) {
783
+ const team = await this.#teamGroup(channel);
784
+ const base = `/teams/${encodeURIComponent(team)}/channels/${encodeURIComponent(channel)}/messages`;
785
+ const found = [];
786
+ for await (const page of this.#pages(`${this.#graph}${base}?$top=50&$expand=replies`)) {
787
+ let changed = false;
788
+ for (const root of page) {
789
+ const replies = [...(root.replies ?? [])];
790
+ // The replies Graph did not expand (all of them, if it expanded none), to the end.
791
+ const rest = root.replies === undefined ? `${this.#graph}${base}/${encodeURIComponent(root.id)}/replies?$top=50` : root["replies@odata.nextLink"];
792
+ if (rest)
793
+ for await (const more of this.#pages(rest))
794
+ replies.push(...more);
795
+ const newer = replies.filter((reply) => changedAfter(reply, since));
796
+ if (changedAfter(root, since))
797
+ found.push(withoutReplies(root));
798
+ found.push(...newer.map((reply) => ({ ...withoutReplies(reply), replyToId: reply.replyToId ?? root.id })));
799
+ changed ||= newer.length > 0 || changedAfter(root, since);
800
+ }
801
+ if (!changed)
802
+ break;
803
+ }
804
+ return found;
805
+ }
806
+ /**
807
+ * The Entra group ID of a channel's team, which Graph needs: from the channel's events, from another channel of the
808
+ * same team, or else from Teams' Bot Connector (by the team's ID, or by the channel's when no event gave the team).
809
+ */
810
+ async #teamGroup(channel) {
811
+ const conversations = this.#state.conversations;
812
+ const team = conversations[channel]?.team;
813
+ if (team?.aadGroupId)
814
+ return team.aadGroupId;
815
+ const teamId = team?.id;
816
+ const known = teamId ? Object.values(conversations).find((each) => each.team?.id === teamId && each.team.aadGroupId)?.team?.aadGroupId : undefined;
817
+ const details = known ? undefined : (await this.#fetch("bot", "GET", `${this.#serviceUrl(channel)}/v3/teams/${teamId ?? channel}`));
818
+ const group = known ?? details?.aadGroupId;
819
+ if (!group)
820
+ throw new Error("Teams did not give the Entra group of this channel's team");
821
+ const conversation = (conversations[channel] ??= {});
822
+ conversation.team = { ...conversation.team, id: teamId ?? details?.id ?? channel, aadGroupId: group, ...(details?.name && !conversation.team?.name ? { name: details.name } : {}) };
823
+ this.#knowTeam(conversation.team.id, group);
824
+ this.#save();
825
+ return group;
826
+ }
827
+ /** A group chat's messages changed after since, newest first, from Graph. */
828
+ async #chatHistory(chat, since) {
829
+ const query = new URLSearchParams({ $top: "50", $orderby: "lastModifiedDateTime desc", $filter: `lastModifiedDateTime gt ${new Date(since).toISOString()}` });
830
+ const found = [];
831
+ for await (const page of this.#pages(`${this.#graph}/chats/${encodeURIComponent(chat)}/messages?${query}`))
832
+ found.push(...page.filter((message) => changedAfter(message, since)));
833
+ return found;
834
+ }
835
+ /**
836
+ * The pages of a Graph list, following @odata.nextLink to the end: no page is left out, so nothing is lost between
837
+ * what was read and where the next backfill starts. A link that leaves Graph or comes again is an error.
838
+ */
839
+ async *#pages(first) {
840
+ let url = first;
841
+ const seen = new Set();
842
+ while (url) {
843
+ if (!url.startsWith(`${this.#graph}/`))
844
+ throw new Error(`Microsoft Graph gave a next page outside Graph: ${url.slice(0, 200)}`);
845
+ if (seen.has(url))
846
+ throw new Error("Microsoft Graph gave the same next page twice");
847
+ seen.add(url);
848
+ const answer = (await this.#fetch("graph", "GET", url));
849
+ yield answer.value ?? [];
850
+ url = answer["@odata.nextLink"];
851
+ }
852
+ }
853
+ // ---- Send ----
854
+ checkText(_to, text) {
855
+ return refusal(this.#outgoing(text).text);
856
+ }
857
+ /**
858
+ * Post the text. Teams keeps no field of ours on a message, so a sent message cannot be found again by its send ID:
859
+ * a crash between Teams taking it and Pots recording it posts it twice. A text over Teams' limit is refused, never cut.
860
+ */
861
+ async send(to, text, sendId) {
862
+ const { text: content, entities } = this.#outgoing(text);
863
+ const refused = refusal(content);
864
+ if (refused)
865
+ throw new Error(refused);
866
+ const target = await this.#target(to);
867
+ const activity = { type: "message", text: content, textFormat: "markdown", ...(entities.length ? { entities } : {}) };
868
+ const conversationId = target.root ? `${target.conversation};messageid=${target.root}` : target.conversation;
869
+ const answer = (await this.#fetch("bot", "POST", `${this.#serviceUrl(target.conversation)}/v3/conversations/${conversationId}/activities`, activity));
870
+ if (!answer?.id)
871
+ throw new Error("Teams took the message but gave no ID");
872
+ const sent = { ...activity, id: answer.id, conversation: { id: conversationId }, ...(this.#botId ? { from: { id: this.#botId, name: this.#env.botName } } : {}), timestamp: new Date().toISOString() };
873
+ const where = { conversation: target.conversation, ...(target.root ? { root: target.root } : {}) };
874
+ return { message: this.#messageAt(where, answer.id), place: this.place(target.conversation), raw: { source: "sent", sendId, markdown: text, activity: sent } };
875
+ }
876
+ /** Teams keeps no send ID on a message. */
877
+ async findSent(_to, _sendId, _since) {
878
+ return undefined;
879
+ }
880
+ /**
881
+ * The text as Teams takes it: Markdown through Chat SDK's converter, and each person address in angle brackets as a
882
+ * Teams mention, with the person's name from what the channel has seen.
883
+ */
884
+ #outgoing(text) {
885
+ const prefix = this.id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
886
+ const people = [];
887
+ const marked = text.replace(new RegExp(`<${prefix}:@([^>\\s/]+)>`, "g"), (_token, id) => `${people.push(id) - 1}`);
888
+ const rendered = convertEmojiPlaceholders(converter.renderPostable({ markdown: marked }), "teams");
889
+ const entities = [];
890
+ const content = rendered.replace(/(\d+)/g, (_token, index) => {
891
+ const id = people[Number(index)];
892
+ const known = this.#state.people[id];
893
+ const name = known?.name ?? id;
894
+ const tag = `<at>${escapeHtml(name)}</at>`;
895
+ entities.push({ type: "mention", text: tag, mentioned: { id: known?.id ?? id, name } });
896
+ return tag;
897
+ });
898
+ return { text: content, entities };
899
+ }
900
+ /**
901
+ * Where a send goes. A place: a new post in a channel, or a message in a chat. A thread, or a message in one: a reply in
902
+ * that thread. A channel's root message: a reply in its thread. A message in a chat: a message in that chat. A person:
903
+ * the DM with them, made when there is none.
904
+ */
905
+ async #target(to) {
906
+ const parsed = this.#parse(to);
907
+ if ("user" in parsed)
908
+ return { conversation: await this.#dm(parsed.user) };
909
+ if (parsed.root)
910
+ return { conversation: parsed.conversation, root: parsed.root };
911
+ if (parsed.message && placeKind(parsed.conversation, this.#state.conversations[parsed.conversation]?.type) === "channel")
912
+ return { conversation: parsed.conversation, root: parsed.message };
913
+ return { conversation: parsed.conversation };
914
+ }
915
+ /** The DM conversation with a person: the one Teams gave, or a new one (Teams makes it, or gives the one there is). */
916
+ async #dm(user) {
917
+ const known = this.#state.dms[user];
918
+ if (known)
919
+ return known;
920
+ const tenant = this.#tenantId ?? Object.values(this.#state.conversations).find((conversation) => conversation.tenant)?.tenant;
921
+ if (!this.#botId)
922
+ throw new Error("the bot's Teams ID is not known yet");
923
+ const member = this.#state.people[user]?.id ?? user;
924
+ const answer = (await this.#fetch("bot", "POST", `${this.#serviceUrl()}/v3/conversations`, {
925
+ isGroup: false,
926
+ bot: { id: this.#botId },
927
+ members: [{ id: member }],
928
+ ...(tenant ? { tenantId: tenant, channelData: { tenant: { id: tenant } } } : {}),
929
+ }));
930
+ if (!answer?.id)
931
+ throw new Error("Teams made no DM");
932
+ this.#state.dms[user] = answer.id;
933
+ (this.#state.conversations[answer.id] ??= {}).type = "personal";
934
+ this.#save();
935
+ return answer.id;
936
+ }
937
+ /** Where to send for a conversation: the service URL of its events, or else of any event, or else the default. */
938
+ #serviceUrl(conversation) {
939
+ const known = conversation ? this.#state.conversations[conversation]?.serviceUrl : undefined;
940
+ return (known ??
941
+ Object.values(this.#state.conversations).find((each) => each.serviceUrl)?.serviceUrl ??
942
+ (this.#endpoints.serviceUrl ?? DEFAULT_SERVICE_URL).replace(/\/+$/, ""));
943
+ }
944
+ /**
945
+ * React to a message. Teams takes a few reactions from a bot: like, heart, laugh, surprised, sad, angry and some
946
+ * others by their Teams ID; an emoji or a name it does not take is refused here.
947
+ */
948
+ async react(message, emoji, remove) {
949
+ const parsed = this.#parse(message);
950
+ if (!("conversation" in parsed) || !parsed.message)
951
+ throw new Error(`not a message address: ${message}`);
952
+ const type = reactionType(emoji);
953
+ const conversationId = parsed.root ? `${parsed.conversation};messageid=${parsed.root}` : parsed.conversation;
954
+ await this.#fetch("bot", remove ? "DELETE" : "PUT", `${this.#serviceUrl(parsed.conversation)}/v3/conversations/${conversationId}/activities/${parsed.message}/reactions/${encodeURIComponent(type)}`);
955
+ }
956
+ /**
957
+ * The content of a file of a message. A file in a DM comes with a download link of its own, which needs no token; an
958
+ * image pasted in a message is read with the bot token, only at the address of Teams' Bot Connector that Teams' own
959
+ * events gave (as Chat SDK does: no other host gets the token). A file in a channel or a group chat is a SharePoint
960
+ * link, which needs Graph file permissions that only an admin can give: it is not read.
961
+ */
962
+ async fetchFile(file, signal) {
963
+ const url = new URL(file.url ?? "");
964
+ let headers = {};
965
+ if (url.protocol === "https:" && isSharePoint(url.hostname) && url.searchParams.has("tempauth")) {
966
+ // A DM file's own download link.
967
+ }
968
+ else if (this.#connectorOrigins().has(connectorOrigin(url) ?? "")) {
969
+ const token = await abortable(() => this.#token("bot"), AbortSignal.any([signal, this.#stopping.signal, AbortSignal.timeout(this.#requestTimeout)]));
970
+ headers = token ? { authorization: `Bearer ${token}` } : {};
971
+ }
972
+ else if (isSharePoint(url.hostname)) {
973
+ throw new Error("Teams gives files in channels and group chats as SharePoint links; reading them needs Graph file permissions (Files.Read.All or Sites.Read.All) that an admin grants. Ask the person to send the file in a DM, or to share it with you another way.");
974
+ }
975
+ else {
976
+ throw new Error(`not a Teams file URL: ${url.origin}`);
977
+ }
978
+ const response = await fetch(url, { headers, signal, redirect: "error" });
979
+ if (!response.ok || !response.body)
980
+ throw new Error(`Teams answered ${response.status} ${response.statusText}`);
981
+ return Readable.fromWeb(response.body);
982
+ }
983
+ /**
984
+ * A request with the bot's token. method is "<HTTP method> <path>": a path of Teams' Bot Connector API (/v3/…), at
985
+ * the service URL of the conversation in it; or "graph:<HTTP method> <path>" for Microsoft Graph, with the app's own
986
+ * token (what the app's resource-specific permissions allow). params are the query for GET and DELETE, and the JSON
987
+ * body for the others. A message posted with POST /v3/conversations/<ID>/activities is stored as the bot's own.
988
+ */
989
+ async call(method, params) {
990
+ const match = /^(graph:)?(GET|POST|PUT|PATCH|DELETE) (\/\S+)$/.exec(method.trim());
991
+ if (!match)
992
+ throw new Error(`call takes "<GET|POST|PUT|PATCH|DELETE> /v3/<path>" for Teams, or "graph:<METHOD> /<path>" for Microsoft Graph; not ${JSON.stringify(method)}`);
993
+ const [, graph, verb, path] = match;
994
+ const query = verb === "GET" || verb === "DELETE" ? new URLSearchParams(Object.entries(params).map(([key, value]) => [key, String(value)])) : undefined;
995
+ const body = query ? undefined : params;
996
+ if (graph) {
997
+ const base = path.startsWith("/beta/") ? this.#graph.replace(/\/v1\.0$/, "") : this.#graph;
998
+ return this.#fetch("graph", verb, `${base}${path}${query?.size ? `?${query}` : ""}`, body);
999
+ }
1000
+ if (!path.startsWith("/v3/"))
1001
+ throw new Error(`a Teams path starts with /v3/, for example /v3/conversations/<ID>/activities; for Microsoft Graph, use "graph:${verb} ${path}"`);
1002
+ const conversation = /^\/v3\/conversations\/([^/;]+)/.exec(path)?.[1];
1003
+ const result = await this.#fetch("bot", verb, `${this.#serviceUrl(conversation)}${path}${query?.size ? `?${query}` : ""}`, body);
1004
+ const posted = /^\/v3\/conversations\/([^/]+)\/activities$/.exec(path)?.[1];
1005
+ const id = result?.id;
1006
+ if (verb === "POST" && posted && typeof id === "string" && (body?.type === undefined || body.type === "message")) {
1007
+ const activity = { ...body, id, conversation: { id: posted }, ...(this.#botId ? { from: { id: this.#botId, name: this.#env.botName } } : {}), timestamp: new Date().toISOString() };
1008
+ await this.#sink?.receive(`sent:${messageKey(whereOf(activity), id)}`, { source: "sent", activity }).catch((error) => this.#sink?.log("sent message not stored", { error: String(error) }));
1009
+ }
1010
+ return result;
1011
+ }
1012
+ /** The origins of Teams' Bot Connector: the service URLs Teams' events gave, and the default one. */
1013
+ #connectorOrigins() {
1014
+ const urls = [...Object.values(this.#state.conversations).map((conversation) => conversation.serviceUrl), this.#endpoints.serviceUrl ?? DEFAULT_SERVICE_URL];
1015
+ return new Set(urls.flatMap((each) => (each ? [connectorOrigin(new URL(each))].filter((origin) => origin !== undefined) : [])));
1016
+ }
1017
+ get #requestTimeout() {
1018
+ return this.#endpoints.timeouts?.request ?? REQUEST_TIMEOUT_MS;
1019
+ }
1020
+ /**
1021
+ * The bot's token for Teams, or the app's token for Graph; never one in playground mode. The SDK and MSAL take no
1022
+ * signal, so a getting that a request stops waiting for goes on: the requests of the next minute (as long as a
1023
+ * request is tried) wait for the same one rather than begin more, and what it gives after stop goes nowhere.
1024
+ */
1025
+ #token(kind) {
1026
+ const app = this.#app;
1027
+ if (!app)
1028
+ throw new TeamsError(`channel ${this.id} is not started`);
1029
+ if (this.#options.playground)
1030
+ return Promise.resolve(undefined);
1031
+ const known = this.#tokens.get(kind);
1032
+ if (known && Date.now() - known.started < (this.#endpoints.timeouts?.retry ?? RETRY_MS) + this.#requestTimeout)
1033
+ return known.work;
1034
+ const provider = app.tokenProvider;
1035
+ const work = (kind === "bot" ? provider.getAppToken() : provider.getAppToken(app.cloud.graphScope, this.#tenantId)).then((token) => (token ? String(token) : undefined));
1036
+ const getting = { work, started: Date.now() };
1037
+ this.#tokens.set(kind, getting);
1038
+ void work
1039
+ .finally(() => {
1040
+ if (this.#tokens.get(kind) === getting)
1041
+ this.#tokens.delete(kind);
1042
+ })
1043
+ .catch(() => { });
1044
+ return work;
1045
+ }
1046
+ /**
1047
+ * One request to Teams or Graph. One that fails before Teams answers, or that Teams answers with "too many requests"
1048
+ * or "busy", is tried again after the wait Teams asks for or a growing one, until a try fails a minute or more after
1049
+ * the first began. Each try, its token included, has REQUEST_TIMEOUT_MS. stop ends the request and its waits. The
1050
+ * error says what Teams answered, never the token.
1051
+ */
1052
+ async #fetch(kind, method, url, body) {
1053
+ const stopping = this.#stopping.signal;
1054
+ const retryMs = this.#endpoints.timeouts?.retry ?? RETRY_MS;
1055
+ const started = Date.now();
1056
+ for (let attempt = 1;; attempt++) {
1057
+ if (stopping.aborted)
1058
+ throw new TeamsError(`channel ${this.id} stopped`);
1059
+ const signal = AbortSignal.any([stopping, AbortSignal.timeout(this.#requestTimeout)]);
1060
+ let wait;
1061
+ let failure;
1062
+ try {
1063
+ const token = await abortable(() => this.#token(kind), signal);
1064
+ const response = await fetch(url, {
1065
+ method,
1066
+ headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body !== undefined ? { "content-type": "application/json" } : {}), accept: "application/json" },
1067
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
1068
+ signal,
1069
+ redirect: "error",
1070
+ });
1071
+ const text = await response.text();
1072
+ const data = text ? parseJson(text) : null;
1073
+ if (response.ok)
1074
+ return data;
1075
+ failure = `${kind === "graph" ? "Microsoft Graph" : "Teams"} answered ${response.status}${answerText(data, text)}`;
1076
+ if (!RETRY_STATUS.has(response.status))
1077
+ throw new TeamsError(failure);
1078
+ wait = retryAfter(response.headers.get("retry-after")) ?? backoff(attempt);
1079
+ }
1080
+ catch (error) {
1081
+ if (error instanceof TeamsError)
1082
+ throw error;
1083
+ if (stopping.aborted)
1084
+ throw new TeamsError(`channel ${this.id} stopped`);
1085
+ failure = `${kind === "graph" ? "Microsoft Graph" : "Teams"} did not answer: ${errorText(error)}`;
1086
+ wait = backoff(attempt);
1087
+ }
1088
+ if (Date.now() - started >= retryMs)
1089
+ throw new TeamsError(`${failure}; tried for ${Math.round((Date.now() - started) / 1000)} s, then gave up`);
1090
+ await sleep(Math.min(wait, Math.max(retryMs - (Date.now() - started), 0)), undefined, { signal: stopping }).catch(() => { });
1091
+ }
1092
+ }
1093
+ }
1094
+ class TeamsError extends Error {
1095
+ }
1096
+ /** The conversation of an activity, without ";messageid=", and the root of its thread in a channel. */
1097
+ function whereOf(activity) {
1098
+ const id = activity.conversation?.id;
1099
+ if (typeof id !== "string" || !id)
1100
+ return undefined;
1101
+ const [conversation] = id.split(";");
1102
+ const root = /;messageid=([^;]+)/.exec(id)?.[1];
1103
+ return { conversation: conversation, ...(root ? { root } : {}) };
1104
+ }
1105
+ /**
1106
+ * An activity's event ID. An activity Teams sends again has the same one. An edit is one event per edit time; an
1107
+ * activity without an ID is known by its content.
1108
+ */
1109
+ function activityEventId(activity) {
1110
+ const where = whereOf(activity) ?? { conversation: "" };
1111
+ const id = activity.id ?? createHash("sha256").update(JSON.stringify(activity)).digest("hex").slice(0, 32);
1112
+ if (activity.type === "messageUpdate")
1113
+ return `${activity.channelData?.eventType ?? "messageUpdate"}:${messageKey(where, id)}:${activity.timestamp ?? ""}`;
1114
+ return `${activity.type}${activity.name ? `/${activity.name}` : ""}:${messageKey(where, id)}`;
1115
+ }
1116
+ /**
1117
+ * A message in an event ID: its conversation, its thread's root when it is a reply, and its ID, as in its address.
1118
+ * Graph keeps a message ID unique only in its chat, channel or thread
1119
+ * (https://learn.microsoft.com/graph/api/resources/chatmessage): replies in two threads of a channel can have the same.
1120
+ * A root message, or one outside a thread, keeps the key it always had.
1121
+ */
1122
+ function messageKey(where, id) {
1123
+ return where.root && where.root !== id ? `${where.conversation}/${where.root}/${id}` : `${where.conversation}/${id}`;
1124
+ }
1125
+ /** A message ID of Teams is the time it was made, in Unix ms. */
1126
+ function messageTime(id) {
1127
+ return id && /^\d{12,14}$/.test(id) ? Number(id) : undefined;
1128
+ }
1129
+ function changedAfter(message, since) {
1130
+ const changed = Date.parse(message.lastModifiedDateTime ?? message.createdDateTime ?? "");
1131
+ return !Number.isFinite(changed) || changed > since;
1132
+ }
1133
+ /** A message as the backfill stores it: a root without the replies Graph expanded, which are stored on their own. */
1134
+ function withoutReplies(message) {
1135
+ const { replies: _replies, "replies@odata.nextLink": _next, ...rest } = message;
1136
+ return rest;
1137
+ }
1138
+ /** A DM is "personal"; a group chat "groupChat"; a channel "channel". Without an event's word, by the ID's form. */
1139
+ function placeKind(conversation, type) {
1140
+ if (type === "channel")
1141
+ return "channel";
1142
+ if (type === "groupChat")
1143
+ return "group";
1144
+ if (type === "personal")
1145
+ return "dm";
1146
+ if (/@thread\.(tacv2|skype)$/.test(conversation))
1147
+ return "channel";
1148
+ if (/@thread\.v2$/.test(conversation))
1149
+ return "group";
1150
+ return "dm";
1151
+ }
1152
+ /** A message's text as Markdown: its HTML when Teams sent one, else its text. */
1153
+ function activityText(activity) {
1154
+ const html = (activity.attachments ?? []).find((attachment) => attachment?.contentType === "text/html" && typeof attachment.content === "string")?.content;
1155
+ const text = html ?? (typeof activity.text === "string" ? activity.text : "");
1156
+ if (activity.textFormat === "markdown" && !html)
1157
+ return text;
1158
+ return htmlToMarkdown(text);
1159
+ }
1160
+ /** Teams' HTML as Markdown, with the line breaks of its blocks kept; mentions as @name. */
1161
+ function htmlToMarkdown(html) {
1162
+ if (!/[<&]/.test(html))
1163
+ return html;
1164
+ const blocks = html
1165
+ .replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi, (_all, code) => `<p>\`\`\`\n${code.replace(/<br\s*\/?>/gi, "\n")}\n\`\`\`</p>`)
1166
+ .replace(/<br\s*\/?>/gi, "\n")
1167
+ .replace(/<li[^>]*>/gi, "\n- ")
1168
+ .replace(/<\/(p|div|ul|ol|h\d|blockquote)>/gi, "$&\n\n");
1169
+ return converter.toMarkdown(blocks).trim();
1170
+ }
1171
+ /** The files of a message: a DM's files with their download link, pasted images, and SharePoint links in channels. */
1172
+ function activityFiles(activity) {
1173
+ const files = [];
1174
+ for (const attachment of (activity.attachments ?? [])) {
1175
+ const type = String(attachment?.contentType ?? "");
1176
+ if (type === "application/vnd.microsoft.teams.file.download.info" && attachment.content?.downloadUrl) {
1177
+ files.push({ ...(attachment.name ? { name: attachment.name } : {}), ...(attachment.content.fileType ? { type: mimeOf(attachment.content.fileType) } : {}), url: attachment.content.downloadUrl });
1178
+ }
1179
+ else if (type.startsWith("image/") && attachment.contentUrl) {
1180
+ files.push({ ...(attachment.name ? { name: attachment.name } : {}), ...(type !== "image/*" ? { type } : {}), url: attachment.contentUrl });
1181
+ }
1182
+ else if (type === "reference" && attachment.contentUrl) {
1183
+ files.push({ ...(attachment.name ? { name: attachment.name } : {}), url: attachment.contentUrl });
1184
+ }
1185
+ }
1186
+ return files.length ? { files } : {};
1187
+ }
1188
+ function mimeOf(fileType) {
1189
+ const types = { pdf: "application/pdf", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", txt: "text/plain", csv: "text/csv", json: "application/json", zip: "application/zip" };
1190
+ return types[fileType.toLowerCase()] ?? "application/octet-stream";
1191
+ }
1192
+ /** A card's values, one a line, after a colon; nothing when there are none. */
1193
+ function valuesText(value) {
1194
+ if (value === undefined || value === null)
1195
+ return "";
1196
+ if (typeof value !== "object")
1197
+ return `: ${String(value)}`;
1198
+ const lines = Object.entries(value).map(([key, each]) => `${key}: ${(typeof each === "string" ? each || "(empty)" : JSON.stringify(each)).replace(/\r?\n/g, "\n ")}`);
1199
+ return lines.length ? `\n${lines.join("\n")}` : "";
1200
+ }
1201
+ /** A change in a team or a chat, in words. */
1202
+ function updateText(event, activity) {
1203
+ const channel = activity.channelData?.channel?.name;
1204
+ const team = activity.channelData?.team?.name;
1205
+ switch (event) {
1206
+ case "teamMemberAdded":
1207
+ case "teamMemberRemoved":
1208
+ return undefined;
1209
+ case "channelCreated":
1210
+ return `the channel ${channel ? `"${channel}" ` : ""}was created`;
1211
+ case "channelRenamed":
1212
+ return `a channel was renamed to "${channel ?? "?"}"`;
1213
+ case "channelDeleted":
1214
+ return `the channel ${channel ? `"${channel}" ` : ""}was deleted`;
1215
+ case "channelRestored":
1216
+ return `the channel ${channel ? `"${channel}" ` : ""}was restored`;
1217
+ case "teamRenamed":
1218
+ return `the team was renamed to "${team ?? "?"}"`;
1219
+ case "teamDeleted":
1220
+ return "the team was deleted";
1221
+ case "teamArchived":
1222
+ return "the team was archived";
1223
+ case "teamUnarchived":
1224
+ return "the team was unarchived";
1225
+ case "teamRestored":
1226
+ return "the team was restored";
1227
+ default:
1228
+ return `Teams event ${event}`;
1229
+ }
1230
+ }
1231
+ /** A reaction as Teams takes it, from an emoji, a name such as :eyes:, or Teams' own ID. */
1232
+ function reactionType(emoji) {
1233
+ const text = emoji.trim();
1234
+ if (REACTIONS[text])
1235
+ return REACTIONS[text];
1236
+ const name = /^:?([\w+-]+):?$/.exec(text)?.[1];
1237
+ if (name && REACTION_NAMES[name.toLowerCase()])
1238
+ return REACTION_NAMES[name.toLowerCase()];
1239
+ if (/^[0-9a-f]{4,6}_\w+$/.test(text))
1240
+ return text;
1241
+ throw new Error(`Teams does not take the reaction ${text} from a bot. Use one of 👍 ❤️ 😆 😮 😢 😠 👀 ✅ 🚀 📌 (or like, heart, laugh, surprised, sad, angry, eyes, white_check_mark, rocket, pushpin), or a Teams reaction ID such as 1f440_eyes`);
1242
+ }
1243
+ function refusal(text) {
1244
+ const bytes = Buffer.byteLength(text, "utf8");
1245
+ return bytes > MAX_BYTES ? `Teams allows about ${MAX_BYTES} bytes in one message; this one has ${bytes}. Send it in parts, or as a page.` : undefined;
1246
+ }
1247
+ function escapeHtml(text) {
1248
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1249
+ }
1250
+ function isSharePoint(host) {
1251
+ return host.endsWith(".sharepoint.com") || host.endsWith(".sharepoint.us") || host.endsWith(".sharepoint-df.com");
1252
+ }
1253
+ /** The origin of a URL that may get the bot token: HTTPS, or HTTP on this computer (as Chat SDK has it, for tests). */
1254
+ function connectorOrigin(url) {
1255
+ if (url.protocol === "https:")
1256
+ return url.origin;
1257
+ if (url.protocol === "http:" && /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i.test(url.hostname))
1258
+ return url.origin;
1259
+ return undefined;
1260
+ }
1261
+ /**
1262
+ * What start gives, or the signal's reason once it aborts: for work that takes no signal, such as getting a token. It
1263
+ * does not start once the signal has aborted, and an end of the work that comes after is taken and dropped.
1264
+ */
1265
+ function abortable(start, signal) {
1266
+ if (signal.aborted)
1267
+ return Promise.reject(signal.reason);
1268
+ return new Promise((resolve, reject) => {
1269
+ const work = start();
1270
+ const abort = () => reject(signal.reason);
1271
+ signal.addEventListener("abort", abort, { once: true });
1272
+ work.then((value) => {
1273
+ signal.removeEventListener("abort", abort);
1274
+ resolve(value);
1275
+ }, (error) => {
1276
+ signal.removeEventListener("abort", abort);
1277
+ reject(error);
1278
+ });
1279
+ });
1280
+ }
1281
+ function parseJson(text) {
1282
+ try {
1283
+ return JSON.parse(text);
1284
+ }
1285
+ catch {
1286
+ return text;
1287
+ }
1288
+ }
1289
+ /** What Teams or Graph said in a refused request: its error code and message. */
1290
+ function answerText(data, text) {
1291
+ const error = data?.error;
1292
+ if (error && typeof error === "object")
1293
+ return `: ${[error.code, error.message].filter(Boolean).join(": ")}`;
1294
+ if (typeof data === "string" && text)
1295
+ return `: ${text.slice(0, 500)}`;
1296
+ return data ? `: ${JSON.stringify(data).slice(0, 500)}` : "";
1297
+ }
1298
+ function retryAfter(header) {
1299
+ if (!header)
1300
+ return undefined;
1301
+ const seconds = Number(header);
1302
+ if (Number.isFinite(seconds))
1303
+ return Math.min(Math.max(seconds, 0) * 1000, 30_000);
1304
+ const at = Date.parse(header);
1305
+ return Number.isFinite(at) ? Math.min(Math.max(at - Date.now(), 0), 30_000) : undefined;
1306
+ }
1307
+ /** 1, 2, 4, 8, 15 s, with up to half more at random so many bots do not try at the same moment. */
1308
+ function backoff(attempt) {
1309
+ const base = Math.min(1000 * 2 ** (attempt - 1), 15_000);
1310
+ return base + Math.floor(Math.random() * base * 0.5);
1311
+ }
1312
+ function errorText(error) {
1313
+ return error instanceof Error ? error.message : String(error);
1314
+ }
1315
+ function readState(file) {
1316
+ try {
1317
+ const value = JSON.parse(readFileSync(file, "utf8"));
1318
+ return { conversations: value.conversations ?? {}, people: value.people ?? {}, dms: value.dms ?? {}, recovering: value.recovering ?? {} };
1319
+ }
1320
+ catch {
1321
+ return { conversations: {}, people: {}, dms: {}, recovering: {} };
1322
+ }
1323
+ }
1324
+ /** Written whole, to a part file first, so a crash leaves the old file or the new one. */
1325
+ function writeState(file, state) {
1326
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
1327
+ const part = `${file}.${randomBytes(6).toString("hex")}.part`;
1328
+ try {
1329
+ writeFileSync(part, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
1330
+ renameSync(part, file);
1331
+ }
1332
+ catch (error) {
1333
+ rmSync(part, { force: true });
1334
+ throw error;
1335
+ }
1336
+ }
1337
+ //# sourceMappingURL=index.js.map