@segmentstream/ontology 0.156.0 → 0.158.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +8 -7
  3. package/dist/agent-chat.d.ts +1 -1
  4. package/dist/agent-chat.js +8 -8
  5. package/dist/agent-draft.d.ts +287 -0
  6. package/dist/{agent-review.js → agent-draft.js} +103 -82
  7. package/dist/analyze.d.ts +1 -1
  8. package/dist/analyze.js +71 -14
  9. package/dist/channel-files.d.ts +70 -0
  10. package/dist/channel-files.js +58 -0
  11. package/dist/chat.d.ts +2 -2
  12. package/dist/earlier-entity-names.d.ts +35 -0
  13. package/dist/earlier-entity-names.js +88 -0
  14. package/dist/email.d.ts +2 -0
  15. package/dist/email.js +1 -0
  16. package/dist/gmail-send.d.ts +39 -0
  17. package/dist/gmail-send.js +179 -0
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +3 -1
  20. package/dist/migrate/plan.js +31 -2
  21. package/dist/permissions.d.ts +5 -5
  22. package/dist/permissions.js +13 -10
  23. package/dist/replicated-entities.d.ts +1 -1
  24. package/dist/replicated-entities.js +4 -1
  25. package/dist/replication/bigquery.d.ts +24 -2
  26. package/dist/replication/bigquery.js +72 -12
  27. package/dist/runtime/agents.d.ts +1 -1
  28. package/dist/runtime/agents.js +43 -38
  29. package/dist/runtime/chat-messages.d.ts +8 -7
  30. package/dist/runtime/chat-messages.js +11 -10
  31. package/dist/runtime/service-binding.js +1 -1
  32. package/dist/service/agent/protocol.d.ts +4 -4
  33. package/dist/service/agent/protocol.js +7 -7
  34. package/dist/service/agent/server.js +14 -9
  35. package/dist/service/chat/envelope.d.ts +12 -12
  36. package/dist/service/chat/review-delivery.js +23 -22
  37. package/dist/service/chat/review-revision.d.ts +1 -1
  38. package/dist/service/chat/review-revision.js +13 -13
  39. package/dist/service/mcp/runtime-policy.js +1 -1
  40. package/dist/service/mcp/server.js +9 -1
  41. package/dist/service/mcp/tools.js +1 -1
  42. package/dist/service/operations.js +11 -5
  43. package/dist/service/runtime-contract.d.ts +3 -3
  44. package/dist/service/service.d.ts +6 -0
  45. package/dist/service/service.js +21 -3
  46. package/dist/slack-files.d.ts +53 -0
  47. package/dist/slack-files.js +183 -0
  48. package/dist/slack.d.ts +3 -0
  49. package/dist/slack.js +2 -0
  50. package/dist/telegram-files.d.ts +81 -0
  51. package/dist/telegram-files.js +244 -0
  52. package/dist/telegram.d.ts +3 -1
  53. package/dist/telegram.js +2 -0
  54. package/dist/whatsapp-files.d.ts +54 -0
  55. package/dist/whatsapp-files.js +138 -0
  56. package/dist/whatsapp.d.ts +3 -0
  57. package/dist/whatsapp.js +2 -0
  58. package/dist/workspace-channel.d.ts +20 -0
  59. package/dist/workspace-channel.js +10 -0
  60. package/package.json +1 -1
  61. package/dist/agent-review.d.ts +0 -154
@@ -0,0 +1,53 @@
1
+ import { type ChannelFile, type ChannelPart, type ChannelRequest, type DefiniteFailure } from "./channel-files.js";
2
+ /**
3
+ * Slack's message with files, which the agent's `attachments_send` and the ontology's delivery of
4
+ * an approved draft both send, with Slack's external upload: each file's bytes go to the address
5
+ * `files.getUploadURLExternal` answers, then one `files.completeUploadExternal` shares all of them
6
+ * in the chat with the text, as one visible message. Nothing is visible until that share, so a
7
+ * file that fails to upload is left out without anything reaching the person. The Web API calls
8
+ * go on the connection's `web` API and the bytes on its `files` API.
9
+ */
10
+ /** The most bytes of one file a single connection request carries to Slack. */
11
+ export declare const SLACK_FILE_BYTES: number;
12
+ /** The most files one `files.completeUploadExternal` shares. */
13
+ export declare const SLACK_FILES_PER_MESSAGE = 10;
14
+ /** Why Slack cannot take this file through one connection request, or undefined when it can. */
15
+ export declare function slackFileRefusal(file: {
16
+ readonly size: number;
17
+ }): {
18
+ readonly code: "too_large" | "empty";
19
+ readonly message: string;
20
+ } | undefined;
21
+ /** What Slack's upload of the files and its share became. */
22
+ export interface SlackFilesResult {
23
+ /**
24
+ * Each file's upload in the order given, which nobody sees: Slack's file id, or why it did not
25
+ * upload. A file that did not upload is not shared.
26
+ */
27
+ readonly uploads: ReadonlyArray<{
28
+ readonly index: number;
29
+ readonly slackFileId: string;
30
+ } | {
31
+ readonly index: number;
32
+ readonly code: string;
33
+ readonly cause: unknown;
34
+ }>;
35
+ /** The one visible message, absent when no file uploaded. */
36
+ readonly share?: ChannelPart;
37
+ }
38
+ /**
39
+ * Uploads `files`, then shares those that uploaded in `channel`, in `threadTs` when given, with
40
+ * `text` as the message's text. The share is `sent` when Slack confirms it, `failed` when Slack
41
+ * refused it with a code that proves nothing was posted, otherwise `uncertain`. Nothing is
42
+ * retried.
43
+ */
44
+ export declare function sendSlackFiles(options: {
45
+ readonly request: ChannelRequest;
46
+ readonly channel: string;
47
+ readonly threadTs?: string;
48
+ readonly files: ReadonlyArray<ChannelFile & {
49
+ readonly index?: number;
50
+ }>;
51
+ readonly text?: string;
52
+ readonly definite?: DefiniteFailure;
53
+ }): Promise<SlackFilesResult>;
@@ -0,0 +1,183 @@
1
+ import { ChannelAnswerError, isRecord, replyJson, unrelayed, } from "./channel-files.js";
2
+ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
3
+ /**
4
+ * Slack's message with files, which the agent's `attachments_send` and the ontology's delivery of
5
+ * an approved draft both send, with Slack's external upload: each file's bytes go to the address
6
+ * `files.getUploadURLExternal` answers, then one `files.completeUploadExternal` shares all of them
7
+ * in the chat with the text, as one visible message. Nothing is visible until that share, so a
8
+ * file that fails to upload is left out without anything reaching the person. The Web API calls
9
+ * go on the connection's `web` API and the bytes on its `files` API.
10
+ */
11
+ /** The most bytes of one file a single connection request carries to Slack. */
12
+ export const SLACK_FILE_BYTES = MAXIMUM_CONNECTION_BODY_BYTES;
13
+ /** The most files one `files.completeUploadExternal` shares. */
14
+ export const SLACK_FILES_PER_MESSAGE = 10;
15
+ /** Where Slack's upload addresses are, which the connection's `files` API reaches. */
16
+ const SLACK_FILES = "https://files.slack.com/";
17
+ /**
18
+ * Slack's `ok: false` codes that do not prove the share was not posted: Slack says some of the
19
+ * operation may have succeeded before the error.
20
+ */
21
+ const POSSIBLY_POSTED = new Set([
22
+ "internal_error",
23
+ "fatal_error",
24
+ "service_unavailable",
25
+ ]);
26
+ /** Why Slack cannot take this file through one connection request, or undefined when it can. */
27
+ export function slackFileRefusal(file) {
28
+ if (file.size > SLACK_FILE_BYTES) {
29
+ return {
30
+ code: "too_large",
31
+ message: `The connection takes at most ${SLACK_FILE_BYTES} bytes per upload.`,
32
+ };
33
+ }
34
+ if (file.size === 0) {
35
+ return { code: "empty", message: "Slack cannot share an empty file." };
36
+ }
37
+ return undefined;
38
+ }
39
+ /** A Web API call's refusal code, by Slack's own error code. */
40
+ function refusalCode(error) {
41
+ return error === "missing_scope" || error === "not_in_channel" ? "forbidden" : "send_failed";
42
+ }
43
+ class SlackCallError extends Error {
44
+ code;
45
+ status;
46
+ answer;
47
+ name = "SlackCallError";
48
+ constructor(message, code, status,
49
+ /** Slack's answer, kept for operators. */
50
+ answer) {
51
+ super(message);
52
+ this.code = code;
53
+ this.status = status;
54
+ this.answer = answer;
55
+ }
56
+ }
57
+ /**
58
+ * Uploads `files`, then shares those that uploaded in `channel`, in `threadTs` when given, with
59
+ * `text` as the message's text. The share is `sent` when Slack confirms it, `failed` when Slack
60
+ * refused it with a code that proves nothing was posted, otherwise `uncertain`. Nothing is
61
+ * retried.
62
+ */
63
+ export async function sendSlackFiles(options) {
64
+ /** One Web API call; Slack's own refusal (`ok: false`) throws with its error code. */
65
+ async function call(method, contentType, body) {
66
+ const reply = await options.request({
67
+ api: "web",
68
+ method: "POST",
69
+ path: `/${method}`,
70
+ headers: [["content-type", contentType]],
71
+ body: new TextEncoder().encode(body),
72
+ });
73
+ const answer = replyJson(reply);
74
+ if (reply.status < 200 || reply.status >= 300 || !isRecord(answer) || answer.ok !== true) {
75
+ const code = isRecord(answer) && typeof answer.error === "string" ? answer.error : "";
76
+ throw new SlackCallError(`Slack refused ${method}${code === "" ? "" : `: ${code}`}.`, refusalCode(code), reply.status, answer);
77
+ }
78
+ return answer;
79
+ }
80
+ const uploads = [];
81
+ const uploaded = [];
82
+ for (const [position, file] of options.files.entries()) {
83
+ const index = file.index ?? position;
84
+ try {
85
+ const ticket = await call("files.getUploadURLExternal", "application/x-www-form-urlencoded", new URLSearchParams({
86
+ filename: file.filename,
87
+ length: String(file.bytes.byteLength),
88
+ }).toString());
89
+ if (typeof ticket.upload_url !== "string" ||
90
+ !ticket.upload_url.startsWith(SLACK_FILES) ||
91
+ typeof ticket.file_id !== "string") {
92
+ throw new SlackCallError("Slack answered no upload address.", "invalid_response", 200);
93
+ }
94
+ const reply = await options.request({
95
+ api: "files",
96
+ method: "POST",
97
+ path: `/${ticket.upload_url.slice(SLACK_FILES.length)}`,
98
+ headers: [["content-type", file.contentType]],
99
+ body: file.bytes,
100
+ });
101
+ if (reply.status < 200 || reply.status >= 300) {
102
+ throw new SlackCallError("Slack refused the file's bytes.", "send_failed", reply.status, replyJson(reply) ?? new TextDecoder().decode(reply.body).slice(0, 2000));
103
+ }
104
+ uploads.push({ index, slackFileId: ticket.file_id });
105
+ uploaded.push({ index, id: ticket.file_id, title: file.filename });
106
+ }
107
+ catch (error) {
108
+ uploads.push({
109
+ index,
110
+ code: error instanceof SlackCallError ? error.code : "send_failed",
111
+ cause: error,
112
+ });
113
+ }
114
+ }
115
+ if (uploaded.length === 0) {
116
+ return { uploads };
117
+ }
118
+ const part = { files: uploaded.map(({ index }) => index), text: options.text !== undefined };
119
+ let reply;
120
+ try {
121
+ reply = await options.request({
122
+ api: "web",
123
+ method: "POST",
124
+ path: "/files.completeUploadExternal",
125
+ headers: [["content-type", "application/json; charset=utf-8"]],
126
+ body: new TextEncoder().encode(JSON.stringify({
127
+ files: uploaded.map(({ id, title }) => ({ id, title })),
128
+ channel_id: options.channel,
129
+ ...(options.threadTs === undefined || options.threadTs === ""
130
+ ? {}
131
+ : { thread_ts: options.threadTs }),
132
+ ...(options.text === undefined ? {} : { initial_comment: options.text }),
133
+ })),
134
+ });
135
+ }
136
+ catch (error) {
137
+ return { uploads, share: unrelayed(part, error, options.definite) };
138
+ }
139
+ const answer = replyJson(reply);
140
+ if (reply.status >= 200 &&
141
+ reply.status < 300 &&
142
+ isRecord(answer) &&
143
+ answer.ok === true &&
144
+ Array.isArray(answer.files)) {
145
+ return {
146
+ uploads,
147
+ share: { ...part, status: "sent", messageIds: shareTs(answer.files, options.channel) },
148
+ };
149
+ }
150
+ const error = isRecord(answer) && typeof answer.error === "string" ? answer.error : "";
151
+ const definite = reply.status < 500 &&
152
+ isRecord(answer) &&
153
+ answer.ok === false &&
154
+ error !== "" &&
155
+ !POSSIBLY_POSTED.has(error);
156
+ return {
157
+ uploads,
158
+ share: {
159
+ ...part,
160
+ status: definite ? "failed" : "uncertain",
161
+ messageIds: [],
162
+ code: reply.status >= 200 && reply.status < 300 && answer !== undefined && error === ""
163
+ ? "invalid_response"
164
+ : refusalCode(error),
165
+ cause: new ChannelAnswerError(`Slack answered files.completeUploadExternal with status ${reply.status}` +
166
+ (error === "" ? "." : `: ${error}.`), reply.status, reply),
167
+ },
168
+ };
169
+ }
170
+ /** The message's `ts` in `channel`, when Slack's answer names the share. */
171
+ function shareTs(files, channel) {
172
+ for (const file of files) {
173
+ const shares = isRecord(file) && isRecord(file.shares) ? file.shares : {};
174
+ for (const scope of [shares.public, shares.private]) {
175
+ const list = isRecord(scope) ? scope[channel] : undefined;
176
+ const ts = Array.isArray(list) && isRecord(list[0]) ? list[0].ts : undefined;
177
+ if (typeof ts === "string" && ts !== "") {
178
+ return [ts];
179
+ }
180
+ }
181
+ }
182
+ return [];
183
+ }
package/dist/slack.d.ts CHANGED
@@ -13,3 +13,6 @@ export declare function escapeSlackMarkdown(text: string): string;
13
13
  * Markdown.
14
14
  */
15
15
  export declare function renderSlack(markdown: string, attribution: string, separator?: string): string;
16
+ export type { ChannelCall, ChannelFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
17
+ export { ChannelAnswerError } from "./channel-files.js";
18
+ export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, type SlackFilesResult, } from "./slack-files.js";
package/dist/slack.js CHANGED
@@ -21,3 +21,5 @@ export function renderSlack(markdown, attribution, separator = "\n\n") {
21
21
  ? markdown
22
22
  : `${markdown}${escapeSlackMarkdown(separator)}_${escapeSlackMarkdown(attribution)}_`;
23
23
  }
24
+ export { ChannelAnswerError } from "./channel-files.js";
25
+ export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, } from "./slack-files.js";
@@ -0,0 +1,81 @@
1
+ import { type ChannelFile, type ChannelPart, type ChannelRequest, type DefiniteFailure } from "./channel-files.js";
2
+ /**
3
+ * Telegram's message with files, which the agent's `attachments_send` and the ontology's delivery
4
+ * of an approved draft both send: the files in their order, as few messages as Telegram allows,
5
+ * the caption on the first. Photos go as photos and other files as documents; consecutive files of
6
+ * one type go together as an album of at most ten, as long as one request carries them. Each
7
+ * request is one multipart call on the connection's `bot` API.
8
+ */
9
+ /** The most bytes Telegram takes of a photo. */
10
+ export declare const TELEGRAM_PHOTO_BYTES: number;
11
+ /** The most bytes Telegram takes of a document a bot uploads. */
12
+ export declare const TELEGRAM_DOCUMENT_BYTES: number;
13
+ /** The most files one Telegram album carries. */
14
+ export declare const TELEGRAM_FILES_PER_MESSAGE = 10;
15
+ /** The most characters a Telegram caption has. */
16
+ export declare const TELEGRAM_CAPTION_LIMIT = 1024;
17
+ /** A formatting entity of Telegram's, in UTF-16 code units. */
18
+ export interface TelegramEntity {
19
+ readonly type: string;
20
+ readonly offset: number;
21
+ readonly length: number;
22
+ readonly url?: string;
23
+ readonly language?: string;
24
+ readonly unix_time?: number;
25
+ readonly date_time_format?: string;
26
+ }
27
+ /** Visible text and the entities that format it. */
28
+ export interface TelegramFormattedText {
29
+ readonly text: string;
30
+ readonly entities: ReadonlyArray<TelegramEntity>;
31
+ }
32
+ /** How Telegram sends a file of this content type: as a photo or as a document. */
33
+ export declare function telegramFileType(contentType: string): "photo" | "document";
34
+ /**
35
+ * Why Telegram cannot take this file through one connection request, or undefined when it can:
36
+ * `too_large` past Telegram's bound for its type or the connection's request bound, `empty` for no
37
+ * bytes.
38
+ */
39
+ export declare function telegramFileRefusal(file: {
40
+ readonly contentType: string;
41
+ readonly size: number;
42
+ }): {
43
+ readonly code: "too_large" | "empty";
44
+ readonly message: string;
45
+ } | undefined;
46
+ /** The most bytes of one file a single connection request can carry to Telegram. */
47
+ export declare function telegramFileBytes(contentType: string): number;
48
+ /**
49
+ * The same text with every line break written CRLF, and its entities moved to match. A multipart
50
+ * form sends a text field's line breaks as CRLF, and Telegram counts the CR in entity offsets, so a
51
+ * caption sent in one keeps its links and formatting only once its line breaks are CRLF already.
52
+ */
53
+ export declare function withCrlfLineBreaks<Text extends TelegramFormattedText>(message: Text): Text;
54
+ /**
55
+ * Whether Telegram refused a message only for its formatting entities, which it then takes without
56
+ * them. Only this definite refusal permits a second request; an unknown failure never does.
57
+ */
58
+ export declare function telegramFormattingRefused(status: number, body: unknown): boolean;
59
+ /** Where the files go: the chat, its forum topic, and the message they answer. */
60
+ export interface TelegramFilesTarget {
61
+ readonly chatId: string;
62
+ /** A forum topic's id; absent outside one. */
63
+ readonly messageThreadId?: string;
64
+ readonly replyTo?: string | number;
65
+ }
66
+ /**
67
+ * Sends `files` to `target` in their order, `caption` on the first message Telegram takes. Each
68
+ * album is one request and one part: `sent` when Telegram names its messages, `failed` when it
69
+ * refused them (`too_large` for 413, `forbidden` for 403, `send_failed` otherwise) or a request
70
+ * could not be built, `uncertain` when its answer proves neither. A refusal of the caption's
71
+ * formatting alone sends the album again without it. Nothing is retried otherwise.
72
+ */
73
+ export declare function sendTelegramFiles(options: {
74
+ readonly request: ChannelRequest;
75
+ readonly target: TelegramFilesTarget;
76
+ readonly files: ReadonlyArray<ChannelFile & {
77
+ readonly index?: number;
78
+ }>;
79
+ readonly caption?: TelegramFormattedText;
80
+ readonly definite?: DefiniteFailure;
81
+ }): Promise<ReadonlyArray<ChannelPart>>;
@@ -0,0 +1,244 @@
1
+ import { ChannelAnswerError, isRecord, replyJson, unrelayed, } from "./channel-files.js";
2
+ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
3
+ /**
4
+ * Telegram's message with files, which the agent's `attachments_send` and the ontology's delivery
5
+ * of an approved draft both send: the files in their order, as few messages as Telegram allows,
6
+ * the caption on the first. Photos go as photos and other files as documents; consecutive files of
7
+ * one type go together as an album of at most ten, as long as one request carries them. Each
8
+ * request is one multipart call on the connection's `bot` API.
9
+ */
10
+ /** The most bytes Telegram takes of a photo. */
11
+ export const TELEGRAM_PHOTO_BYTES = 10 * 1024 * 1024;
12
+ /** The most bytes Telegram takes of a document a bot uploads. */
13
+ export const TELEGRAM_DOCUMENT_BYTES = 50 * 1024 * 1024;
14
+ /** The most files one Telegram album carries. */
15
+ export const TELEGRAM_FILES_PER_MESSAGE = 10;
16
+ /** The most characters a Telegram caption has. */
17
+ export const TELEGRAM_CAPTION_LIMIT = 1024;
18
+ /** The content types Telegram shows as photos. */
19
+ const PHOTOS = new Set(["image/jpeg", "image/png", "image/webp"]);
20
+ /** How Telegram sends a file of this content type: as a photo or as a document. */
21
+ export function telegramFileType(contentType) {
22
+ return PHOTOS.has(contentType.toLowerCase().split(";")[0].trim()) ? "photo" : "document";
23
+ }
24
+ /**
25
+ * Why Telegram cannot take this file through one connection request, or undefined when it can:
26
+ * `too_large` past Telegram's bound for its type or the connection's request bound, `empty` for no
27
+ * bytes.
28
+ */
29
+ export function telegramFileRefusal(file) {
30
+ const type = telegramFileType(file.contentType);
31
+ const maximum = type === "photo" ? TELEGRAM_PHOTO_BYTES : TELEGRAM_DOCUMENT_BYTES;
32
+ if (file.size > maximum) {
33
+ return { code: "too_large", message: `Telegram's ${type} limit is ${maximum} bytes.` };
34
+ }
35
+ if (file.size > MAXIMUM_CONNECTION_BODY_BYTES) {
36
+ return { code: "too_large", message: TELEGRAM_REQUEST_LIMIT };
37
+ }
38
+ if (file.size === 0) {
39
+ return { code: "empty", message: "Telegram cannot send an empty file." };
40
+ }
41
+ return undefined;
42
+ }
43
+ /** The most bytes of one file a single connection request can carry to Telegram. */
44
+ export function telegramFileBytes(contentType) {
45
+ return Math.min(telegramFileType(contentType) === "photo" ? TELEGRAM_PHOTO_BYTES : TELEGRAM_DOCUMENT_BYTES, MAXIMUM_CONNECTION_BODY_BYTES);
46
+ }
47
+ const TELEGRAM_REQUEST_LIMIT = `The multipart upload exceeds the connection's ` +
48
+ `${MAXIMUM_CONNECTION_BODY_BYTES}-byte request limit.`;
49
+ /**
50
+ * The same text with every line break written CRLF, and its entities moved to match. A multipart
51
+ * form sends a text field's line breaks as CRLF, and Telegram counts the CR in entity offsets, so a
52
+ * caption sent in one keeps its links and formatting only once its line breaks are CRLF already.
53
+ */
54
+ export function withCrlfLineBreaks(message) {
55
+ if (!/[\r\n]/u.test(message.text)) {
56
+ return message;
57
+ }
58
+ let text = "";
59
+ // Where each index of the original text lands in the new one, with one past the end.
60
+ const at = [];
61
+ for (let index = 0; index < message.text.length; index++) {
62
+ const char = message.text[index];
63
+ at.push(text.length);
64
+ if (char === "\r" && message.text[index + 1] === "\n") {
65
+ text += "\r\n";
66
+ at.push(text.length - 1);
67
+ index++;
68
+ }
69
+ else if (char === "\r" || char === "\n") {
70
+ text += "\r\n";
71
+ }
72
+ else {
73
+ text += char;
74
+ }
75
+ }
76
+ at.push(text.length);
77
+ return {
78
+ ...message,
79
+ text,
80
+ entities: message.entities.map((entity) => {
81
+ const start = at[entity.offset] ?? text.length;
82
+ const end = at[entity.offset + entity.length] ?? text.length;
83
+ return { ...entity, offset: start, length: end - start };
84
+ }),
85
+ };
86
+ }
87
+ /**
88
+ * Whether Telegram refused a message only for its formatting entities, which it then takes without
89
+ * them. Only this definite refusal permits a second request; an unknown failure never does.
90
+ */
91
+ export function telegramFormattingRefused(status, body) {
92
+ return (status === 400 &&
93
+ isRecord(body) &&
94
+ body.ok === false &&
95
+ typeof body.description === "string" &&
96
+ (/can't parse entities|cannot parse entities|entity (?:bounds|offset|length)|entities (?:are|too)/iu.test(body.description) ||
97
+ /unsupported (?:start tag|parse mode)/iu.test(body.description)));
98
+ }
99
+ /** One multipart request of files: one file by its type's method, several as an album. */
100
+ async function multipart(target, files, caption) {
101
+ const form = new FormData();
102
+ const blob = (upload) => new Blob([Buffer.from(upload.file.bytes)], { type: upload.file.contentType });
103
+ form.set("chat_id", target.chatId);
104
+ if (target.messageThreadId !== undefined && /^\d+$/u.test(target.messageThreadId)) {
105
+ form.set("message_thread_id", target.messageThreadId);
106
+ }
107
+ if (target.replyTo !== undefined) {
108
+ form.set("reply_parameters", JSON.stringify({ message_id: Number(target.replyTo) }));
109
+ }
110
+ if (files.length === 1) {
111
+ const upload = files[0];
112
+ form.set(upload.type, blob(upload), upload.file.filename);
113
+ if (caption !== undefined) {
114
+ // The form sends its line breaks as CRLF anyway; the entities must count them so.
115
+ const sent = withCrlfLineBreaks(caption);
116
+ form.set("caption", sent.text);
117
+ if (sent.entities.length > 0) {
118
+ form.set("caption_entities", JSON.stringify(sent.entities));
119
+ }
120
+ }
121
+ }
122
+ else {
123
+ form.set("media", JSON.stringify(files.map((upload, index) => ({
124
+ type: upload.type,
125
+ media: `attach://file${index}`,
126
+ ...(index === 0 && caption !== undefined
127
+ ? {
128
+ caption: caption.text,
129
+ ...(caption.entities.length > 0 ? { caption_entities: caption.entities } : {}),
130
+ }
131
+ : {}),
132
+ }))));
133
+ files.forEach((upload, index) => form.set(`file${index}`, blob(upload), upload.file.filename));
134
+ }
135
+ // A request serializes the form and names its boundary in the content type together.
136
+ const request = new Request("https://telegram.invalid/", { method: "POST", body: form });
137
+ return {
138
+ method: files.length > 1
139
+ ? "sendMediaGroup"
140
+ : files[0].type === "photo"
141
+ ? "sendPhoto"
142
+ : "sendDocument",
143
+ contentType: request.headers.get("content-type") ?? "multipart/form-data",
144
+ body: new Uint8Array(await request.arrayBuffer()),
145
+ };
146
+ }
147
+ /** The message ids Telegram's answer to a batch names, one per file, or undefined. */
148
+ function messageIds(answer, count) {
149
+ if (!isRecord(answer) || answer.ok !== true) {
150
+ return undefined;
151
+ }
152
+ const messages = count === 1 ? [answer.result] : answer.result;
153
+ return Array.isArray(messages) &&
154
+ messages.length === count &&
155
+ messages.every((message) => isRecord(message) && Number.isSafeInteger(message.message_id))
156
+ ? messages.map((message) => String(message.message_id))
157
+ : undefined;
158
+ }
159
+ /**
160
+ * Sends `files` to `target` in their order, `caption` on the first message Telegram takes. Each
161
+ * album is one request and one part: `sent` when Telegram names its messages, `failed` when it
162
+ * refused them (`too_large` for 413, `forbidden` for 403, `send_failed` otherwise) or a request
163
+ * could not be built, `uncertain` when its answer proves neither. A refusal of the caption's
164
+ * formatting alone sends the album again without it. Nothing is retried otherwise.
165
+ */
166
+ export async function sendTelegramFiles(options) {
167
+ const uploads = options.files.map((file, position) => ({
168
+ index: file.index ?? position,
169
+ type: telegramFileType(file.contentType),
170
+ file,
171
+ }));
172
+ const parts = [];
173
+ let caption = options.caption;
174
+ let cursor = 0;
175
+ while (cursor < uploads.length) {
176
+ const batch = [uploads[cursor++]];
177
+ let built = await multipart(options.target, batch, caption);
178
+ // An album holds files of one type only; the request's order is kept.
179
+ while (cursor < uploads.length &&
180
+ batch.length < TELEGRAM_FILES_PER_MESSAGE &&
181
+ uploads[cursor].type === batch[0].type) {
182
+ const candidate = await multipart(options.target, [...batch, uploads[cursor]], caption);
183
+ if (candidate.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
184
+ break;
185
+ }
186
+ batch.push(uploads[cursor++]);
187
+ built = candidate;
188
+ }
189
+ const part = { files: batch.map((upload) => upload.index), text: caption !== undefined };
190
+ if (built.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
191
+ parts.push({
192
+ ...part,
193
+ status: "failed",
194
+ messageIds: [],
195
+ code: "too_large",
196
+ cause: new Error(TELEGRAM_REQUEST_LIMIT),
197
+ });
198
+ continue;
199
+ }
200
+ const send = (message) => options.request({
201
+ api: "bot",
202
+ method: "POST",
203
+ path: `/${message.method}`,
204
+ headers: [["content-type", message.contentType]],
205
+ body: message.body,
206
+ });
207
+ let reply;
208
+ try {
209
+ reply = await send(built);
210
+ if (caption !== undefined &&
211
+ caption.entities.length > 0 &&
212
+ telegramFormattingRefused(reply.status, replyJson(reply))) {
213
+ caption = { text: caption.text, entities: [] };
214
+ reply = await send(await multipart(options.target, batch, caption));
215
+ }
216
+ }
217
+ catch (error) {
218
+ parts.push(unrelayed(part, error, options.definite));
219
+ continue;
220
+ }
221
+ const answer = replyJson(reply);
222
+ const ids = reply.status >= 200 && reply.status < 300 ? messageIds(answer, batch.length) : [];
223
+ if (ids !== undefined && ids.length === batch.length) {
224
+ parts.push({ ...part, status: "sent", messageIds: ids });
225
+ caption = undefined;
226
+ continue;
227
+ }
228
+ const refused = reply.status >= 400 && reply.status < 500 && isRecord(answer) && answer.ok === false;
229
+ parts.push({
230
+ ...part,
231
+ status: refused ? "failed" : "uncertain",
232
+ messageIds: [],
233
+ code: ids === undefined && reply.status >= 200 && reply.status < 300
234
+ ? "invalid_response"
235
+ : reply.status === 413
236
+ ? "too_large"
237
+ : reply.status === 403
238
+ ? "forbidden"
239
+ : "send_failed",
240
+ cause: new ChannelAnswerError(`Telegram answered ${built.method} with status ${reply.status}.`, reply.status, reply),
241
+ });
242
+ }
243
+ return parts;
244
+ }
@@ -60,4 +60,6 @@ export declare function telegramStartParam(page: string): string | undefined;
60
60
  export declare function miniAppLink(url: string, origins: ReadonlySet<string>, botUsername: string): string | undefined;
61
61
  /** A username Telegram accepts in a `t.me` link; any other leaves every link as it is. */
62
62
  export declare function isTelegramBotUsername(username: string): boolean;
63
- export {};
63
+ export type { ChannelCall, ChannelFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
64
+ export { ChannelAnswerError } from "./channel-files.js";
65
+ export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_PHOTO_BYTES, type TelegramEntity, type TelegramFilesTarget, type TelegramFormattedText, } from "./telegram-files.js";
package/dist/telegram.js CHANGED
@@ -306,3 +306,5 @@ export function miniAppLink(url, origins, botUsername) {
306
306
  export function isTelegramBotUsername(username) {
307
307
  return /^[A-Za-z0-9_]{1,64}$/u.test(username);
308
308
  }
309
+ export { ChannelAnswerError } from "./channel-files.js";
310
+ export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_PHOTO_BYTES, } from "./telegram-files.js";
@@ -0,0 +1,54 @@
1
+ import { type ChannelPart, type ChannelRequest, type DefiniteFailure } from "./channel-files.js";
2
+ /**
3
+ * WhatsApp's message with files, which the agent's `attachments_send` and the ontology's delivery
4
+ * of an approved draft both send: one message per file, by a link WhatsApp fetches the file from,
5
+ * the caption on the first. A caption too long for one, or files that start with audio, which takes
6
+ * none, go first as a text message of their own. Each message is one `POST /phone/messages` on the
7
+ * connection's `graph` API, as the workspace's number.
8
+ */
9
+ /** Meta's message types a file is sent as. */
10
+ export type WhatsAppFileType = "image" | "audio" | "video" | "document";
11
+ /** The most bytes WhatsApp fetches of a file of each type. */
12
+ export declare const WHATSAPP_FILE_BYTES: Readonly<Record<WhatsAppFileType, number>>;
13
+ /** The most characters a WhatsApp caption has. */
14
+ export declare const WHATSAPP_CAPTION_LIMIT = 1024;
15
+ /** How WhatsApp sends a file of this content type. */
16
+ export declare function whatsappFileType(contentType: string): WhatsAppFileType;
17
+ /** Why WhatsApp cannot take this file, or undefined when it can. */
18
+ export declare function whatsappFileRefusal(file: {
19
+ readonly contentType: string;
20
+ readonly size: number;
21
+ }): {
22
+ readonly code: "too_large" | "empty";
23
+ readonly message: string;
24
+ } | undefined;
25
+ /**
26
+ * A file WhatsApp fetches by its link. A link valid only briefly is better resolved just before
27
+ * its message: a function is called then, and when it throws, that file's message is not sent and
28
+ * its part fails with `unavailable`.
29
+ */
30
+ export interface WhatsAppLinkedFile {
31
+ readonly link: string | (() => Promise<string>);
32
+ readonly filename: string;
33
+ readonly contentType: string;
34
+ readonly index?: number;
35
+ }
36
+ /** A message WhatsApp accepted, with Meta's type of it and its text or caption. */
37
+ export interface WhatsAppSentPart extends ChannelPart {
38
+ readonly type: WhatsAppFileType | "text";
39
+ }
40
+ /**
41
+ * Sends one message per file to `recipient`, `{ to }` by phone number or `{ recipient }` by
42
+ * business-scoped user id, `caption` with the first; `replyTo` answers a message with the first.
43
+ * A caption sent on its own is never put on a file, whatever became of it.
44
+ * Each message is a part: `sent` when Meta names it, `failed` when Meta refused it with an error
45
+ * code, otherwise `uncertain`. Nothing is retried, and a failed message does not stop the next.
46
+ */
47
+ export declare function sendWhatsAppFiles(options: {
48
+ readonly request: ChannelRequest;
49
+ readonly recipient: Readonly<Record<string, string>>;
50
+ readonly files: ReadonlyArray<WhatsAppLinkedFile>;
51
+ readonly caption?: string;
52
+ readonly replyTo?: string;
53
+ readonly definite?: DefiniteFailure;
54
+ }): Promise<ReadonlyArray<WhatsAppSentPart>>;