pi-pocket 0.29.0-beta.7 → 0.29.0-beta.8
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/docs/extensions/relay.md +15 -7
- package/docs/features.md +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/src/server/extensions/pocket-relay/connectors/discord.ts +1 -32
- package/src/server/extensions/pocket-relay/connectors/matrix.ts +166 -26
- package/src/server/extensions/pocket-relay/connectors/slack.ts +185 -11
- package/src/server/extensions/pocket-relay/connectors/telegram.ts +216 -29
- package/src/server/extensions/pocket-relay/download.ts +73 -0
- package/src/server/extensions/pocket-relay/files.ts +15 -1
- package/src/server/extensions/pocket-relay/runtime.ts +19 -1
- package/src/server/extensions/pocket-relay.ts +1 -1
package/docs/extensions/relay.md
CHANGED
|
@@ -204,16 +204,24 @@ Return `{ id }`, the id the service gave, or nothing. A call that takes more tha
|
|
|
204
204
|
|
|
205
205
|
### Files
|
|
206
206
|
|
|
207
|
-
A connector that sends files declares `files: { max, maxBytes }`: `max` files of `maxBytes` each at most in one reply. Pi gives paths in `relay_reply`'s `files`. The relay reads each one and gives your `reply` the bytes in `reply.files`. The relay refuses a path outside the session's folder (after it follows links), a path with a hidden part (a name that starts with `.`, except the `.relay` folder), a file in the server's data folder, and a file over the caps. A connector without `files` refuses a reply with files, and nothing is sent. With files, a reply has 120 seconds.
|
|
207
|
+
A connector that sends files declares `files: { max, maxBytes }`: `max` files of `maxBytes` each at most in one reply. Pi gives paths in `relay_reply`'s `files`. The relay reads each one and gives your `reply` the bytes in `reply.files`. The relay refuses a path outside the session's folder (after it follows links), a path with a hidden part (a name that starts with `.`, except the `.relay` folder), a file in the server's data folder, and a file over the caps. A connector without `files` refuses a reply with files, and nothing is sent. One reply sends 100 MB of files in all at most. With files, a reply has 120 seconds, and about 1 second more for each MB.
|
|
208
208
|
|
|
209
209
|
A connector that downloads attachments has `fetch(context, file, maxBytes)`. It returns `{ data, type }`, with `maxBytes` (25 MB) at most. Pi calls `relay_fetch` with the event id and the attachment's number. The relay writes the file to `.relay/<event>/<number>-<name>` in the session's folder, with a safe name. It refuses a file over the cap, and a web page (`text/html`) in place of a file that did not name that type. Errors go to Pi without secrets and without links. Download only from the service's own file hosts, and never send the token to a host that is not the service's.
|
|
210
210
|
|
|
211
|
-
| Kind
|
|
212
|
-
|
|
|
213
|
-
| Discord
|
|
214
|
-
| Slack
|
|
215
|
-
|
|
|
216
|
-
|
|
|
211
|
+
| Kind | Sends files | Fetches attachments |
|
|
212
|
+
| -------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
213
|
+
| Discord | Yes: 10 files, 10 MB each | Yes |
|
|
214
|
+
| Slack | Yes: 10 files, 50 MB each, in one message with the text (needs the `files:write` scope) | Yes, from `files.slack.com` only (needs the `files:read` scope) |
|
|
215
|
+
| Telegram | Yes: 10 files, 50 MB each; an image of 10 MB or less goes as a photo | Yes: photos, documents, video, and sound, 20 MB at most (the Bot API's limit) |
|
|
216
|
+
| Matrix | Yes: 10 files, 50 MB each (or the homeserver's lower limit), each as its own event | Yes, from the homeserver only; not from an encrypted room |
|
|
217
|
+
| HTTP | No | No |
|
|
218
|
+
| RSS | No: it only listens | No |
|
|
219
|
+
|
|
220
|
+
Limits of the built-in kinds:
|
|
221
|
+
|
|
222
|
+
- Slack and Telegram have no idempotency key. The relay does not send again a reply that a restart or an error cut off. Slack shares the text and all the files in one call, so it sends all or nothing. Telegram sends each part on its own, so a cut-off reply can stay partly sent (the text without a file, or some of the files).
|
|
223
|
+
- Telegram sends each file as its own message. A short text (1,024 characters or fewer) is the first file's caption. A photo that Telegram refuses goes again as a document. A local Bot API server in `--local` mode gives paths on its disk: the relay cannot fetch from it.
|
|
224
|
+
- Matrix sends the text and each file as separate events, each with its own transaction id. A homeserver keeps transaction ids for a limited time (Synapse about 30 minutes): a replay after a longer stop can show the reply twice. A replay uploads the files again.
|
|
217
225
|
|
|
218
226
|
`relay_reply` and `relay_fetch` are deferred tools: they are offered only in sessions that a connector delivers to. The relay adds them to the session's `modelTools` when a connector is saved, and takes them out when no connector delivers there any more. Pi gives `connector` (the name) when more than one connector delivers to the session.
|
|
219
227
|
|
package/docs/features.md
CHANGED
|
@@ -47,7 +47,7 @@ The full tour. For setup, see the [README](../README.md).
|
|
|
47
47
|
- **Watch a pull request.** Menu → **Watch pull request**, `/watch` (or `/watch 123`, `/watch <PR address>`), or Pi's `watch_pr` tool, which it can start after opening a PR (Pi only for its folder's repository, by number; a person for any): until the PR is merged or closed, Pi Pocket looks at it on GitHub every few minutes with the `gh` command signed in on the server, and tells Pi in the session what needs doing, as a message sent through the watch for whoever set it up: checks that failed on its last commit (once all of them finished, with the end of each GitHub Actions log), conflicts with its base branch, and new comments and reviews. Only comments from the repository's owner, and from organization members and collaborators whom GitHub says can write to it, count, and bots' reviews (a member may only read, a collaborator only triage: `gh` asks GitHub, at most every ten minutes for each person, and GitHub tells only an account that can push there, so on a PR where yours cannot, such as a fork's PR to someone else's repository, only the owner's count, and the watch says so); your own account's (which Pi posts as) only when they mention @pi in their own words (not in a quote or code), so Pi never answers itself. Comments keep their lines (a suggested change is code), 30 at most in a message (read newest first, so a burst never hides the new ones); each is told once, and what does not fit in one message comes in the next; nothing goes while Pi is busy there or, with take turns on, while someone else drives (the bar says it waits, and nothing counts as failed); and a watch sends 10 messages at most. While Triggers is off it asks GitHub nothing. A bar above the message box shows the PR, its checks, and how many messages went, with **Stop**. It ends, with a line in the chat and a notification, when the PR is merged or closed, when there is more to tell than it may send, after two weeks with nothing new, or after an hour of looks that failed (the bar says why). Logs reach Pi fenced as data, which nothing in them can end early, and titles, check names, and branches come on one line, quoted, as data too. It needs `gh` installed and signed in (`gh auth login`) on the server, on GitHub Enterprise hosts too: a host other than github.com is used only when `gh` is signed in there (`gh auth login --hostname <host>`; a token only in `GH_ENTERPRISE_TOKEN` does not count), for Pi, PiP, and people alike, and Pi names a PR by address only on github.com or its folder's own host.
|
|
48
48
|
- **Watch a repository.** Tell PiP in plain words, such as "watch acme/api: when CI fails on main, fix it and tell me" or "when I open an issue labelled pi in acme/web, work on it": it sets up a watch that looks at the repository on GitHub every few minutes with `gh` (no public address needed, unlike a webhook), and what is new there (issues and pull requests opened, CI failing on a branch, releases, someone writing @pi, as a word of its own, in a comment or an issue) comes to PiP, or to a session you name, with your instructions; PiP then acts on it: it starts a session in the repository (its checkout here, or a clone it makes in the data folder's `repos/`), sends it the task, follows it, and tells you what came of it. A watch can be narrowed to a label, to issues assigned to you, or to a branch's CI (mentions of @pi are not narrowed). CI is the branch's own runs: pushed to it, scheduled, started by hand or through the API, or started by another workflow, in the repository itself, never a pull request's or an issue's (a renamed repository keeps working). Only repositories `gh`'s account can push to can be watched or worked on, and issues and pull requests count only from the repository's owner, and organization members and collaborators whom GitHub says can write to it (and bots' pull requests), unless you turn on **From anyone** on the watch in Menu → Webhooks and watches (PiP cannot); @pi always only from them. PiP works in a checkout of a session you started, or in a clone it makes, which appears only once complete (a clone a restart cut off leaves a `~part-…` folder, removed at the next clone of that repository); a different folder already where the clone goes is reported, never overwritten. While Triggers is off, watches wait and ask GitHub nothing; while PiP is off, a watch to PiP holds what it found, and its note says so. What came from GitHub is fenced as data, each thing is told once, ten in a message and twelve messages an hour at most (the rest come next), and a look that fails is tried again, less often each time, with the reason shown. Menu → **Webhooks and watches** lists the watches, to remove one; or ask PiP ("what are you watching?", "stop watching acme/api"). PiP can also start a PR watch on a session ("see acme/api#12 through"), and Pi's own `watch_pr` takes a PR in another repository it can push to by its address or `owner/name#12`, telling Pi to work in a checkout of it. Part of the **Triggers** extension.
|
|
49
49
|
- **Webhooks.** Menu → **Webhooks and watches**: an address that other services (GitHub, a deploy, a monitor) post to, each post becoming a message to Pi in a session, or to PiP, as the work of whoever made the hook: their instructions first ("When a deploy fails, find out why and fix it"), then what was posted, trimmed of noise such as API addresses, and fenced as data. PiP gets them as folded cards and decides what to do: start a session, message one, or tell you. A GitHub hook is signed: GitHub gets the address and, separately, a secret (its Payload URL and Secret), and a post gets in only with GitHub's signature made with it, so whoever sees the address (the repository's admins do, in its settings) cannot post as the hook. Unless a GitHub hook is made **From anyone**, what people outside the repository wrote does not reach Pi (the repository's people are its owner, and the organization members and collaborators whom GitHub says can write to it, asked through `gh`, which must be signed in to the host and able to push there, or else only the owner counts; bots count on pull requests and what is said on them, never on issues): a post an outsider started (their issue, comment, pull request, review, or discussion) is dropped with a 202 that says so; in a post the repository's people started, the body of anything an outsider wrote in it (the issue under a member's comment, a review thread's comments) is left out, its title kept; a workflow run goes only when a branch of the repository itself started it (a push, a schedule, a manual or API dispatch, or another workflow), so one a pull request (a fork's too), an issue, or a comment started is dropped, and so is one whose head repository GitHub does not show; workflow jobs, check suites, and check runs do not say where their run came from, so they are dropped too, as are a commit status on no branch of the repository (a fork's commit) and a security advisory someone reported; and pushes, releases, and other posts that name no author go as they came. A hook for another service has the secret in its address instead: anyone who has the address can message Pi as the hook's person. **New secret** shuts out the old one, for an address or a secret that got out. Anything else gets 404. A post GitHub sends again goes to Pi once, GitHub's ping gets an answer and is nothing for Pi, a hook takes 30 posts an hour of up to 5 MB each (the server reads eight at a time, two to one hook, each within 15 seconds; past that, 503 with Retry-After), a hook to PiP answers 503 while PiP is turned off, and a post that cannot go now (someone else drives, a spend limit) gets a 409 that says no more. Services must be able to reach the server: through a tunnel, a public address works for GitHub. People who can steer make hooks for the sessions they can reach; each sees their own, the owner every one. Choose **Edit prompt** to change a hook's instructions, then **Save** or **Cancel**. Only the hook's creator or the server owner can save changes, and they need steering rights. You can enter up to 2000 characters. Leave the instructions empty to ask Pi to summarize what happened and whether anything needs doing. Saved changes apply to later posts. The address, secret, destination, and usage history stay unchanged. Webhooks and the Relay (the next item) deliver the same way, through core's inbox: the same fence, the same once-only key, and a limit for each source. The watch and webhooks are the **Triggers** extension: turned off, watches wait and hooks answer 503.
|
|
50
|
-
- **Relay.** Menu → **Extensions** → **Relay** (off by default) lets a chat service or a feed send messages to a session, with no separate relay service and no public address: each connector makes outbound connections only (it polls, or keeps a stream open), and delivers inside the server. Menu → **Relay** (the owner only) adds a connector: choose its kind, a session, and instructions for Pi, then its fields. **Discord** needs a bot token, and the bot's **Message Content Intent** turned on in the Developer Portal; **Slack** uses Socket Mode, with an app token (`xapp-…`) and a bot token (`xoxb-…`); **Telegram** needs a bot token; **Matrix** needs a homeserver address and an access token; **RSS** needs a feed address; **HTTP** polls any JSON address, with headers, the fields of an item, and an optional reply address. For a chat service, give channel, chat, or room IDs, or leave them empty for all the bot can see; for direct messages, Discord has its own switch. Each message comes to the session as `[via relay <name>]`: the owner's instructions first, then the sender, then what was written, fenced as data in `<relay-message>` tags. Pi answers with the `relay_reply` tool, which only a session that a connector delivers to is offered; a reply goes to where the message came from, and a call that runs again sends once. On **Discord**, Pi can send images and files from the session's folder with a reply (10 files
|
|
50
|
+
- **Relay.** Menu → **Extensions** → **Relay** (off by default) lets a chat service or a feed send messages to a session, with no separate relay service and no public address: each connector makes outbound connections only (it polls, or keeps a stream open), and delivers inside the server. Menu → **Relay** (the owner only) adds a connector: choose its kind, a session, and instructions for Pi, then its fields. **Discord** needs a bot token, and the bot's **Message Content Intent** turned on in the Developer Portal; **Slack** uses Socket Mode, with an app token (`xapp-…`) and a bot token (`xoxb-…`); **Telegram** needs a bot token; **Matrix** needs a homeserver address and an access token; **RSS** needs a feed address; **HTTP** polls any JSON address, with headers, the fields of an item, and an optional reply address. For a chat service, give channel, chat, or room IDs, or leave them empty for all the bot can see; for direct messages, Discord has its own switch. Each message comes to the session as `[via relay <name>]`: the owner's instructions first, then the sender, then what was written, fenced as data in `<relay-message>` tags. Pi answers with the `relay_reply` tool, which only a session that a connector delivers to is offered; a reply goes to where the message came from, and a call that runs again sends once. On **Discord**, **Slack**, **Telegram**, and **Matrix**, Pi can send images and files from the session's folder with a reply (10 files; 10 MB each on Discord, 50 MB on the others, 100 MB in all; never a hidden file, a file outside the folder, or the server's data), and can download an attachment that a person posted with `relay_fetch`, into `.relay/` in the session's folder, where it reads an image (25 MB at most, 20 MB on Telegram); the token and the file's link never reach Pi. Slack needs the `files:write` and `files:read` scopes for this, and Matrix fetches nothing from an encrypted room. Each event is delivered once, also across restarts: what came waits on disk until the session takes it (a busy session, a spend limit, or a restart do not lose it). Messages from bots, and from the connector's own account, are dropped. **Mention only** takes messages that name the bot, or that come in a direct message. **Owner IDs** are your own accounts on the service: Pi reads them as an id you marked as trusted (guidance for the model, not a boundary, since some services let a person pretend to be another), and they have no limit; every other author has 10 messages an hour by default, and a connector 30 an hour (both can be changed; a feed's items, RSS, or HTTP without an author id field, have only the connector's limit), and a message over a limit is dropped and counted. The first look at a feed or an address takes nothing that was there before. Tokens are kept on the server only (a file of mode 0600 in the data folder's `x.pocket-relay`, which Pi's tools cannot read), never reach the browser (it only shows that one is set), and are hidden from transcripts and errors. A connector that fails shows why and tries again, less often each time; a refused token stops it until you edit it, and an error never stops the server. Drop-in extensions can add kinds of connectors ([Relay connectors](extensions/relay.md)).
|
|
51
51
|
- **Spend and limits.** Menu → **Spend** shows a large total and usage bars (against a limit, or the largest spend in that group): what Pi spent per person (the work goes to whoever asked for it) and per session, subagents included. The owner can limit a session or a person: past the limit Pi takes no new messages there, scheduled messages and goals stop, a run that crosses it stops, and subagents' reports wait instead of starting Pi again: the subagents bar says why (the owner gets **Raise it**), and they go to Pi together once the limit is raised, those that were in the queue when the run stopped included. The status line shows a session's spend and limit; for a session with a limit that started linked sessions (Agent Teams), the spend it shows, here and in the sheet, is the team's, as its limit counts it. PiP's row shows its limit too, and PiP's notices (such as a stop at its limit) show in its panel. Spend per person counts from the first start of a version with this feature; what was spent before shows for its sessions only.
|
|
52
52
|
- **A session's folder.** **New** (or Alt+N) opens a folder picker laid out as a desktop's file dialog, in the folder of the session you are in (or the server's folder, on the home screen): the path on top (tap a part to go back up, or its end to type a path), places at the side (Home, Computer, the server's default workspace when it is another folder, and recent folders; pin the default workspace there to start every new session in it, in this browser, since 0.28.0), the folders where you are, and **Cancel** and **Open** at the bottom, with **Own git worktree** and **Show hidden** beside them. With a mouse, a click selects a folder and a double click goes into it; on a touch screen, a tap goes into it. **Open** starts the session in the selected folder, or in the one you are in, as the **Folder:** line says. Keys work as in a file dialog: arrows, Enter, Backspace to go up, letters to jump, `/` or Ctrl+L to type a path, Ctrl+Enter to open. The star on the **Folder:** line keeps that folder among the places as a favorite (tap it again to let it go). Favorites are each person's own, saved on the server, and change at once on all their devices; while New session is open, Ctrl+1…9 (⌘1…9 on a Mac) starts a session in one of the first nine, with **Own git worktree** as it is set. **New folder** makes a folder where you are and goes into it; a typed path that is not there yet offers **Create it**. Menu → **Working directory** (or `/cwd`) moves a session with the same picker. Someone invited to one session cannot browse or make folders. The launcher lists these too: **New session here** for the folder you are in, and **New session in** and its name for each favorite; each starts a session there at once, without a worktree of its own.
|
|
53
53
|
- **Branch.** The top bar shows the git branch the session's folder has checked out, under the session's title beside the folder, and follows it when Pi or anyone else switches (in a terminal too, within seconds). Tap it (or Menu → **Branch**, the launcher, `/branch`, or the branch in Changes, which stays in sight however long the folder's path) for the branch picker, down from it: the folder's branches with the current one first, then the newest, each with its last commit and how far it is ahead of or behind its remote branch, and the remote branches it has no local branch for. Type to search; a name that is no branch yet makes one from what is checked out (spaces become dashes), and a remote branch becomes a local one that follows it. Uncommitted changes come along, and when git would overwrite them it says so and nothing changes. A branch checked out in another worktree is listed but switched to only there. Switching changes the files under Pi, so as with moving the session to another folder it waits while Pi works and, while taking turns, is the driver's; Pi is told. Viewers see the branch; someone invited to one session can look but not switch.
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-pocket",
|
|
3
|
-
"version": "0.29.0-beta.
|
|
3
|
+
"version": "0.29.0-beta.8",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "pi-pocket",
|
|
9
|
-
"version": "0.29.0-beta.
|
|
9
|
+
"version": "0.29.0-beta.8",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@earendil-works/chord": "1.5.2",
|
package/package.json
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Discord: a bot that hears messages over the gateway (v10) and replies over REST. */
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
+
import { bytesOf } from "../download.ts";
|
|
3
4
|
import {
|
|
4
5
|
RelayError,
|
|
5
6
|
type RelayConnector,
|
|
@@ -343,38 +344,6 @@ function fileHost(url: string, values: RelayValues): boolean {
|
|
|
343
344
|
);
|
|
344
345
|
}
|
|
345
346
|
|
|
346
|
-
/** At most `max` bytes of a response, or an error: a larger file is never read to its end. */
|
|
347
|
-
async function bytesOf(response: Response, max: number): Promise<Uint8Array> {
|
|
348
|
-
if (Number(response.headers.get("content-length") ?? 0) > max) {
|
|
349
|
-
await response.body?.cancel();
|
|
350
|
-
|
|
351
|
-
throw new Error(`the file is larger than ${Math.round(max / 1048576)} MB`);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
const parts: Uint8Array[] = [];
|
|
355
|
-
let size = 0;
|
|
356
|
-
|
|
357
|
-
for await (const part of (response.body ?? []) as AsyncIterable<Uint8Array>) {
|
|
358
|
-
size += part.byteLength;
|
|
359
|
-
|
|
360
|
-
if (size > max) {
|
|
361
|
-
throw new Error(`the file is larger than ${Math.round(max / 1048576)} MB`);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
parts.push(part);
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
const data = new Uint8Array(size);
|
|
368
|
-
let at = 0;
|
|
369
|
-
|
|
370
|
-
for (const part of parts) {
|
|
371
|
-
data.set(part, at);
|
|
372
|
-
at += part.byteLength;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
return data;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
347
|
async function download(
|
|
379
348
|
context: Pick<RelayContext, "values" | "signal">,
|
|
380
349
|
file: RelayFile,
|
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { bytesOf, getFrom } from "../download.ts";
|
|
3
|
+
import {
|
|
4
|
+
RelayError,
|
|
5
|
+
type RelayConnector,
|
|
6
|
+
type RelayContext,
|
|
7
|
+
type RelayEvent,
|
|
8
|
+
type RelayFile,
|
|
9
|
+
type RelayOutFile,
|
|
10
|
+
} from "../types.ts";
|
|
11
|
+
|
|
12
|
+
/** Synapse takes 50 MB by default; a homeserver with a lower limit refuses, and nothing is sent. */
|
|
13
|
+
const MAX_UPLOAD = 50 * 1024 * 1024;
|
|
14
|
+
const MXC = /^mxc:\/\/([A-Za-z0-9.:[\]-]{1,255})\/([A-Za-z0-9_-]{1,255})$/;
|
|
3
15
|
|
|
4
16
|
type RequestContext = Pick<RelayContext, "values" | "signal">;
|
|
5
17
|
interface MatrixEvent {
|
|
@@ -10,6 +22,8 @@ interface MatrixEvent {
|
|
|
10
22
|
content?: {
|
|
11
23
|
body?: string;
|
|
12
24
|
msgtype?: string;
|
|
25
|
+
filename?: string;
|
|
26
|
+
url?: string;
|
|
13
27
|
info?: { mimetype?: string; size?: number };
|
|
14
28
|
"m.mentions"?: { user_ids?: string[] };
|
|
15
29
|
"m.relates_to"?: { rel_type?: string; event_id?: string };
|
|
@@ -25,25 +39,35 @@ async function request<T>(
|
|
|
25
39
|
path: string,
|
|
26
40
|
body?: unknown,
|
|
27
41
|
longPoll = false,
|
|
42
|
+
file?: RelayOutFile,
|
|
28
43
|
): Promise<T> {
|
|
29
44
|
let response: Response;
|
|
30
45
|
let data: T & { errcode?: string; retry_after_ms?: number };
|
|
31
46
|
|
|
32
47
|
try {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
"
|
|
48
|
+
// A file goes to the media API; everything else is the client API.
|
|
49
|
+
response = await fetch(
|
|
50
|
+
file === undefined
|
|
51
|
+
? `${baseOf(context)}/_matrix/client/v3/${path}`
|
|
52
|
+
: `${baseOf(context)}/_matrix/media/v3/upload?${new URLSearchParams({ filename: file.name })}`,
|
|
53
|
+
{
|
|
54
|
+
method: file !== undefined ? "POST" : body === undefined ? "GET" : "PUT",
|
|
55
|
+
headers: {
|
|
56
|
+
Authorization: `Bearer ${context.values.token}`,
|
|
57
|
+
"content-type": file?.type ?? "application/json",
|
|
58
|
+
},
|
|
59
|
+
body:
|
|
60
|
+
file !== undefined
|
|
61
|
+
? new Blob([file.data as Uint8Array<ArrayBuffer>], { type: file.type })
|
|
62
|
+
: body === undefined
|
|
63
|
+
? undefined
|
|
64
|
+
: JSON.stringify(body),
|
|
65
|
+
signal: AbortSignal.any([
|
|
66
|
+
context.signal,
|
|
67
|
+
AbortSignal.timeout(file !== undefined ? 110_000 : longPoll ? 40_000 : 20_000),
|
|
68
|
+
]),
|
|
40
69
|
},
|
|
41
|
-
|
|
42
|
-
signal: AbortSignal.any([
|
|
43
|
-
context.signal,
|
|
44
|
-
AbortSignal.timeout(longPoll ? 40_000 : 20_000),
|
|
45
|
-
]),
|
|
46
|
-
});
|
|
70
|
+
);
|
|
47
71
|
data = (await response.json().catch(() => undefined)) as typeof data;
|
|
48
72
|
} catch {
|
|
49
73
|
throw new Error("Matrix request failed. Check the homeserver and connection.");
|
|
@@ -72,6 +96,10 @@ async function request<T>(
|
|
|
72
96
|
});
|
|
73
97
|
}
|
|
74
98
|
|
|
99
|
+
if (response.status === 413 || data.errcode === "M_TOO_LARGE") {
|
|
100
|
+
throw new Error("The Matrix homeserver refused the file as too large.");
|
|
101
|
+
}
|
|
102
|
+
|
|
75
103
|
if (!response.ok || data.errcode) {
|
|
76
104
|
throw new Error("Matrix request failed. Check the homeserver configuration.");
|
|
77
105
|
}
|
|
@@ -79,6 +107,61 @@ async function request<T>(
|
|
|
79
107
|
return data;
|
|
80
108
|
}
|
|
81
109
|
|
|
110
|
+
const baseOf = (context: RequestContext): string =>
|
|
111
|
+
String(context.values.homeserver ?? "").replace(/\/$/, "");
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Download from the homeserver only, with the token: its authenticated media first, and the old media API when the
|
|
115
|
+
* homeserver does not know the new one.
|
|
116
|
+
*/
|
|
117
|
+
async function download(
|
|
118
|
+
context: Pick<RelayContext, "values" | "signal">,
|
|
119
|
+
file: RelayFile,
|
|
120
|
+
max: number,
|
|
121
|
+
): Promise<{ data: Uint8Array; type?: string }> {
|
|
122
|
+
const match = MXC.exec(file.ref);
|
|
123
|
+
|
|
124
|
+
if (match === null || !URL.canParse(baseOf(context))) {
|
|
125
|
+
throw new Error("the attachment has no Matrix media address");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const origin = new URL(baseOf(context)).origin;
|
|
129
|
+
const media = `${encodeURIComponent(match[1]!)}/${encodeURIComponent(match[2]!)}`;
|
|
130
|
+
|
|
131
|
+
const get = (path: string) =>
|
|
132
|
+
getFrom(
|
|
133
|
+
`${baseOf(context)}/_matrix/${path}/${media}`,
|
|
134
|
+
(url) => url.origin === origin,
|
|
135
|
+
{
|
|
136
|
+
headers: { Authorization: `Bearer ${context.values.token}` },
|
|
137
|
+
signal: context.signal,
|
|
138
|
+
},
|
|
139
|
+
"the Matrix homeserver",
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
let response = await get("client/v1/media/download");
|
|
143
|
+
|
|
144
|
+
if ([400, 404, 405].includes(response.status)) {
|
|
145
|
+
const error = (await response.json().catch(() => ({}))) as { errcode?: unknown };
|
|
146
|
+
|
|
147
|
+
if (response.status !== 405 && error.errcode !== "M_UNRECOGNIZED") {
|
|
148
|
+
throw new Error(`the Matrix homeserver answered ${response.status}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
response = await get("media/v3/download");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (!response.ok) {
|
|
155
|
+
await response.body?.cancel();
|
|
156
|
+
|
|
157
|
+
throw new Error(`the Matrix homeserver answered ${response.status}`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const type = response.headers.get("content-type") ?? undefined;
|
|
161
|
+
|
|
162
|
+
return { data: await bytesOf(response, max), ...(type === undefined ? {} : { type }) };
|
|
163
|
+
}
|
|
164
|
+
|
|
82
165
|
function batchOf(sync: Sync): string {
|
|
83
166
|
if (typeof sync.next_batch !== "string" || sync.next_batch === "") {
|
|
84
167
|
throw new Error("Matrix sent a sync without a next batch token.");
|
|
@@ -94,6 +177,22 @@ function eventOf(event: MatrixEvent, room: string, user: string): RelayEvent {
|
|
|
94
177
|
const attachment =
|
|
95
178
|
content.msgtype !== undefined &&
|
|
96
179
|
["m.image", "m.file", "m.video", "m.audio"].includes(content.msgtype);
|
|
180
|
+
// An encrypted file has no plain `url`: it is only described.
|
|
181
|
+
const files: RelayFile[] =
|
|
182
|
+
attachment && typeof content.url === "string" && MXC.test(content.url)
|
|
183
|
+
? [
|
|
184
|
+
{
|
|
185
|
+
name: content.filename ?? content.body ?? "file",
|
|
186
|
+
...(typeof content.info?.mimetype === "string"
|
|
187
|
+
? { type: content.info.mimetype }
|
|
188
|
+
: {}),
|
|
189
|
+
...(typeof content.info?.size === "number"
|
|
190
|
+
? { size: content.info.size }
|
|
191
|
+
: {}),
|
|
192
|
+
ref: content.url,
|
|
193
|
+
},
|
|
194
|
+
]
|
|
195
|
+
: [];
|
|
97
196
|
|
|
98
197
|
return {
|
|
99
198
|
id: event.event_id,
|
|
@@ -104,6 +203,7 @@ function eventOf(event: MatrixEvent, room: string, user: string): RelayEvent {
|
|
|
104
203
|
mentioned: content["m.mentions"]?.user_ids?.includes(user) === true || text.includes(user),
|
|
105
204
|
at: event.origin_server_ts,
|
|
106
205
|
attachments: attachment ? [`${content.msgtype}: ${text.replace(/[\r\n]/g, " ")}`] : [],
|
|
206
|
+
...(files.length > 0 ? { files } : {}),
|
|
107
207
|
};
|
|
108
208
|
}
|
|
109
209
|
|
|
@@ -114,6 +214,8 @@ const matrix: RelayConnector = {
|
|
|
114
214
|
description: "A Matrix account: messages in the rooms it joined.",
|
|
115
215
|
shape: "stream",
|
|
116
216
|
mentions: true,
|
|
217
|
+
files: { max: 10, maxBytes: MAX_UPLOAD },
|
|
218
|
+
fetch: download,
|
|
117
219
|
fields: [
|
|
118
220
|
{
|
|
119
221
|
name: "homeserver",
|
|
@@ -192,23 +294,61 @@ const matrix: RelayConnector = {
|
|
|
192
294
|
throw new Error("Choose a Matrix reply room.");
|
|
193
295
|
}
|
|
194
296
|
|
|
195
|
-
const txnId = createHash("sha256").update(reply.key).digest("hex");
|
|
196
297
|
const relation = {
|
|
197
298
|
...(reply.to ? { "m.in_reply_to": { event_id: reply.to.id } } : {}),
|
|
198
299
|
...(thread ? { rel_type: "m.thread", event_id: thread, is_falling_back: true } : {}),
|
|
199
300
|
};
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
301
|
+
const files = reply.files ?? [];
|
|
302
|
+
|
|
303
|
+
// Each event has its own transaction id from the key: one that runs again is sent once.
|
|
304
|
+
const send = async (part: string, content: Record<string, unknown>) =>
|
|
305
|
+
(
|
|
306
|
+
await request<{ event_id: string }>(
|
|
307
|
+
context,
|
|
308
|
+
`rooms/${encodeURIComponent(String(room))}/send/m.room.message/${createHash(
|
|
309
|
+
"sha256",
|
|
310
|
+
)
|
|
311
|
+
.update(part === "" ? reply.key : `${reply.key}\u0000${part}`)
|
|
312
|
+
.digest("hex")}`,
|
|
313
|
+
{
|
|
314
|
+
...content,
|
|
315
|
+
...(Object.keys(relation).length ? { "m.relates_to": relation } : {}),
|
|
316
|
+
"m.mentions": {},
|
|
317
|
+
},
|
|
318
|
+
)
|
|
319
|
+
).event_id;
|
|
320
|
+
|
|
321
|
+
let first: string | undefined;
|
|
322
|
+
|
|
323
|
+
if (reply.text !== "" || files.length === 0) {
|
|
324
|
+
first = await send("", { msgtype: "m.text", body: reply.text });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
for (const [index, file] of files.entries()) {
|
|
328
|
+
const { content_uri: url } = await request<{ content_uri?: string }>(
|
|
329
|
+
context,
|
|
330
|
+
"",
|
|
331
|
+
undefined,
|
|
332
|
+
false,
|
|
333
|
+
file,
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
if (typeof url !== "string" || !MXC.test(url)) {
|
|
337
|
+
throw new Error("The Matrix homeserver gave no media address for the file.");
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const id = await send(`file:${index}`, {
|
|
341
|
+
msgtype: file.type.startsWith("image/") ? "m.image" : "m.file",
|
|
342
|
+
body: file.name,
|
|
343
|
+
filename: file.name,
|
|
344
|
+
url,
|
|
345
|
+
info: { mimetype: file.type, size: file.data.byteLength },
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
first ??= id;
|
|
349
|
+
}
|
|
210
350
|
|
|
211
|
-
return { id:
|
|
351
|
+
return first === undefined ? {} : { id: first };
|
|
212
352
|
},
|
|
213
353
|
};
|
|
214
354
|
|
|
@@ -1,4 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { bytesOf, getFrom } from "../download.ts";
|
|
2
|
+
import {
|
|
3
|
+
RelayError,
|
|
4
|
+
type RelayConnector,
|
|
5
|
+
type RelayContext,
|
|
6
|
+
type RelayEvent,
|
|
7
|
+
type RelayFile,
|
|
8
|
+
type RelayOutFile,
|
|
9
|
+
type RelayValues,
|
|
10
|
+
} from "../types.ts";
|
|
11
|
+
|
|
12
|
+
/** Slack takes files of up to 1 GB: the relay keeps them in memory, so it sends 50 MB at most. */
|
|
13
|
+
const MAX_FILE = 50 * 1024 * 1024;
|
|
2
14
|
|
|
3
15
|
type RequestContext = Pick<RelayContext, "values" | "signal">;
|
|
4
16
|
interface SlackEvent {
|
|
@@ -11,7 +23,16 @@ interface SlackEvent {
|
|
|
11
23
|
ts?: string;
|
|
12
24
|
thread_ts?: string;
|
|
13
25
|
text?: string;
|
|
14
|
-
files?:
|
|
26
|
+
files?: SlackFile[];
|
|
27
|
+
}
|
|
28
|
+
interface SlackFile {
|
|
29
|
+
id?: string;
|
|
30
|
+
name?: string;
|
|
31
|
+
mimetype?: string;
|
|
32
|
+
size?: number;
|
|
33
|
+
mode?: string;
|
|
34
|
+
url_private?: string;
|
|
35
|
+
url_private_download?: string;
|
|
15
36
|
}
|
|
16
37
|
interface Envelope {
|
|
17
38
|
envelope_id?: string;
|
|
@@ -24,20 +45,23 @@ async function request<T>(
|
|
|
24
45
|
method: string,
|
|
25
46
|
app = false,
|
|
26
47
|
body?: unknown,
|
|
48
|
+
form?: Record<string, string>,
|
|
27
49
|
): Promise<T> {
|
|
28
50
|
let response: Response;
|
|
29
|
-
let data: T & { ok?: boolean; error?: string };
|
|
51
|
+
let data: T & { ok?: boolean; error?: string; needed?: string };
|
|
30
52
|
|
|
31
53
|
try {
|
|
32
54
|
const base = String(context.values.apiUrl || "https://slack.com/api").replace(/\/$/, "");
|
|
33
55
|
|
|
56
|
+
// The file methods take form fields, not JSON.
|
|
34
57
|
response = await fetch(`${base}/${method}`, {
|
|
35
58
|
method: "POST",
|
|
36
59
|
headers: {
|
|
37
60
|
Authorization: `Bearer ${app ? context.values.appToken : context.values.botToken}`,
|
|
38
|
-
"content-type":
|
|
61
|
+
"content-type":
|
|
62
|
+
form === undefined ? "application/json" : "application/x-www-form-urlencoded",
|
|
39
63
|
},
|
|
40
|
-
body: JSON.stringify(body ?? {}),
|
|
64
|
+
body: form === undefined ? JSON.stringify(body ?? {}) : new URLSearchParams(form),
|
|
41
65
|
signal: AbortSignal.any([context.signal, AbortSignal.timeout(20_000)]),
|
|
42
66
|
});
|
|
43
67
|
data = (await response.json().catch(() => ({}))) as typeof data;
|
|
@@ -45,6 +69,12 @@ async function request<T>(
|
|
|
45
69
|
throw new Error("Slack request failed. Check the API address and connection.");
|
|
46
70
|
}
|
|
47
71
|
|
|
72
|
+
if (data.error === "missing_scope" && /^[a-z:._,]{1,100}$/.test(data.needed ?? "")) {
|
|
73
|
+
throw new RelayError(`Slack denied access: the bot token needs the ${data.needed} scope.`, {
|
|
74
|
+
fatal: true,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
48
78
|
if (
|
|
49
79
|
response.status === 401 ||
|
|
50
80
|
response.status === 403 ||
|
|
@@ -72,7 +102,9 @@ function eventOf(event: SlackEvent, user: string, channels: string[]): RelayEven
|
|
|
72
102
|
if (
|
|
73
103
|
!["message", "app_mention"].includes(event.type ?? "") ||
|
|
74
104
|
event.bot_id ||
|
|
75
|
-
(event.subtype !== undefined &&
|
|
105
|
+
(event.subtype !== undefined &&
|
|
106
|
+
event.subtype !== "thread_broadcast" &&
|
|
107
|
+
event.subtype !== "file_share") ||
|
|
76
108
|
!event.channel ||
|
|
77
109
|
!event.ts ||
|
|
78
110
|
!event.user ||
|
|
@@ -83,6 +115,22 @@ function eventOf(event: SlackEvent, user: string, channels: string[]): RelayEven
|
|
|
83
115
|
|
|
84
116
|
const text = event.text ?? "";
|
|
85
117
|
const mention = `<@${user}>`;
|
|
118
|
+
// A file kept outside Slack (a drive's link) or deleted has nothing for the bot to download.
|
|
119
|
+
const files: RelayFile[] = (event.files ?? []).flatMap((file) =>
|
|
120
|
+
typeof file.id === "string" && file.mode !== "external" && file.mode !== "tombstone"
|
|
121
|
+
? [
|
|
122
|
+
{
|
|
123
|
+
name: file.name ?? "file",
|
|
124
|
+
...(typeof file.mimetype === "string" ? { type: file.mimetype } : {}),
|
|
125
|
+
...(typeof file.size === "number" ? { size: file.size } : {}),
|
|
126
|
+
ref: JSON.stringify({
|
|
127
|
+
id: file.id,
|
|
128
|
+
url: file.url_private_download ?? file.url_private,
|
|
129
|
+
}),
|
|
130
|
+
},
|
|
131
|
+
]
|
|
132
|
+
: [],
|
|
133
|
+
);
|
|
86
134
|
|
|
87
135
|
return {
|
|
88
136
|
id: `${event.channel}:${event.ts}`,
|
|
@@ -96,9 +144,114 @@ function eventOf(event: SlackEvent, user: string, channels: string[]): RelayEven
|
|
|
96
144
|
(file) =>
|
|
97
145
|
`File: ${(file.name ?? file.mimetype ?? "attachment").replace(/[\r\n]/g, " ")}`,
|
|
98
146
|
),
|
|
147
|
+
...(files.length > 0 ? { files } : {}),
|
|
99
148
|
};
|
|
100
149
|
}
|
|
101
150
|
|
|
151
|
+
/** Slack's file host, and the API's own (a mock's) when the owner set one: the bot token goes to no other host. */
|
|
152
|
+
function fileHost(url: URL, values: RelayValues): boolean {
|
|
153
|
+
const api = String(values.apiUrl ?? "");
|
|
154
|
+
|
|
155
|
+
return (
|
|
156
|
+
(url.protocol === "https:" && url.hostname === "files.slack.com") ||
|
|
157
|
+
(api !== "" && URL.canParse(api) && url.origin === new URL(api).origin)
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const escape = (text: string): string =>
|
|
162
|
+
text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
163
|
+
|
|
164
|
+
async function download(
|
|
165
|
+
context: Pick<RelayContext, "values" | "signal">,
|
|
166
|
+
file: RelayFile,
|
|
167
|
+
max: number,
|
|
168
|
+
): Promise<{ data: Uint8Array; type?: string }> {
|
|
169
|
+
const ref = JSON.parse(file.ref) as { id?: unknown; url?: unknown };
|
|
170
|
+
let url = typeof ref.url === "string" ? ref.url : undefined;
|
|
171
|
+
|
|
172
|
+
// An event may leave the link out (a file shared from another workspace): files.info has it.
|
|
173
|
+
if (url === undefined && typeof ref.id === "string") {
|
|
174
|
+
const info = await request<{ file?: SlackFile }>(context, "files.info", false, undefined, {
|
|
175
|
+
file: ref.id,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
url = info.file?.url_private_download ?? info.file?.url_private;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (url === undefined) {
|
|
182
|
+
throw new Error("Slack has no download for the attachment");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const response = await getFrom(
|
|
186
|
+
url,
|
|
187
|
+
(each) => fileHost(each, context.values),
|
|
188
|
+
{
|
|
189
|
+
headers: { Authorization: `Bearer ${context.values.botToken}` },
|
|
190
|
+
signal: context.signal,
|
|
191
|
+
},
|
|
192
|
+
"Slack's file host",
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
if (!response.ok) {
|
|
196
|
+
await response.body?.cancel();
|
|
197
|
+
|
|
198
|
+
throw new Error(`Slack's file host answered ${response.status}`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const type = response.headers.get("content-type") ?? undefined;
|
|
202
|
+
|
|
203
|
+
// Without the files:read scope, Slack answers with its sign-in page.
|
|
204
|
+
if (type?.startsWith("text/html") && !file.type?.startsWith("text/html")) {
|
|
205
|
+
await response.body?.cancel();
|
|
206
|
+
|
|
207
|
+
throw new Error("Slack sent a sign-in page: the bot token needs the files:read scope");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return { data: await bytesOf(response, max), ...(type === undefined ? {} : { type }) };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Upload one file (Slack's external upload): it shows only when `completeUploadExternal` shares it. */
|
|
214
|
+
async function upload(context: RequestContext, file: RelayOutFile): Promise<string> {
|
|
215
|
+
const { upload_url: url, file_id: id } = await request<{
|
|
216
|
+
upload_url?: string;
|
|
217
|
+
file_id?: string;
|
|
218
|
+
}>(context, "files.getUploadURLExternal", false, undefined, {
|
|
219
|
+
filename: file.name,
|
|
220
|
+
length: String(file.data.byteLength),
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
if (
|
|
224
|
+
typeof id !== "string" ||
|
|
225
|
+
typeof url !== "string" ||
|
|
226
|
+
!URL.canParse(url) ||
|
|
227
|
+
!fileHost(new URL(url), context.values)
|
|
228
|
+
) {
|
|
229
|
+
throw new Error("Slack gave an upload address that is not its own. Nothing was sent.");
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
let response: Response;
|
|
233
|
+
|
|
234
|
+
try {
|
|
235
|
+
// The address is signed for this one file: it needs no token.
|
|
236
|
+
response = await fetch(url, {
|
|
237
|
+
method: "POST",
|
|
238
|
+
headers: { "content-type": file.type },
|
|
239
|
+
body: new Blob([file.data as Uint8Array<ArrayBuffer>], { type: file.type }),
|
|
240
|
+
redirect: "error",
|
|
241
|
+
signal: AbortSignal.any([context.signal, AbortSignal.timeout(110_000)]),
|
|
242
|
+
});
|
|
243
|
+
await response.body?.cancel();
|
|
244
|
+
} catch {
|
|
245
|
+
throw new Error("Slack upload failed. Check the connection.");
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (!response.ok) {
|
|
249
|
+
throw new Error(`Slack upload failed: its file host answered ${response.status}.`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return id;
|
|
253
|
+
}
|
|
254
|
+
|
|
102
255
|
async function socketRun(
|
|
103
256
|
context: RelayContext,
|
|
104
257
|
url: string,
|
|
@@ -277,6 +430,9 @@ const slack: RelayConnector = {
|
|
|
277
430
|
}
|
|
278
431
|
}
|
|
279
432
|
},
|
|
433
|
+
// 10 files a reply, as Discord: Slack shares them in one message.
|
|
434
|
+
files: { max: 10, maxBytes: MAX_FILE },
|
|
435
|
+
fetch: download,
|
|
280
436
|
async reply(context, reply) {
|
|
281
437
|
const channel = reply.to?.channel ?? reply.channel ?? context.values.replyChannel;
|
|
282
438
|
const thread = reply.to?.thread ?? reply.thread;
|
|
@@ -285,13 +441,31 @@ const slack: RelayConnector = {
|
|
|
285
441
|
throw new Error("Choose a Slack reply channel.");
|
|
286
442
|
}
|
|
287
443
|
|
|
444
|
+
const files = reply.files ?? [];
|
|
445
|
+
|
|
446
|
+
// Files and text go as one message: the text is its comment.
|
|
447
|
+
if (files.length > 0) {
|
|
448
|
+
const ids: string[] = [];
|
|
449
|
+
|
|
450
|
+
for (const file of files) {
|
|
451
|
+
ids.push(await upload(context, file));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const text = escape(reply.text.slice(0, 4000));
|
|
455
|
+
|
|
456
|
+
await request(context, "files.completeUploadExternal", false, undefined, {
|
|
457
|
+
files: JSON.stringify(ids.map((id, index) => ({ id, title: files[index]!.name }))),
|
|
458
|
+
channel_id: String(channel),
|
|
459
|
+
...(thread ? { thread_ts: String(thread) } : {}),
|
|
460
|
+
...(text === "" ? {} : { initial_comment: text }),
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
return {};
|
|
464
|
+
}
|
|
465
|
+
|
|
288
466
|
const result = await request<{ ts: string }>(context, "chat.postMessage", false, {
|
|
289
467
|
channel,
|
|
290
|
-
text: reply.text
|
|
291
|
-
.slice(0, 4000)
|
|
292
|
-
.replace(/&/g, "&")
|
|
293
|
-
.replace(/</g, "<")
|
|
294
|
-
.replace(/>/g, ">"),
|
|
468
|
+
text: escape(reply.text.slice(0, 4000)),
|
|
295
469
|
...(thread ? { thread_ts: thread } : {}),
|
|
296
470
|
unfurl_links: false,
|
|
297
471
|
parse: "none",
|
|
@@ -1,4 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { bytesOf } from "../download.ts";
|
|
2
|
+
import {
|
|
3
|
+
RelayError,
|
|
4
|
+
type RelayConnector,
|
|
5
|
+
type RelayContext,
|
|
6
|
+
type RelayEvent,
|
|
7
|
+
type RelayFile,
|
|
8
|
+
} from "../types.ts";
|
|
9
|
+
|
|
10
|
+
const API = "https://api.telegram.org";
|
|
11
|
+
/** The Bot API's own limits: a bot uploads 50 MB, a photo 10 MB, and downloads 20 MB at most. */
|
|
12
|
+
const MAX_UPLOAD = 50 * 1024 * 1024;
|
|
13
|
+
const MAX_PHOTO = 10 * 1024 * 1024;
|
|
14
|
+
const MAX_DOWNLOAD = 20 * 1024 * 1024;
|
|
15
|
+
const PHOTOS = new Set(["image/png", "image/jpeg", "image/webp"]);
|
|
2
16
|
|
|
3
17
|
type RequestContext = Pick<RelayContext, "values" | "signal">;
|
|
4
18
|
interface TelegramUser {
|
|
@@ -18,12 +32,20 @@ interface Message {
|
|
|
18
32
|
entities?: { type: string; offset: number; length: number }[];
|
|
19
33
|
caption_entities?: { type: string; offset: number; length: number }[];
|
|
20
34
|
reply_to_message?: { from?: TelegramUser };
|
|
21
|
-
photo?:
|
|
22
|
-
document?:
|
|
23
|
-
video?:
|
|
24
|
-
audio?:
|
|
35
|
+
photo?: TelegramFile[];
|
|
36
|
+
document?: TelegramFile;
|
|
37
|
+
video?: TelegramFile;
|
|
38
|
+
audio?: TelegramFile;
|
|
39
|
+
voice?: TelegramFile;
|
|
40
|
+
animation?: TelegramFile;
|
|
25
41
|
sticker?: unknown;
|
|
26
42
|
}
|
|
43
|
+
interface TelegramFile {
|
|
44
|
+
file_id?: string;
|
|
45
|
+
file_name?: string;
|
|
46
|
+
mime_type?: string;
|
|
47
|
+
file_size?: number;
|
|
48
|
+
}
|
|
27
49
|
interface Update {
|
|
28
50
|
update_id: number;
|
|
29
51
|
message?: Message;
|
|
@@ -34,7 +56,7 @@ async function request<T>(
|
|
|
34
56
|
method: string,
|
|
35
57
|
query = "",
|
|
36
58
|
body?: unknown,
|
|
37
|
-
|
|
59
|
+
timeout = 20_000,
|
|
38
60
|
): Promise<T> {
|
|
39
61
|
let response: Response;
|
|
40
62
|
let data: {
|
|
@@ -45,16 +67,14 @@ async function request<T>(
|
|
|
45
67
|
};
|
|
46
68
|
|
|
47
69
|
try {
|
|
48
|
-
const
|
|
70
|
+
const form = body instanceof FormData;
|
|
49
71
|
|
|
50
|
-
response = await fetch(`${
|
|
72
|
+
response = await fetch(`${baseOf(context)}/bot${context.values.token}/${method}${query}`, {
|
|
51
73
|
method: body === undefined ? "GET" : "POST",
|
|
52
|
-
headers:
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
AbortSignal.timeout(longPoll ? 40_000 : 20_000),
|
|
57
|
-
]),
|
|
74
|
+
headers:
|
|
75
|
+
body === undefined || form ? undefined : { "content-type": "application/json" },
|
|
76
|
+
body: body === undefined ? undefined : form ? body : JSON.stringify(body),
|
|
77
|
+
signal: AbortSignal.any([context.signal, AbortSignal.timeout(timeout)]),
|
|
58
78
|
});
|
|
59
79
|
data = (await response.json().catch(() => ({}))) as typeof data;
|
|
60
80
|
} catch {
|
|
@@ -83,6 +103,11 @@ async function request<T>(
|
|
|
83
103
|
});
|
|
84
104
|
}
|
|
85
105
|
|
|
106
|
+
if (code === 400) {
|
|
107
|
+
// Telegram's own words can carry what Pi sent: say only that it refused.
|
|
108
|
+
throw Object.assign(new Error("Telegram refused the request."), { refused: true });
|
|
109
|
+
}
|
|
110
|
+
|
|
86
111
|
if (!response.ok || !data.ok || data.result === undefined) {
|
|
87
112
|
throw new Error("Telegram request failed. Check the bot configuration.");
|
|
88
113
|
}
|
|
@@ -90,6 +115,116 @@ async function request<T>(
|
|
|
90
115
|
return data.result;
|
|
91
116
|
}
|
|
92
117
|
|
|
118
|
+
const baseOf = (context: RequestContext): string =>
|
|
119
|
+
String(context.values.apiUrl || API).replace(/\/$/, "");
|
|
120
|
+
|
|
121
|
+
/** The files a message carries: the largest size of a photo, and each document, video, or sound. */
|
|
122
|
+
function filesOf(message: Message): RelayFile[] {
|
|
123
|
+
// Telegram lists a photo's sizes smallest first.
|
|
124
|
+
const largest = (message.photo ?? []).reduce<TelegramFile | undefined>(
|
|
125
|
+
(best, each) =>
|
|
126
|
+
best === undefined || (each.file_size ?? 0) >= (best.file_size ?? 0) ? each : best,
|
|
127
|
+
undefined,
|
|
128
|
+
);
|
|
129
|
+
const found: [TelegramFile | undefined, string, string | undefined][] = [
|
|
130
|
+
[largest, `photo-${message.message_id}.jpg`, "image/jpeg"],
|
|
131
|
+
// A GIF comes as `animation` and as `document` with the same file: list it once.
|
|
132
|
+
[message.animation === undefined ? message.document : undefined, "document", undefined],
|
|
133
|
+
[message.video, `video-${message.message_id}.mp4`, undefined],
|
|
134
|
+
[message.animation, `animation-${message.message_id}.mp4`, undefined],
|
|
135
|
+
[message.audio, `audio-${message.message_id}.mp3`, undefined],
|
|
136
|
+
[message.voice, `voice-${message.message_id}.ogg`, "audio/ogg"],
|
|
137
|
+
];
|
|
138
|
+
|
|
139
|
+
return found.flatMap(([file, name, type]) =>
|
|
140
|
+
typeof file?.file_id === "string"
|
|
141
|
+
? [
|
|
142
|
+
{
|
|
143
|
+
name: file.file_name ?? name,
|
|
144
|
+
...((file.mime_type ?? type) === undefined
|
|
145
|
+
? {}
|
|
146
|
+
: { type: file.mime_type ?? type }),
|
|
147
|
+
...(typeof file.file_size === "number" ? { size: file.file_size } : {}),
|
|
148
|
+
ref: file.file_id,
|
|
149
|
+
},
|
|
150
|
+
]
|
|
151
|
+
: [],
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Telegram's download puts the bot token in the address: no address, and no transport error, ever leaves this
|
|
157
|
+
* function.
|
|
158
|
+
*/
|
|
159
|
+
async function download(
|
|
160
|
+
context: Pick<RelayContext, "values" | "signal">,
|
|
161
|
+
file: RelayFile,
|
|
162
|
+
max: number,
|
|
163
|
+
): Promise<{ data: Uint8Array; type?: string }> {
|
|
164
|
+
const cap = Math.min(max, MAX_DOWNLOAD);
|
|
165
|
+
|
|
166
|
+
if ((file.size ?? 0) > cap) {
|
|
167
|
+
throw new Error(`Telegram lets a bot download ${Math.round(cap / 1048576)} MB at most`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const found = await request<{ file_path?: string; file_size?: number }>(
|
|
171
|
+
context,
|
|
172
|
+
"getFile",
|
|
173
|
+
`?${new URLSearchParams({ file_id: file.ref })}`,
|
|
174
|
+
);
|
|
175
|
+
const path = found.file_path;
|
|
176
|
+
|
|
177
|
+
if (
|
|
178
|
+
typeof path !== "string" ||
|
|
179
|
+
!/^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/.test(path) ||
|
|
180
|
+
path.split("/").some((part) => part === "..")
|
|
181
|
+
) {
|
|
182
|
+
throw new Error("Telegram gave no file to download");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if ((found.file_size ?? 0) > cap) {
|
|
186
|
+
throw new Error(`Telegram lets a bot download ${Math.round(cap / 1048576)} MB at most`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
let response: Response;
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
response = await fetch(`${baseOf(context)}/file/bot${context.values.token}/${path}`, {
|
|
193
|
+
redirect: "error",
|
|
194
|
+
signal: context.signal,
|
|
195
|
+
});
|
|
196
|
+
} catch {
|
|
197
|
+
throw new Error("Telegram download failed. Check the connection.");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (!response.ok) {
|
|
201
|
+
await response.body?.cancel().catch(() => {});
|
|
202
|
+
|
|
203
|
+
throw new Error(`Telegram's file server answered ${response.status}`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const type = response.headers.get("content-type") ?? undefined;
|
|
207
|
+
let data: Uint8Array;
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
data = await bytesOf(response, cap);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
String((error as Error).message).startsWith("the file is larger")
|
|
214
|
+
? `the file is larger than ${Math.round(cap / 1048576)} MB`
|
|
215
|
+
: "Telegram download failed. Check the connection.",
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Telegram serves most files as octet-stream: the type the message named is the better one.
|
|
220
|
+
return {
|
|
221
|
+
data,
|
|
222
|
+
...(type === undefined || (type === "application/octet-stream" && file.type)
|
|
223
|
+
? {}
|
|
224
|
+
: { type }),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
93
228
|
function eventOf(message: Message, bot: TelegramUser): RelayEvent {
|
|
94
229
|
const text = message.text ?? message.caption ?? "";
|
|
95
230
|
const entities = message.text === undefined ? message.caption_entities : message.entities;
|
|
@@ -107,6 +242,7 @@ function eventOf(message: Message, bot: TelegramUser): RelayEvent {
|
|
|
107
242
|
}
|
|
108
243
|
|
|
109
244
|
const author = message.from;
|
|
245
|
+
const files = filesOf(message);
|
|
110
246
|
const attachments: string[] = [];
|
|
111
247
|
|
|
112
248
|
if (message.photo?.length) {
|
|
@@ -141,6 +277,7 @@ function eventOf(message: Message, bot: TelegramUser): RelayEvent {
|
|
|
141
277
|
message.reply_to_message?.from?.id === bot.id,
|
|
142
278
|
at: message.date === undefined ? undefined : message.date * 1000,
|
|
143
279
|
attachments,
|
|
280
|
+
...(files.length > 0 ? { files } : {}),
|
|
144
281
|
};
|
|
145
282
|
}
|
|
146
283
|
|
|
@@ -150,6 +287,8 @@ const telegram: RelayConnector = {
|
|
|
150
287
|
description: "A Telegram bot: messages to it and in its groups. Make one with @BotFather.",
|
|
151
288
|
shape: "stream",
|
|
152
289
|
mentions: true,
|
|
290
|
+
files: { max: 10, maxBytes: MAX_UPLOAD },
|
|
291
|
+
fetch: download,
|
|
153
292
|
fields: [
|
|
154
293
|
{ name: "token", label: "Bot token", type: "secret", required: true },
|
|
155
294
|
{
|
|
@@ -195,7 +334,7 @@ const telegram: RelayConnector = {
|
|
|
195
334
|
"getUpdates",
|
|
196
335
|
`?${query}`,
|
|
197
336
|
undefined,
|
|
198
|
-
|
|
337
|
+
40_000,
|
|
199
338
|
);
|
|
200
339
|
const events = updates.flatMap((update) => {
|
|
201
340
|
const message = update.message;
|
|
@@ -223,22 +362,70 @@ const telegram: RelayConnector = {
|
|
|
223
362
|
}
|
|
224
363
|
|
|
225
364
|
const messageId = reply.to?.id.split(":").at(-1);
|
|
365
|
+
const answer =
|
|
366
|
+
messageId === undefined
|
|
367
|
+
? undefined
|
|
368
|
+
: { message_id: Number(messageId), allow_sending_without_reply: true };
|
|
369
|
+
const files = reply.files ?? [];
|
|
370
|
+
// A short text goes as the first file's caption; a long one as a message of its own first.
|
|
371
|
+
const caption = files.length > 0 && reply.text.length <= 1024 ? reply.text : undefined;
|
|
372
|
+
let first: number | undefined;
|
|
373
|
+
|
|
226
374
|
// Telegram has no idempotency key. The runtime records replies by key.
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
? {}
|
|
232
|
-
: {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
375
|
+
if (caption === undefined) {
|
|
376
|
+
const result = await request<{ message_id: number }>(context, "sendMessage", "", {
|
|
377
|
+
chat_id: channel,
|
|
378
|
+
text: reply.text.slice(0, 4096),
|
|
379
|
+
...(answer === undefined ? {} : { reply_parameters: answer }),
|
|
380
|
+
link_preview_options: { is_disabled: true },
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
first = result.message_id;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
for (const [index, file] of files.entries()) {
|
|
387
|
+
const send = async (photo: boolean) => {
|
|
388
|
+
const form = new FormData();
|
|
389
|
+
|
|
390
|
+
form.append("chat_id", String(channel));
|
|
391
|
+
|
|
392
|
+
if (index === 0 && caption !== undefined && caption !== "") {
|
|
393
|
+
form.append("caption", caption);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (answer !== undefined) {
|
|
397
|
+
form.append("reply_parameters", JSON.stringify(answer));
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
form.append(
|
|
401
|
+
photo ? "photo" : "document",
|
|
402
|
+
new Blob([file.data as Uint8Array<ArrayBuffer>], { type: file.type }),
|
|
403
|
+
file.name,
|
|
404
|
+
);
|
|
405
|
+
|
|
406
|
+
return request<{ message_id: number }>(
|
|
407
|
+
context,
|
|
408
|
+
photo ? "sendPhoto" : "sendDocument",
|
|
409
|
+
"",
|
|
410
|
+
form,
|
|
411
|
+
110_000,
|
|
412
|
+
);
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const photo = PHOTOS.has(file.type) && file.data.byteLength <= MAX_PHOTO;
|
|
416
|
+
// A photo Telegram refuses (too long, too wide) is not sent: it goes as a document.
|
|
417
|
+
const result = await send(photo).catch((error: unknown) => {
|
|
418
|
+
if (photo && (error as { refused?: unknown }).refused === true) {
|
|
419
|
+
return send(false);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
throw error;
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
first ??= result.message_id;
|
|
426
|
+
}
|
|
240
427
|
|
|
241
|
-
return { id: `${channel}:${
|
|
428
|
+
return first === undefined ? {} : { id: `${channel}:${first}` };
|
|
242
429
|
},
|
|
243
430
|
};
|
|
244
431
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Downloads for the connectors: only from the hosts a service names, and never more than the cap. */
|
|
2
|
+
|
|
3
|
+
/** At most `max` bytes of a response, or an error: a larger file is never read to its end. */
|
|
4
|
+
export async function bytesOf(response: Response, max: number): Promise<Uint8Array> {
|
|
5
|
+
if (Number(response.headers.get("content-length") ?? 0) > max) {
|
|
6
|
+
await response.body?.cancel();
|
|
7
|
+
|
|
8
|
+
throw new Error(`the file is larger than ${Math.round(max / 1048576)} MB`);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const parts: Uint8Array[] = [];
|
|
12
|
+
let size = 0;
|
|
13
|
+
|
|
14
|
+
for await (const part of (response.body ?? []) as AsyncIterable<Uint8Array>) {
|
|
15
|
+
size += part.byteLength;
|
|
16
|
+
|
|
17
|
+
if (size > max) {
|
|
18
|
+
throw new Error(`the file is larger than ${Math.round(max / 1048576)} MB`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
parts.push(part);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const data = new Uint8Array(size);
|
|
25
|
+
let at = 0;
|
|
26
|
+
|
|
27
|
+
for (const part of parts) {
|
|
28
|
+
data.set(part, at);
|
|
29
|
+
at += part.byteLength;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* GET `url`, and follow up to 3 redirects, each only to a host `allowed` takes: the headers (a token) go to no other
|
|
37
|
+
* host. Errors name no link.
|
|
38
|
+
*/
|
|
39
|
+
export async function getFrom(
|
|
40
|
+
url: string,
|
|
41
|
+
allowed: (url: URL) => boolean,
|
|
42
|
+
init: { headers?: Record<string, string>; signal: AbortSignal },
|
|
43
|
+
where: string,
|
|
44
|
+
): Promise<Response> {
|
|
45
|
+
let next = url;
|
|
46
|
+
|
|
47
|
+
for (let hop = 0; hop <= 3; hop += 1) {
|
|
48
|
+
const parsed = URL.canParse(next) ? new URL(next) : undefined;
|
|
49
|
+
|
|
50
|
+
if (parsed === undefined || !allowed(parsed)) {
|
|
51
|
+
throw new Error(`the attachment is not on ${where}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let response: Response;
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
response = await fetch(parsed, { ...init, redirect: "manual" });
|
|
58
|
+
} catch {
|
|
59
|
+
throw new Error(`the download from ${where} failed`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const location = response.headers.get("location");
|
|
63
|
+
|
|
64
|
+
if (![301, 302, 303, 307, 308].includes(response.status) || location === null) {
|
|
65
|
+
return response;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
await response.body?.cancel();
|
|
69
|
+
next = URL.canParse(location, parsed) ? new URL(location, parsed).href : "";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
throw new Error(`${where} redirected too often`);
|
|
73
|
+
}
|
|
@@ -5,6 +5,9 @@ import { basename, extname, relative, resolve, sep } from "node:path";
|
|
|
5
5
|
import { workspaceScheme } from "../../paths.ts";
|
|
6
6
|
import type { RelayOutFile } from "./types.ts";
|
|
7
7
|
|
|
8
|
+
/** What one reply sends in all, whatever the connector's caps: the relay holds it in memory while it sends. */
|
|
9
|
+
export const MAX_REPLY_BYTES = 100 * 1024 * 1024;
|
|
10
|
+
|
|
8
11
|
/** Where a fetched attachment goes, in the session's folder. */
|
|
9
12
|
export const FETCH_FOLDER = ".relay";
|
|
10
13
|
|
|
@@ -68,6 +71,7 @@ export async function readFiles(
|
|
|
68
71
|
const root = await folderOf(cwd);
|
|
69
72
|
const data = await realpath(dataDir).catch(() => resolve(dataDir));
|
|
70
73
|
const files: RelayOutFile[] = [];
|
|
74
|
+
let total = 0;
|
|
71
75
|
|
|
72
76
|
for (const path of paths) {
|
|
73
77
|
const shown = JSON.stringify(path).slice(0, 120);
|
|
@@ -114,12 +118,22 @@ export async function readFiles(
|
|
|
114
118
|
);
|
|
115
119
|
}
|
|
116
120
|
|
|
121
|
+
total += stat.size;
|
|
122
|
+
|
|
123
|
+
if (total > MAX_REPLY_BYTES) {
|
|
124
|
+
throw new Error(
|
|
125
|
+
`These files are more than ${MAX_REPLY_BYTES / 1048576} MB in all: the relay sends that much in one reply at most. Nothing was sent.`,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
117
129
|
const name = safeName(basename(real));
|
|
130
|
+
const data = await handle.readFile();
|
|
118
131
|
|
|
119
132
|
files.push({
|
|
120
133
|
name,
|
|
121
134
|
type: TYPES[extname(name).toLowerCase()] ?? "application/octet-stream",
|
|
122
|
-
|
|
135
|
+
// The file's own bytes, not a copy.
|
|
136
|
+
data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
|
|
123
137
|
});
|
|
124
138
|
} finally {
|
|
125
139
|
await handle.close();
|
|
@@ -8,6 +8,7 @@ import { chmod, mkdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import type { ConversationId } from "@earendil-works/pi-durable";
|
|
10
10
|
import type { InboxApi } from "../../host.ts";
|
|
11
|
+
import { MAX_REPLY_BYTES } from "./files.ts";
|
|
11
12
|
import {
|
|
12
13
|
type RelayConnector,
|
|
13
14
|
type RelayContext,
|
|
@@ -1049,6 +1050,12 @@ export class Relay {
|
|
|
1049
1050
|
);
|
|
1050
1051
|
}
|
|
1051
1052
|
|
|
1053
|
+
if (files.reduce((sum, file) => sum + file.data.byteLength, 0) > MAX_REPLY_BYTES) {
|
|
1054
|
+
throw new Error(
|
|
1055
|
+
`A reply sends ${mb(MAX_REPLY_BYTES)} of files in all at most: nothing was sent.`,
|
|
1056
|
+
);
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1052
1059
|
if (
|
|
1053
1060
|
files.length > (connector.files?.max ?? 0) ||
|
|
1054
1061
|
files.some((file) => file.data.byteLength > (connector.files?.maxBytes ?? 0))
|
|
@@ -1145,7 +1152,18 @@ export class Relay {
|
|
|
1145
1152
|
signal: AbortSignal.any([
|
|
1146
1153
|
signal,
|
|
1147
1154
|
this.#replies.signal,
|
|
1148
|
-
|
|
1155
|
+
// About 1 MB a second more for files: 100 MB has 222 seconds.
|
|
1156
|
+
AbortSignal.timeout(
|
|
1157
|
+
request.files?.length
|
|
1158
|
+
? 120_000 +
|
|
1159
|
+
Math.ceil(
|
|
1160
|
+
request.files.reduce(
|
|
1161
|
+
(sum, file) => sum + file.data.byteLength,
|
|
1162
|
+
0,
|
|
1163
|
+
) / 1024,
|
|
1164
|
+
)
|
|
1165
|
+
: 30_000,
|
|
1166
|
+
),
|
|
1149
1167
|
]),
|
|
1150
1168
|
log: (text) => this.log(`${config.name}: ${this.scrub(config, String(text))}`),
|
|
1151
1169
|
},
|
|
@@ -538,7 +538,7 @@ export default function createRelay(host: PocketHost, web?: ExtensionWeb) {
|
|
|
538
538
|
const relayReply = defineTool({
|
|
539
539
|
name: REPLY_TOOL,
|
|
540
540
|
description:
|
|
541
|
-
"Answer a message that came through the relay, in the place it came from (a chat, a channel). The people there read it. Give reply_to: the event id of the message you answer. Give connector when more than one delivers to this session. Give files to send images or files from this session's folder, where the connector can (Discord).",
|
|
541
|
+
"Answer a message that came through the relay, in the place it came from (a chat, a channel). The people there read it. Give reply_to: the event id of the message you answer. Give connector when more than one delivers to this session. Give files to send images or files from this session's folder, where the connector can (Discord, Slack, Telegram, Matrix).",
|
|
542
542
|
parameters: obj(
|
|
543
543
|
{
|
|
544
544
|
text: str({ description: "What to send: plain text, short." }),
|