@segmentstream/ontology 0.156.1 → 0.159.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 (67) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +12 -9
  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/apply.d.ts +3 -2
  21. package/dist/migrate/apply.js +11 -4
  22. package/dist/migrate/plan.js +42 -8
  23. package/dist/migrate/preview.js +4 -1
  24. package/dist/permissions.d.ts +5 -5
  25. package/dist/permissions.js +13 -10
  26. package/dist/replicated-entities.d.ts +1 -1
  27. package/dist/replicated-entities.js +4 -1
  28. package/dist/replication/bigquery.d.ts +24 -2
  29. package/dist/replication/bigquery.js +72 -12
  30. package/dist/runtime/agents.d.ts +1 -1
  31. package/dist/runtime/agents.js +43 -38
  32. package/dist/runtime/chat-messages.d.ts +2 -2
  33. package/dist/runtime/chat-messages.js +1 -1
  34. package/dist/runtime/service-binding.js +1 -1
  35. package/dist/service/agent/protocol.d.ts +4 -4
  36. package/dist/service/agent/protocol.js +7 -7
  37. package/dist/service/agent/server.js +14 -9
  38. package/dist/service/chat/envelope.d.ts +12 -12
  39. package/dist/service/chat/review-delivery.js +23 -22
  40. package/dist/service/chat/review-revision.d.ts +1 -1
  41. package/dist/service/chat/review-revision.js +13 -13
  42. package/dist/service/mcp/runtime-policy.js +1 -1
  43. package/dist/service/mcp/server.js +9 -1
  44. package/dist/service/mcp/tools.js +1 -1
  45. package/dist/service/operations.js +11 -5
  46. package/dist/service/runtime-contract.d.ts +3 -3
  47. package/dist/service/service.d.ts +6 -0
  48. package/dist/service/service.js +21 -3
  49. package/dist/slack-files.d.ts +53 -0
  50. package/dist/slack-files.js +183 -0
  51. package/dist/slack.d.ts +3 -0
  52. package/dist/slack.js +2 -0
  53. package/dist/storage/attachments.js +15 -16
  54. package/dist/storage/tables.d.ts +18 -11
  55. package/dist/storage/tables.js +87 -12
  56. package/dist/telegram-files.d.ts +81 -0
  57. package/dist/telegram-files.js +244 -0
  58. package/dist/telegram.d.ts +3 -1
  59. package/dist/telegram.js +2 -0
  60. package/dist/whatsapp-files.d.ts +54 -0
  61. package/dist/whatsapp-files.js +138 -0
  62. package/dist/whatsapp.d.ts +3 -0
  63. package/dist/whatsapp.js +2 -0
  64. package/dist/workspace-channel.d.ts +20 -0
  65. package/dist/workspace-channel.js +10 -0
  66. package/package.json +1 -1
  67. package/dist/agent-review.d.ts +0 -154
@@ -1,7 +1,14 @@
1
1
  /** Storage metadata lives in the ontology database and is migrated by its SDK. */
2
2
  export declare const BLOB_TABLES_DDL: ReadonlyArray<string>;
3
- /** The agent's temporary attachments, beside the blob tables whose storage they share. */
4
- export declare const ATTACHMENTS_TABLE = "_agent_attachments";
3
+ /** The chats' temporary attachments, beside the blob tables whose storage they share. */
4
+ export declare const ATTACHMENTS_TABLE = "_chat_attachments";
5
+ /**
6
+ * @legacy ontology.agent-attachments-view
7
+ * The table's earlier name. A database migrated by this SDK keeps it as a view of
8
+ * {@link ATTACHMENTS_TABLE} with the chat column named `conversation`, so that a workspace still
9
+ * running an earlier ontology SDK reads and writes the same rows.
10
+ */
11
+ export declare const LEGACY_ATTACHMENTS_TABLE = "_agent_attachments";
5
12
  /**
6
13
  * Where an attachment comes from: a chat message on a channel, `channel` for a channel the
7
14
  * workspace defines in its own code, or a file the agent produced in its sandbox and stores so
@@ -9,17 +16,17 @@ export declare const ATTACHMENTS_TABLE = "_agent_attachments";
9
16
  */
10
17
  export declare const ATTACHMENT_SOURCES: readonly ["telegram", "slack", "whatsapp", "email", "sandbox", "channel"];
11
18
  /** The check that limits `source` to {@link ATTACHMENT_SOURCES}; its name is PostgreSQL's default. */
12
- export declare const ATTACHMENT_SOURCE_CHECK = "_agent_attachments_source_check";
19
+ export declare const ATTACHMENT_SOURCE_CHECK = "_chat_attachments_source_check";
13
20
  /**
14
- * A file a member sent the app's agent: platform metadata, never an ontology record. The bytes are
15
- * a `_blobs` revision in the same storage as uploads; the row binds them to their owner, the chat
16
- * and, for private chats, the first agent session that reads them. Group access follows the chat
17
- * registry's current members. Attachments expire 24 hours after receipt unless promoted, or, on a
18
- * channel that keeps its chats' files, with their messages.
21
+ * A file that arrived in a chat or that the agent made in its sandbox: platform metadata, never an
22
+ * ontology record. The bytes are a `_blobs` revision in the same storage as uploads; the row binds
23
+ * them to their owner, the chat (`provider:external_id`) and, for private chats, the first agent
24
+ * session that reads them. Group access follows the chat registry's current members. Attachments
25
+ * expire 24 hours after receipt unless promoted, or, on a channel that keeps its chats' files,
26
+ * with their messages.
19
27
  *
20
- * @legacy ontology.attachment-conversation-column
21
- * The column `conversation` holds the chat, `provider:external_id`: SDKs sharing this database
22
- * still read and write it under that name.
28
+ * The first statement renames the table an earlier SDK created; the last keeps its earlier name
29
+ * as a view for SDKs that share the database.
23
30
  */
24
31
  export declare const ATTACHMENT_TABLES_DDL: ReadonlyArray<string>;
25
32
  /** The pending and started workflow starts of action triggers, beside the blob action results. */
@@ -53,8 +53,15 @@ export const BLOB_TABLES_DDL = [
53
53
  PRIMARY KEY ("principal_id", "key")
54
54
  )`,
55
55
  ];
56
- /** The agent's temporary attachments, beside the blob tables whose storage they share. */
57
- export const ATTACHMENTS_TABLE = "_agent_attachments";
56
+ /** The chats' temporary attachments, beside the blob tables whose storage they share. */
57
+ export const ATTACHMENTS_TABLE = "_chat_attachments";
58
+ /**
59
+ * @legacy ontology.agent-attachments-view
60
+ * The table's earlier name. A database migrated by this SDK keeps it as a view of
61
+ * {@link ATTACHMENTS_TABLE} with the chat column named `conversation`, so that a workspace still
62
+ * running an earlier ontology SDK reads and writes the same rows.
63
+ */
64
+ export const LEGACY_ATTACHMENTS_TABLE = "_agent_attachments";
58
65
  /**
59
66
  * Where an attachment comes from: a chat message on a channel, `channel` for a channel the
60
67
  * workspace defines in its own code, or a file the agent produced in its sandbox and stores so
@@ -71,24 +78,86 @@ export const ATTACHMENT_SOURCES = [
71
78
  /** The check that limits `source` to {@link ATTACHMENT_SOURCES}; its name is PostgreSQL's default. */
72
79
  export const ATTACHMENT_SOURCE_CHECK = `${ATTACHMENTS_TABLE}_source_check`;
73
80
  const SOURCE_CHECK = `CHECK ("source" IN (${ATTACHMENT_SOURCES.map((source) => `'${source}'`).join(", ")}))`;
81
+ /** The columns every SDK since the table's first release reads and writes, in table order. */
82
+ const LEGACY_ATTACHMENT_COLUMNS = [
83
+ "id",
84
+ "blob_id",
85
+ "branch_id",
86
+ "owner_id",
87
+ "chat",
88
+ "session_id",
89
+ "source",
90
+ "source_ref",
91
+ "filename",
92
+ "content_type",
93
+ "size",
94
+ "sha256",
95
+ "state",
96
+ "provider_upload_id",
97
+ "promotion",
98
+ "created_at",
99
+ "expires_at",
100
+ "removed_at",
101
+ ];
102
+ /**
103
+ * @legacy ontology.agent-attachments-view
104
+ * Renames a table an earlier SDK created as `_agent_attachments`, its `conversation` column and
105
+ * the constraints and indexes PostgreSQL named after both, in place: rows, ids and blob
106
+ * references stay as they are. Does nothing once the table has its name.
107
+ */
108
+ const RENAME_LEGACY_ATTACHMENTS = `DO $rename$
109
+ DECLARE
110
+ item record;
111
+ BEGIN
112
+ IF to_regclass('"${ATTACHMENTS_TABLE}"') IS NOT NULL OR NOT EXISTS (
113
+ SELECT 1 FROM pg_catalog.pg_class t
114
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
115
+ WHERE n.nspname = current_schema() AND t.relname = '${LEGACY_ATTACHMENTS_TABLE}'
116
+ AND t.relkind = 'r'
117
+ ) THEN
118
+ RETURN;
119
+ END IF;
120
+ ALTER TABLE "${LEGACY_ATTACHMENTS_TABLE}" RENAME TO "${ATTACHMENTS_TABLE}";
121
+ ALTER TABLE "${ATTACHMENTS_TABLE}" RENAME COLUMN "conversation" TO "chat";
122
+ FOR item IN
123
+ SELECT c.conname AS name FROM pg_catalog.pg_constraint c
124
+ WHERE c.conrelid = '"${ATTACHMENTS_TABLE}"'::regclass
125
+ AND starts_with(c.conname, '${LEGACY_ATTACHMENTS_TABLE}_')
126
+ LOOP
127
+ EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', '${ATTACHMENTS_TABLE}', item.name,
128
+ replace(replace(item.name, '${LEGACY_ATTACHMENTS_TABLE}_', '${ATTACHMENTS_TABLE}_'),
129
+ '_conversation_', '_chat_'));
130
+ END LOOP;
131
+ FOR item IN
132
+ SELECT i.relname AS name FROM pg_catalog.pg_index x
133
+ JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid
134
+ WHERE x.indrelid = '"${ATTACHMENTS_TABLE}"'::regclass
135
+ AND starts_with(i.relname, '${LEGACY_ATTACHMENTS_TABLE}_')
136
+ LOOP
137
+ EXECUTE format('ALTER INDEX %I RENAME TO %I', item.name,
138
+ replace(item.name, '${LEGACY_ATTACHMENTS_TABLE}_', '${ATTACHMENTS_TABLE}_'));
139
+ END LOOP;
140
+ END
141
+ $rename$`;
74
142
  /**
75
- * A file a member sent the app's agent: platform metadata, never an ontology record. The bytes are
76
- * a `_blobs` revision in the same storage as uploads; the row binds them to their owner, the chat
77
- * and, for private chats, the first agent session that reads them. Group access follows the chat
78
- * registry's current members. Attachments expire 24 hours after receipt unless promoted, or, on a
79
- * channel that keeps its chats' files, with their messages.
143
+ * A file that arrived in a chat or that the agent made in its sandbox: platform metadata, never an
144
+ * ontology record. The bytes are a `_blobs` revision in the same storage as uploads; the row binds
145
+ * them to their owner, the chat (`provider:external_id`) and, for private chats, the first agent
146
+ * session that reads them. Group access follows the chat registry's current members. Attachments
147
+ * expire 24 hours after receipt unless promoted, or, on a channel that keeps its chats' files,
148
+ * with their messages.
80
149
  *
81
- * @legacy ontology.attachment-conversation-column
82
- * The column `conversation` holds the chat, `provider:external_id`: SDKs sharing this database
83
- * still read and write it under that name.
150
+ * The first statement renames the table an earlier SDK created; the last keeps its earlier name
151
+ * as a view for SDKs that share the database.
84
152
  */
85
153
  export const ATTACHMENT_TABLES_DDL = [
154
+ RENAME_LEGACY_ATTACHMENTS,
86
155
  `CREATE TABLE IF NOT EXISTS "${ATTACHMENTS_TABLE}" (
87
156
  "id" uuid PRIMARY KEY,
88
157
  "blob_id" uuid NOT NULL UNIQUE REFERENCES "_blobs" ("id"),
89
158
  "branch_id" text NOT NULL,
90
159
  "owner_id" uuid NOT NULL REFERENCES "user" ("id"),
91
- "conversation" text NOT NULL,
160
+ "chat" text NOT NULL,
92
161
  "session_id" text,
93
162
  "source" text NOT NULL CONSTRAINT "${ATTACHMENT_SOURCE_CHECK}" ${SOURCE_CHECK},
94
163
  "source_ref" text NOT NULL,
@@ -102,7 +171,7 @@ export const ATTACHMENT_TABLES_DDL = [
102
171
  "created_at" timestamptz NOT NULL DEFAULT now(),
103
172
  "expires_at" timestamptz NOT NULL DEFAULT now() + interval '24 hours',
104
173
  "removed_at" timestamptz,
105
- UNIQUE ("owner_id", "conversation", "source_ref")
174
+ UNIQUE ("owner_id", "chat", "source_ref")
106
175
  )`,
107
176
  `CREATE INDEX IF NOT EXISTS "${ATTACHMENTS_TABLE}_expiry_idx" ON "${ATTACHMENTS_TABLE}" ("state", "expires_at")`,
108
177
  `CREATE INDEX IF NOT EXISTS "${ATTACHMENTS_TABLE}_sha256_idx" ON "${ATTACHMENTS_TABLE}" ("sha256")`,
@@ -110,6 +179,12 @@ export const ATTACHMENT_TABLES_DDL = [
110
179
  // A table an earlier SDK created accepts fewer sources; widen its check in place.
111
180
  `ALTER TABLE "${ATTACHMENTS_TABLE}" DROP CONSTRAINT IF EXISTS "${ATTACHMENT_SOURCE_CHECK}", ` +
112
181
  `ADD CONSTRAINT "${ATTACHMENT_SOURCE_CHECK}" ${SOURCE_CHECK}`,
182
+ // @legacy ontology.agent-attachments-view
183
+ // A simple view, so an earlier SDK's inserts, updates, `ON CONFLICT` and row locks reach the
184
+ // table's rows, constraints and defaults. Columns added later stay out of it.
185
+ `CREATE OR REPLACE VIEW "${LEGACY_ATTACHMENTS_TABLE}" AS SELECT ` +
186
+ LEGACY_ATTACHMENT_COLUMNS.map((column) => column === "chat" ? `"chat" AS "conversation"` : `"${column}"`).join(", ") +
187
+ ` FROM "${ATTACHMENTS_TABLE}"`,
113
188
  ];
114
189
  /** The pending and started workflow starts of action triggers, beside the blob action results. */
115
190
  export const WORKFLOW_STARTS_TABLE = "_workflow_starts";
@@ -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>>;