@segmentstream/ontology 0.163.0 → 0.164.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.164.0
4
+
5
+ Approving a draft with files now sends them on Telegram, Slack and WhatsApp too, with the shared
6
+ senders of `@segmentstream/ontology/<channel>`. Telegram sends one message when the text fits a
7
+ caption and the files go as one file or one album of one type, otherwise the text and then the
8
+ files; Slack uploads every file and shares them with the text as one message; WhatsApp sends each
9
+ file by a link granted just before its message, the text as the first's caption. Each channel
10
+ declares its file limits and refuses what it cannot send before anything is reserved. A reply that
11
+ reached the person only in part is `uncertain` and never sent again, and its delivery keeps what
12
+ became of each file (`ProviderOutcome.files`). A Telegram caption may now be written in MarkdownV2
13
+ (`parseMode`), with `plainCaption` sent when Telegram refuses its formatting, and `sendSlackFiles`
14
+ takes `requireAll` to share nothing unless every file uploaded.
15
+
16
+ `sendGmailMessage` throws `GmailMaybeSent` when an upload fails after its last chunk went to
17
+ Gmail, which may have sent the message, and an approved email reply that fails so is `uncertain`,
18
+ never `failed`.
19
+
3
20
  ## 0.163.0
4
21
 
5
22
  The ontology of an app preview can serve the workspace's agent, built from the preview's commit,
package/dist/email.d.ts CHANGED
@@ -78,4 +78,4 @@ export declare function emailReplyMessage(reply: EmailReply): string;
78
78
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
79
79
  export declare function base64Url(text: string): string;
80
80
  export type { ChannelCall, ChannelReply, ChannelRequest } from "./channel-files.js";
81
- export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, gmailJson, sendGmailMessage, } from "./gmail-send.js";
81
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, sendGmailMessage, } from "./gmail-send.js";
package/dist/email.js CHANGED
@@ -210,4 +210,4 @@ export function emailReplyMessage(reply) {
210
210
  export function base64Url(text) {
211
211
  return Buffer.from(text, "utf8").toString("base64url");
212
212
  }
213
- export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, gmailJson, sendGmailMessage, } from "./gmail-send.js";
213
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, sendGmailMessage, } from "./gmail-send.js";
@@ -21,6 +21,16 @@ export declare class GmailError extends Error {
21
21
  readonly name = "GmailError";
22
22
  constructor(operation: string, status: number, detail?: string | undefined);
23
23
  }
24
+ /**
25
+ * A failure after the message's last byte went to Gmail: the upload may have completed and the
26
+ * message been sent, whatever the failure says, so it is never retried as unsent. `cause` is what
27
+ * failed, such as the probe of what Gmail held.
28
+ */
29
+ export declare class GmailMaybeSent extends Error {
30
+ readonly cause: unknown;
31
+ readonly name = "GmailMaybeSent";
32
+ constructor(cause: unknown);
33
+ }
24
34
  /** A reply's body as a JSON object, or an empty one. */
25
35
  export declare function gmailJson(reply: Pick<ChannelReply, "body">): Record<string, unknown>;
26
36
  /** Google's explanation of a refused call: its error message and reasons. */
@@ -29,6 +29,19 @@ export class GmailError extends Error {
29
29
  this.detail = detail;
30
30
  }
31
31
  }
32
+ /**
33
+ * A failure after the message's last byte went to Gmail: the upload may have completed and the
34
+ * message been sent, whatever the failure says, so it is never retried as unsent. `cause` is what
35
+ * failed, such as the probe of what Gmail held.
36
+ */
37
+ export class GmailMaybeSent extends Error {
38
+ cause;
39
+ name = "GmailMaybeSent";
40
+ constructor(cause) {
41
+ super("Gmail may have sent the message: its upload's last answer was lost.", { cause });
42
+ this.cause = cause;
43
+ }
44
+ }
32
45
  /** A reply's body as a JSON object, or an empty one. */
33
46
  export function gmailJson(reply) {
34
47
  try {
@@ -134,9 +147,13 @@ export async function sendGmailMessage(options) {
134
147
  const total = message.byteLength;
135
148
  let offset = 0;
136
149
  let recoveries = 0;
150
+ // Once the last byte was offered, Gmail may hold the whole message and have sent it.
151
+ let whole = false;
152
+ const maybeSent = (error) => (whole ? new GmailMaybeSent(error) : error);
137
153
  for (;;) {
138
154
  const end = Math.min(offset + UPLOAD_CHUNK_BYTES, total);
139
155
  let reply;
156
+ whole ||= end === total;
140
157
  try {
141
158
  reply = await request({
142
159
  api: session.api,
@@ -156,21 +173,26 @@ export async function sendGmailMessage(options) {
156
173
  // The chunk may or may not have arrived: Gmail says how much it holds.
157
174
  recoveries += 1;
158
175
  if (recoveries > UPLOAD_RECOVERIES) {
159
- throw error;
176
+ throw maybeSent(error);
177
+ }
178
+ try {
179
+ reply = await request({
180
+ api: session.api,
181
+ method: "PUT",
182
+ path: session.path,
183
+ headers: [["content-range", `bytes */${total}`]],
184
+ body: new Uint8Array(),
185
+ });
186
+ }
187
+ catch (probe) {
188
+ throw maybeSent(probe);
160
189
  }
161
- reply = await request({
162
- api: session.api,
163
- method: "PUT",
164
- path: session.path,
165
- headers: [["content-range", `bytes */${total}`]],
166
- body: new Uint8Array(),
167
- });
168
190
  }
169
191
  if (reply.status === 200 || reply.status === 201) {
170
192
  return gmailJson(reply);
171
193
  }
172
194
  if (reply.status !== 308) {
173
- throw new GmailError("messages.send", reply.status, gmailExplanation(reply));
195
+ throw maybeSent(new GmailError("messages.send", reply.status, gmailExplanation(reply)));
174
196
  }
175
197
  // `Range: bytes=0-N` is what Gmail holds; without it, nothing yet.
176
198
  const held = /^bytes=0-(\d+)$/u.exec(replyHeader(reply, "range") ?? "")?.[1];
@@ -53,4 +53,9 @@ export declare function readDraftFiles(input: {
53
53
  readonly person: string | null;
54
54
  readonly files: ReadonlyArray<AgentDraftFile>;
55
55
  readonly fetch: typeof fetch;
56
+ /**
57
+ * `link` for a provider that fetches the files itself: each is granted to the person now, which
58
+ * checks they may still read it, and its link is granted again just before its message.
59
+ */
60
+ readonly transfer?: "bytes" | "link";
56
61
  }): Effect.Effect<ReadonlyArray<ChatSendFile> | undefined>;
@@ -94,6 +94,28 @@ export function readDraftFiles(input) {
94
94
  return undefined;
95
95
  }
96
96
  const read = [];
97
+ if (input.transfer === "link") {
98
+ for (const file of input.files) {
99
+ const grant = (principal) => blobs.download(file.entity, file.id, file.property, { revisionId: file.revisionId }, principal);
100
+ const granted = yield* grant(member.principal).pipe(Effect.map(() => true), Effect.catch((cause) => Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
101
+ phase: "approve",
102
+ entity: file.entity,
103
+ id: file.id,
104
+ revisionId: file.revisionId,
105
+ error: describeChatError(cause, (text) => text),
106
+ }), Effect.as(false))));
107
+ if (!granted) {
108
+ return undefined;
109
+ }
110
+ read.push({
111
+ filename: file.filename,
112
+ contentType: file.contentType,
113
+ size: file.size,
114
+ link: () => Effect.runPromise(grant(member.principal)).then(({ url }) => url),
115
+ });
116
+ }
117
+ return read;
118
+ }
97
119
  for (const file of input.files) {
98
120
  const bytes = yield* blobs
99
121
  .download(file.entity, file.id, file.property, { revisionId: file.revisionId }, member.principal)
@@ -130,7 +152,12 @@ export function readDraftFiles(input) {
130
152
  }
131
153
  return undefined;
132
154
  }
133
- read.push({ filename: file.filename, contentType: file.contentType, bytes });
155
+ read.push({
156
+ filename: file.filename,
157
+ contentType: file.contentType,
158
+ size: file.size,
159
+ bytes,
160
+ });
134
161
  }
135
162
  return read;
136
163
  });
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
3
3
  import { renderWorkspaceChannelText, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_FILES_BYTES, WORKSPACE_CHANNEL_TEXT_LIMIT, workspaceChannelFiles, workspaceChannelSendRoute, } from "../../../workspace-channel.js";
4
- import { record } from "./provider.js";
4
+ import { filesWithBytes, record, } from "./provider.js";
5
5
  /** How long the agent has to send one message through a workspace channel. */
6
6
  const AGENT_SEND_TIMEOUT_MS = 30_000;
7
7
  /**
@@ -42,7 +42,7 @@ export function sendThroughAgent(input) {
42
42
  text: input.finalText,
43
43
  // Every agent with this route reads `files`, and refuses them with `files_unsupported`
44
44
  // when the channel's code takes none: nothing is sent then.
45
- ...(files.length === 0 ? {} : { files: workspaceChannelFiles(files) }),
45
+ ...(files.length === 0 ? {} : { files: workspaceChannelFiles(filesWithBytes(files)) }),
46
46
  };
47
47
  const answered = yield* Effect.tryPromise(async () => {
48
48
  const response = await agent.fetch(new Request(new URL(workspaceChannelSendRoute(input.destination.provider), agent.origin), {
@@ -1,8 +1,8 @@
1
1
  import { Effect } from "effect";
2
2
  import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
3
- import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, renderEmailHtml, sendGmailMessage, } from "../../../email.js";
3
+ import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, GmailMaybeSent, renderEmailHtml, sendGmailMessage, } from "../../../email.js";
4
4
  import { EMAIL_PATTERN } from "../../../property.js";
5
- import { channelRequest, definiteTransportFailure, record, transportFailure, } from "./provider.js";
5
+ import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportFailure, } from "./provider.js";
6
6
  /** A Gmail id, of a thread or a message. */
7
7
  const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
8
8
  const decoder = new TextDecoder();
@@ -88,7 +88,7 @@ export function sendEmail(input) {
88
88
  html: input.finalText,
89
89
  autoSubmitted: true,
90
90
  ...(/^[A-Za-z0-9_-]{1,128}$/.test(key) ? { replyKey: key } : {}),
91
- ...(files.length === 0 ? {} : { attachments: files }),
91
+ ...(files.length === 0 ? {} : { attachments: filesWithBytes(files) }),
92
92
  });
93
93
  const payload = {
94
94
  threadId,
@@ -116,14 +116,16 @@ export function sendEmail(input) {
116
116
  payload,
117
117
  // Gmail's refusal, or a proxy that never reached Gmail, sent nothing; anything else
118
118
  // may have, such as an upload whose last answer was lost.
119
- status: (cause instanceof GmailError &&
120
- cause.status >= 400 &&
121
- cause.status < 500 &&
122
- cause.status !== 408 &&
123
- cause.status !== 429) ||
124
- definiteTransportFailure(cause)
125
- ? "failed"
126
- : "uncertain",
119
+ status: cause instanceof GmailMaybeSent
120
+ ? "uncertain"
121
+ : (cause instanceof GmailError &&
122
+ cause.status >= 400 &&
123
+ cause.status < 500 &&
124
+ cause.status !== 408 &&
125
+ cause.status !== 429) ||
126
+ definiteTransportFailure(cause)
127
+ ? "failed"
128
+ : "uncertain",
127
129
  messageId: null,
128
130
  url: null,
129
131
  cause,
@@ -0,0 +1,36 @@
1
+ import { Effect } from "effect";
2
+ import { type ChatFileLimits, type ChatFilesRefusal, type ChatSend, type ProviderOutcome } from "./provider.js";
3
+ /** Telegram: up to ten files, each one request of the connection, by Telegram's type bounds. */
4
+ export declare const TELEGRAM_FILE_LIMITS: ChatFileLimits;
5
+ export declare function refuseTelegramFiles(files: ReadonlyArray<{
6
+ readonly contentType: string;
7
+ readonly size: number;
8
+ }>): ChatFilesRefusal | undefined;
9
+ /**
10
+ * Telegram: one message when the text fits a caption and the files go as one file or one album of
11
+ * one type; otherwise the text, then the files. The text keeps its MarkdownV2, sent again plain when
12
+ * Telegram refuses its formatting, as a text reply is.
13
+ */
14
+ export declare function sendTelegramWithFiles(input: ChatSend, sendText: (input: ChatSend) => Effect.Effect<ProviderOutcome>): Effect.Effect<ProviderOutcome>;
15
+ /** Slack: up to ten files, each one request of the connection. */
16
+ export declare const SLACK_FILE_LIMITS: ChatFileLimits;
17
+ export declare function refuseSlackFiles(files: ReadonlyArray<{
18
+ readonly contentType: string;
19
+ readonly size: number;
20
+ }>): ChatFilesRefusal | undefined;
21
+ /**
22
+ * Slack: every file uploaded, which nobody sees, then one share of them all with the text: one
23
+ * visible message. A file that does not upload shares nothing, so the reply is definitely unsent.
24
+ */
25
+ export declare function sendSlackWithFiles(input: ChatSend): Effect.Effect<ProviderOutcome>;
26
+ /** WhatsApp: up to ten files, one message each, by WhatsApp's bound of each type. */
27
+ export declare const WHATSAPP_FILE_LIMITS: ChatFileLimits;
28
+ export declare function refuseWhatsAppFiles(files: ReadonlyArray<{
29
+ readonly contentType: string;
30
+ readonly size: number;
31
+ }>): ChatFilesRefusal | undefined;
32
+ /**
33
+ * WhatsApp: one message per file, which WhatsApp fetches by a link granted just before it, the text
34
+ * as the first's caption, or first on its own when no caption carries it.
35
+ */
36
+ export declare function sendWhatsAppWithFiles(input: ChatSend): Effect.Effect<ProviderOutcome>;
@@ -0,0 +1,182 @@
1
+ import { Effect } from "effect";
2
+ import { MAXIMUM_CONNECTION_BODY_BYTES } from "../../../connection.js";
3
+ import { sendSlackFiles, SLACK_FILES_PER_MESSAGE, slackFileRefusal } from "../../../slack.js";
4
+ import { sendTelegramFiles, TELEGRAM_CAPTION_LIMIT, TELEGRAM_FILES_PER_MESSAGE, telegramFileRefusal, telegramFileType, } from "../../../telegram.js";
5
+ import { sendWhatsAppFiles, WHATSAPP_FILE_BYTES, whatsappFileRefusal } from "../../../whatsapp.js";
6
+ import { channelRequest, definiteTransportFailure, filesOutcome, filesWithBytes, } from "./provider.js";
7
+ /**
8
+ * An approved reply with files on Telegram, Slack and WhatsApp, by each channel's sender of the
9
+ * ontology SDK, the same one the agent's `attachments_send` calls. Everything that can be refused
10
+ * was refused before the reply was reserved; here each visible part is sent once, and what it
11
+ * became is kept per file.
12
+ */
13
+ /** A file a provider refuses on its own, as the delivery's refusal names it. */
14
+ function refusalOf(code) {
15
+ return code === "too_large"
16
+ ? "file_too_large"
17
+ : code === "empty"
18
+ ? "files_unsupported"
19
+ : undefined;
20
+ }
21
+ /** Telegram: up to ten files, each one request of the connection, by Telegram's type bounds. */
22
+ export const TELEGRAM_FILE_LIMITS = {
23
+ count: TELEGRAM_FILES_PER_MESSAGE,
24
+ bytes: TELEGRAM_FILES_PER_MESSAGE * MAXIMUM_CONNECTION_BODY_BYTES,
25
+ };
26
+ export function refuseTelegramFiles(files) {
27
+ for (const file of files) {
28
+ const refusal = refusalOf(telegramFileRefusal(file)?.code);
29
+ if (refusal !== undefined) {
30
+ return refusal;
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+ /**
36
+ * Telegram: one message when the text fits a caption and the files go as one file or one album of
37
+ * one type; otherwise the text, then the files. The text keeps its MarkdownV2, sent again plain when
38
+ * Telegram refuses its formatting, as a text reply is.
39
+ */
40
+ export function sendTelegramWithFiles(input, sendText) {
41
+ return Effect.gen(function* () {
42
+ const files = input.files ?? [];
43
+ const thread = typeof input.threadId === "string" && /^[1-9][0-9]*$/u.test(input.threadId)
44
+ ? input.threadId
45
+ : undefined;
46
+ const target = {
47
+ chatId: input.destination.external_id,
48
+ ...(thread === undefined ? {} : { messageThreadId: thread }),
49
+ };
50
+ const payload = { text: input.finalText, parse_mode: "MarkdownV2" };
51
+ const send = (caption, replyTo) => Effect.promise(() => sendTelegramFiles({
52
+ request: channelRequest(input.transport, input.connection),
53
+ target: { ...target, ...(replyTo === null ? {} : { replyTo }) },
54
+ files: filesWithBytes(files),
55
+ ...(caption
56
+ ? {
57
+ caption: { text: input.finalText, entities: [], parseMode: "MarkdownV2" },
58
+ plainCaption: { text: input.plainText, entities: [] },
59
+ }
60
+ : {}),
61
+ definite: definiteTransportFailure,
62
+ }));
63
+ const types = new Set(files.map((file) => telegramFileType(file.contentType)));
64
+ const oneMessage = files.length === 1 || (types.size === 1 && files.length <= 10);
65
+ if (input.plainText.trim() === "" ||
66
+ (oneMessage && input.finalText.length <= TELEGRAM_CAPTION_LIMIT)) {
67
+ return filesOutcome(payload, files, yield* send(input.plainText.trim() !== "", input.replyTo));
68
+ }
69
+ const text = yield* sendText({ ...input, files: [] });
70
+ // Files never follow a text that did not certainly reach the person: it is never sent again.
71
+ if (text.status !== "sent") {
72
+ return {
73
+ ...text,
74
+ payload: {
75
+ ...text.payload,
76
+ files: files.map((file, index) => ({
77
+ index,
78
+ filename: file.filename,
79
+ status: "failed",
80
+ messageId: null,
81
+ })),
82
+ },
83
+ };
84
+ }
85
+ const textPart = {
86
+ files: [],
87
+ text: true,
88
+ status: "sent",
89
+ messageIds: text.messageId === null ? [] : [text.messageId],
90
+ };
91
+ return filesOutcome(payload, files, [textPart, ...(yield* send(false, null))]);
92
+ });
93
+ }
94
+ /** Slack: up to ten files, each one request of the connection. */
95
+ export const SLACK_FILE_LIMITS = {
96
+ count: SLACK_FILES_PER_MESSAGE,
97
+ bytes: SLACK_FILES_PER_MESSAGE * MAXIMUM_CONNECTION_BODY_BYTES,
98
+ };
99
+ export function refuseSlackFiles(files) {
100
+ for (const file of files) {
101
+ const refusal = refusalOf(slackFileRefusal(file)?.code);
102
+ if (refusal !== undefined) {
103
+ return refusal;
104
+ }
105
+ }
106
+ return undefined;
107
+ }
108
+ /**
109
+ * Slack: every file uploaded, which nobody sees, then one share of them all with the text: one
110
+ * visible message. A file that does not upload shares nothing, so the reply is definitely unsent.
111
+ */
112
+ export function sendSlackWithFiles(input) {
113
+ return Effect.gen(function* () {
114
+ const files = input.files ?? [];
115
+ const payload = { initial_comment: input.finalText };
116
+ const thread = input.replyTo ?? (typeof input.threadId === "string" ? input.threadId : null);
117
+ const result = yield* Effect.promise(() => sendSlackFiles({
118
+ request: channelRequest(input.transport, input.connection),
119
+ // A file is shared in the chat itself: a direct message's channel, not its member's id.
120
+ channel: input.chatId ?? input.destination.external_id,
121
+ ...(thread === null || thread === "" ? {} : { threadTs: thread }),
122
+ files: filesWithBytes(files),
123
+ ...(input.plainText.trim() === "" ? {} : { text: input.finalText }),
124
+ requireAll: true,
125
+ definite: definiteTransportFailure,
126
+ }));
127
+ if (result.share === undefined) {
128
+ const failed = result.uploads.flatMap((upload) => ("code" in upload ? [upload.cause] : []));
129
+ return filesOutcome(payload, files, [
130
+ {
131
+ files: files.map((_file, index) => index),
132
+ text: true,
133
+ status: "failed",
134
+ messageIds: [],
135
+ code: "send_failed",
136
+ cause: failed.length === 1
137
+ ? failed[0]
138
+ : new AggregateError(failed, "Slack took not every file."),
139
+ },
140
+ ]);
141
+ }
142
+ return filesOutcome(payload, files, [result.share]);
143
+ });
144
+ }
145
+ /** WhatsApp: up to ten files, one message each, by WhatsApp's bound of each type. */
146
+ export const WHATSAPP_FILE_LIMITS = {
147
+ count: 10,
148
+ bytes: 10 * WHATSAPP_FILE_BYTES.document,
149
+ transfer: "link",
150
+ };
151
+ export function refuseWhatsAppFiles(files) {
152
+ for (const file of files) {
153
+ const refusal = refusalOf(whatsappFileRefusal(file)?.code);
154
+ if (refusal !== undefined) {
155
+ return refusal;
156
+ }
157
+ }
158
+ return undefined;
159
+ }
160
+ /**
161
+ * WhatsApp: one message per file, which WhatsApp fetches by a link granted just before it, the text
162
+ * as the first's caption, or first on its own when no caption carries it.
163
+ */
164
+ export function sendWhatsAppWithFiles(input) {
165
+ return Effect.gen(function* () {
166
+ const files = input.files ?? [];
167
+ const payload = { caption: input.finalText };
168
+ const parts = yield* Effect.promise(() => sendWhatsAppFiles({
169
+ request: channelRequest(input.transport, input.connection),
170
+ recipient: { to: input.destination.external_id },
171
+ files: files.map((file, index) => ({
172
+ index,
173
+ link: file.link ?? (async () => Promise.reject(new Error("The file has no link."))),
174
+ filename: file.filename,
175
+ contentType: file.contentType,
176
+ })),
177
+ ...(input.plainText.trim() === "" ? {} : { caption: input.finalText }),
178
+ definite: definiteTransportFailure,
179
+ }));
180
+ return filesOutcome(payload, files, parts);
181
+ });
182
+ }
@@ -1,5 +1,5 @@
1
1
  import { Effect, type Exit } from "effect";
2
- import type { ChannelRequest } from "../../../channel-files.js";
2
+ import type { ChannelPart, ChannelRequest } from "../../../channel-files.js";
3
3
  import type { ChatButtonRows } from "../../../chat.js";
4
4
  import type { TelegramPreviewContext } from "../../../telegram.js";
5
5
  import { ConnectionError, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
@@ -26,17 +26,36 @@ export interface ProviderOutcome {
26
26
  readonly messageId: string | null;
27
27
  }>;
28
28
  }
29
- /** A record file a send carries after its text, read before anything is sent. */
29
+ /**
30
+ * A record file a send carries after its text, read before anything is sent: its bytes, or for a
31
+ * provider that fetches files itself a fresh link to them, asked for just before its message.
32
+ */
30
33
  export interface ChatSendFile {
31
34
  readonly filename: string;
32
35
  readonly contentType: string;
33
- readonly bytes: Uint8Array;
36
+ readonly size: number;
37
+ readonly bytes?: Uint8Array;
38
+ readonly link?: () => Promise<string>;
34
39
  }
35
40
  /** How many files one message of a provider carries, and how many bytes of them together. */
36
41
  export interface ChatFileLimits {
37
42
  readonly count: number;
38
43
  readonly bytes: number;
44
+ /** `link` for a provider that fetches each file by a link; its bytes are sent otherwise. */
45
+ readonly transfer?: "bytes" | "link";
39
46
  }
47
+ /** A send's files with their bytes, as a provider that uploads them reads them. */
48
+ export declare function filesWithBytes(files: ReadonlyArray<ChatSendFile>): ReadonlyArray<{
49
+ readonly filename: string;
50
+ readonly contentType: string;
51
+ readonly bytes: Uint8Array;
52
+ }>;
53
+ /**
54
+ * What a send of text and files became, from each visible part's result: `sent` when every part
55
+ * was, `failed` when none reached the person, `uncertain` otherwise. Each file's result is kept,
56
+ * so a partial delivery is never sent again but staff see what reached the person.
57
+ */
58
+ export declare function filesOutcome(payload: Readonly<Record<string, unknown>>, files: ReadonlyArray<ChatSendFile>, parts: ReadonlyArray<ChannelPart>): ProviderOutcome;
40
59
  /** Why a provider cannot send a message's files, before its key is reserved. */
41
60
  export type ChatFilesRefusal = "files_unsupported" | "too_many_files" | "file_too_large" | "file_unavailable";
42
61
  /** Why a chat's provider refused a message, for code to act on. */
@@ -1,5 +1,48 @@
1
1
  import { Cause, Effect } from "effect";
2
2
  import { ConnectionError, } from "../../../connection.js";
3
+ /** A send's files with their bytes, as a provider that uploads them reads them. */
4
+ export function filesWithBytes(files) {
5
+ return files.map((file) => ({
6
+ filename: file.filename,
7
+ contentType: file.contentType,
8
+ bytes: file.bytes ?? new Uint8Array(),
9
+ }));
10
+ }
11
+ /**
12
+ * What a send of text and files became, from each visible part's result: `sent` when every part
13
+ * was, `failed` when none reached the person, `uncertain` otherwise. Each file's result is kept,
14
+ * so a partial delivery is never sent again but staff see what reached the person.
15
+ */
16
+ export function filesOutcome(payload, files, parts) {
17
+ const results = files.map((file, index) => {
18
+ const part = parts.find((candidate) => candidate.files.includes(index));
19
+ const position = part?.files.indexOf(index) ?? -1;
20
+ return {
21
+ index,
22
+ filename: file.filename,
23
+ status: part?.status ?? "failed",
24
+ messageId: part?.status === "sent" ? (part.messageIds[position] ?? part.messageIds[0] ?? null) : null,
25
+ };
26
+ });
27
+ const sent = parts.length > 0 && parts.every((part) => part.status === "sent");
28
+ const none = parts.every((part) => part.status === "failed");
29
+ const first = parts.find((part) => part.status === "sent")?.messageIds[0] ?? null;
30
+ const causes = parts.flatMap((part) => (part.cause === undefined ? [] : [part.cause]));
31
+ return {
32
+ payload: { ...payload, files: results },
33
+ status: sent ? "sent" : none ? "failed" : "uncertain",
34
+ messageId: sent || !none ? first : null,
35
+ url: null,
36
+ files: results.map(({ index, status, messageId }) => ({ index, status, messageId })),
37
+ ...(causes.length === 0
38
+ ? {}
39
+ : {
40
+ cause: causes.length === 1
41
+ ? causes[0]
42
+ : new AggregateError(causes, "Some parts of the message were not sent."),
43
+ }),
44
+ };
45
+ }
3
46
  /** The connection failures that prove the request never reached the provider. */
4
47
  const DEFINITE_CONNECTION_FAILURES = new Set([
5
48
  "authorization_required",
@@ -1,5 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import { renderSlack, SLACK_MESSAGE_LIMIT } from "../../../slack.js";
3
+ import { refuseSlackFiles, sendSlackWithFiles, SLACK_FILE_LIMITS } from "./files-send.js";
3
4
  import { record, transportFailure, } from "./provider.js";
4
5
  /** A message's `ts`, which also names the thread it starts. */
5
6
  const SLACK_TS = /^[0-9]+\.[0-9]+$/;
@@ -120,5 +121,7 @@ export const slackProvider = {
120
121
  payload: (finalText, buttons) => slackPayload(finalText, finalText, buttons),
121
122
  // Each row is an actions block; labels and rows fit within what the schema allows.
122
123
  refuseButtons: () => undefined,
123
- send: sendSlack,
124
+ files: SLACK_FILE_LIMITS,
125
+ refuseFiles: refuseSlackFiles,
126
+ send: (input) => ((input.files ?? []).length > 0 ? sendSlackWithFiles(input) : sendSlack(input)),
124
127
  };
@@ -1,6 +1,7 @@
1
1
  import { isTelegramBotUsername, miniAppLink, telegramMarkdownLinks, telegramMarkdownWithLinks, telegramTextLinks, telegramPreviewOptions, } from "../../../telegram.js";
2
2
  import { escapeMarkdownV2, TelegramFormatConverter } from "@chat-adapter/telegram";
3
3
  import { Effect } from "effect";
4
+ import { refuseTelegramFiles, sendTelegramWithFiles, TELEGRAM_FILE_LIMITS } from "./files-send.js";
4
5
  import { record, transportFailure, } from "./provider.js";
5
6
  export const TELEGRAM_MESSAGE_LIMIT = 4096;
6
7
  const converter = new TelegramFormatConverter();
@@ -218,7 +219,26 @@ export const telegramProvider = {
218
219
  }),
219
220
  // An inline keyboard takes every row the schema allows; a token fits its callback data.
220
221
  refuseButtons: () => undefined,
221
- send: (input) => Effect.gen(function* () {
222
+ files: TELEGRAM_FILE_LIMITS,
223
+ refuseFiles: refuseTelegramFiles,
224
+ send: (input) => (input.files ?? []).length > 0 ? sendTelegramFilesReply(input) : sendTelegramText(input),
225
+ };
226
+ /**
227
+ * A reply with files: its text, when it goes as a caption, leads to the app where a text reply
228
+ * would, so its links to the app open in the bot's Mini App too.
229
+ */
230
+ function sendTelegramFilesReply(input) {
231
+ return Effect.gen(function* () {
232
+ const links = yield* miniAppLinksOf(input, telegramMarkdownLinks(input.text));
233
+ const finalText = links.size === 0
234
+ ? input.finalText
235
+ : renderTelegram(input.text, input.attribution, input.separator, links);
236
+ return yield* sendTelegramWithFiles({ ...input, finalText }, sendTelegramText);
237
+ });
238
+ }
239
+ /** A text reply or post: the member's Markdown, with the chat's links to the app and previews. */
240
+ function sendTelegramText(input) {
241
+ return Effect.gen(function* () {
222
242
  const written = [
223
243
  ...telegramMarkdownLinks(input.text),
224
244
  ...telegramTextLinks(input.separator),
@@ -253,5 +273,5 @@ export const telegramProvider = {
253
273
  ? {}
254
274
  : { replyMarkup: telegramKeyboard(input.buttons, links) }),
255
275
  });
256
- }),
257
- };
276
+ });
277
+ }
@@ -2,6 +2,7 @@ import { Effect } from "effect";
2
2
  import { renderWhatsApp, WHATSAPP_MESSAGE_LIMIT } from "../../../whatsapp.js";
3
3
  import { whatsappTemplate } from "./whatsapp-template.js";
4
4
  import { REFUSALS, WAMID } from "./whatsapp-refusals.js";
5
+ import { refuseWhatsAppFiles, sendWhatsAppWithFiles, WHATSAPP_FILE_LIMITS } from "./files-send.js";
5
6
  import { record, transportFailure, } from "./provider.js";
6
7
  /** A WhatsApp id: the member's number, digits only. */
7
8
  const WA_ID = /^[1-9][0-9]{5,19}$/;
@@ -155,6 +156,8 @@ export const whatsappProvider = {
155
156
  ? { type: "text", text: { body: finalText, preview_url: false } }
156
157
  : whatsappInteractive(finalText, buttons),
157
158
  refuseButtons: refuseWhatsAppButtons,
158
- send: sendWhatsApp,
159
+ files: WHATSAPP_FILE_LIMITS,
160
+ refuseFiles: refuseWhatsAppFiles,
161
+ send: (input) => (input.files ?? []).length > 0 ? sendWhatsAppWithFiles(input) : sendWhatsApp(input),
159
162
  template: whatsappTemplate,
160
163
  };
@@ -329,6 +329,7 @@ export function reviewSender(input) {
329
329
  person,
330
330
  files,
331
331
  fetch: input.fetch ?? fetch,
332
+ ...(provider.files?.transfer === undefined ? {} : { transfer: provider.files.transfer }),
332
333
  });
333
334
  if (sendFiles === undefined) {
334
335
  return yield* refused("file_unavailable", providerName);
@@ -49,5 +49,7 @@ export declare function sendSlackFiles(options: {
49
49
  readonly index?: number;
50
50
  }>;
51
51
  readonly text?: string;
52
+ /** Shares nothing unless every file uploaded, as a reply that must arrive whole does. */
53
+ readonly requireAll?: boolean;
52
54
  readonly definite?: DefiniteFailure;
53
55
  }): Promise<SlackFilesResult>;
@@ -112,7 +112,7 @@ export async function sendSlackFiles(options) {
112
112
  });
113
113
  }
114
114
  }
115
- if (uploaded.length === 0) {
115
+ if (uploaded.length === 0 || (options.requireAll === true && uploaded.length < uploads.length)) {
116
116
  return { uploads };
117
117
  }
118
118
  const part = { files: uploaded.map(({ index }) => index), text: options.text !== undefined };
@@ -28,6 +28,8 @@ export interface TelegramEntity {
28
28
  export interface TelegramFormattedText {
29
29
  readonly text: string;
30
30
  readonly entities: ReadonlyArray<TelegramEntity>;
31
+ /** Text written in Telegram's MarkdownV2, formatted by Telegram, in place of entities. */
32
+ readonly parseMode?: "MarkdownV2";
31
33
  }
32
34
  /** How Telegram sends a file of this content type: as a photo or as a document. */
33
35
  export declare function telegramFileType(contentType: string): "photo" | "document";
@@ -77,5 +79,7 @@ export declare function sendTelegramFiles(options: {
77
79
  readonly index?: number;
78
80
  }>;
79
81
  readonly caption?: TelegramFormattedText;
82
+ /** The caption without its formatting, sent when Telegram refuses the caption's formatting. */
83
+ readonly plainCaption?: TelegramFormattedText;
80
84
  readonly definite?: DefiniteFailure;
81
85
  }): Promise<ReadonlyArray<ChannelPart>>;
@@ -117,6 +117,9 @@ async function multipart(target, files, caption) {
117
117
  if (sent.entities.length > 0) {
118
118
  form.set("caption_entities", JSON.stringify(sent.entities));
119
119
  }
120
+ if (caption.parseMode !== undefined) {
121
+ form.set("parse_mode", caption.parseMode);
122
+ }
120
123
  }
121
124
  }
122
125
  else {
@@ -127,6 +130,7 @@ async function multipart(target, files, caption) {
127
130
  ? {
128
131
  caption: caption.text,
129
132
  ...(caption.entities.length > 0 ? { caption_entities: caption.entities } : {}),
133
+ ...(caption.parseMode === undefined ? {} : { parse_mode: caption.parseMode }),
130
134
  }
131
135
  : {}),
132
136
  }))));
@@ -208,9 +212,9 @@ export async function sendTelegramFiles(options) {
208
212
  try {
209
213
  reply = await send(built);
210
214
  if (caption !== undefined &&
211
- caption.entities.length > 0 &&
215
+ (caption.entities.length > 0 || caption.parseMode !== undefined) &&
212
216
  telegramFormattingRefused(reply.status, replyJson(reply))) {
213
- caption = { text: caption.text, entities: [] };
217
+ caption = options.plainCaption ?? { text: caption.text, entities: [] };
214
218
  reply = await send(await multipart(options.target, batch, caption));
215
219
  }
216
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.163.0",
3
+ "version": "0.164.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",