@segmentstream/ontology 0.184.0 → 0.186.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,66 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.186.0
4
+
5
+ The ontology's Slack messages, a post in either voice (`agent_chat.send`), a draft a member approves
6
+ and a reply its review lets go, are rendered and checked as before and handed to the agent's Slack
7
+ channel of the chat's name at `POST /eve/segmentstream/v1/slack/<name>/deliver`, which sends them
8
+ through its app: the exact Markdown with its attribution, with its buttons as blocks, in the thread
9
+ of the message it answers or the chat's thread, and the files with the text, each by a short-lived
10
+ link granted just before. What the channel answers is recorded as the ontology's own send was:
11
+ `sent` with the message's `ts`, `failed` when Slack refused it, or `uncertain`, with each file's
12
+ result and the same payload in the delivery's history.
13
+
14
+ `@segmentstream/ontology/slack` exports the route and its wire types: `slackDeliverRoute`,
15
+ `SlackDeliver`, `SlackDeliverMessage`, `SlackDelivered` and `SlackDeliverRefused`, with
16
+ `ChannelDeliverFile` and `ChannelDeliveredFile`. It also exports `SLACK_POSSIBLY_POSTED`, Slack's
17
+ `ok: false` codes that do not prove nothing was posted, by which both SDKs classify Slack's answers.
18
+
19
+ An agent from before the route answers 404, and one without a Slack channel of the chat's name on
20
+ the connection `chat` names answers `channel_unknown`: the ontology then sends the message through
21
+ that connection itself, as before. This release works with the agent SDK's previous release, and
22
+ the agent SDK's next release works with this ontology SDK's previous one, which never calls the
23
+ route.
24
+
25
+ Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and give
26
+ the agent a Slack channel of the name of each Slack channel in the ontology's `chat`, on the same
27
+ connection (`channels.slack.connection` in `agent/segmentstream.json` naming the connection of
28
+ `chat.slack`, and so for a channel of another name). The ontology's own Slack sender, which sends
29
+ for an agent without such a channel, is deprecated and stops on 2027-05-28
30
+ (`ontology.slack-own-sender`).
31
+
32
+ ## 0.185.0
33
+
34
+ The ontology's WhatsApp messages, a post in either voice (`agent_chat.send`), a draft a member
35
+ approves and a reply its review lets go, are rendered and checked as before and handed to the
36
+ agent's WhatsApp channel of the chat's name at `POST /eve/segmentstream/v1/whatsapp/<name>/deliver`,
37
+ which sends them from its number: the text with its attribution, the text with its buttons, or an
38
+ approved template with its header's, body's and buttons' values, and the files after the text, each
39
+ by a short-lived link granted just before. What the channel answers is recorded as the ontology's
40
+ own send was: `sent`, `failed` (with `outside_reply_window`, `recipient_unreachable` or
41
+ `recipient_opted_out` where Meta's code names one) or `uncertain`, with each file's result and the
42
+ same payload in the delivery's history.
43
+
44
+ `@segmentstream/ontology/whatsapp` exports the route and its wire types: `whatsappDeliverRoute`,
45
+ `WhatsAppDeliver`, `WhatsAppDeliverMessage`, `WhatsAppDelivered`, `WhatsAppDeliverRefused` and
46
+ `WHATSAPP_DELIVER_FILES`, with `ChannelDeliverFile` and `ChannelDeliveredFile`. It also exports
47
+ `sendWhatsAppMessage`, the one-message sender `sendWhatsAppFiles` sends each of its messages with,
48
+ and `WhatsAppMessageType` and `WhatsAppRefusal`; a part `sendWhatsAppFiles` answers as `failed`
49
+ now names Meta's `refusal` where its code names one.
50
+
51
+ An agent from before the route answers 404, and one without a WhatsApp channel of the chat's name
52
+ on the connection `chat` names answers `channel_unknown`: the ontology then sends the message
53
+ through that connection itself, as before. A workspace channel that reaches WhatsApp through
54
+ another provider is unaffected. This release works with the agent SDK's previous release, and the
55
+ agent SDK's next release works with this ontology SDK's previous one, which never calls the route.
56
+
57
+ Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and give
58
+ the agent a WhatsApp channel of the name of each WhatsApp channel in the ontology's `chat`, on the
59
+ same connection (`channels.whatsapp.connection` in `agent/segmentstream.json` naming the connection
60
+ of `chat.whatsapp`, and so for a channel of another name). The ontology's own WhatsApp sender, which
61
+ sends for an agent without such a channel, is deprecated and stops on 2027-05-28
62
+ (`ontology.whatsapp-own-sender`).
63
+
3
64
  ## 0.184.0
4
65
 
5
66
  The ontology's Telegram messages, a post in either voice (`agent_chat.send`), a draft a member
package/README.md CHANGED
@@ -1582,17 +1582,22 @@ defineOntology({
1582
1582
 
1583
1583
  Its destinations are the `agent_chat` registry's Slack channels, which the agent's Slack channel
1584
1584
  reports, and `slack:private:<member UUID>` for each member paired on Slack, posted to their user
1585
- id. A Slack post is one `chat.postMessage` with `markdown_text`: the member's exact Markdown, then
1586
- the separator and attribution with Markdown escaped and the attribution in italics, as
1587
- `renderSlack` from `@segmentstream/ontology/slack` renders it. `reply_to` is a thread message's
1585
+ id. A Slack post is one `chat.postMessage` with `markdown_text`, which the agent's Slack channel of
1586
+ the chat's name sends through its app (`POST /eve/segmentstream/v1/slack/<name>/deliver`,
1587
+ `slackDeliverRoute`), or the ontology itself for an agent without one: the member's exact
1588
+ Markdown, then the separator and attribution with Markdown escaped and the attribution in italics,
1589
+ as `renderSlack` from `@segmentstream/ontology/slack` renders it. `reply_to` is a thread message's
1588
1590
  `ts`. Slack's `ok: false` refusal consumes the key; a timeout, a 5xx or an unverifiable answer is
1589
1591
  `uncertain`. The receipt's `message_id` is the message's `ts`; it has no URL.
1590
1592
 
1591
1593
  Members' WhatsApp chats with the workspace's number are destinations only when `chat.whatsapp`
1592
1594
  declares the `WhatsAppConnection`, under the same rules. Each member with a live WhatsApp pairing
1593
1595
  is `whatsapp:private:<member UUID>`, posted to their WhatsApp id; WhatsApp has no group
1594
- destinations. A WhatsApp post is one text message, `POST /phone/messages` on the connection's
1595
- `graph` API with link previews off: the member's text as written, then the separator and the
1596
+ destinations. A WhatsApp post is one text message, which the agent's WhatsApp channel of the
1597
+ chat's name sends from its number (`POST /eve/segmentstream/v1/whatsapp/<name>/deliver`,
1598
+ `whatsappDeliverRoute`), or the ontology itself for an agent without one, `POST /phone/messages` on
1599
+ the connection's `graph` API with link previews off: the member's text as written, then the
1600
+ separator and the
1596
1601
  attribution in italics, whose WhatsApp formatting markers (`*`, `_`, `~`, `` ` ``) become
1597
1602
  look-alikes WhatsApp never formats, as `renderWhatsApp` from `@segmentstream/ontology/whatsapp`
1598
1603
  renders it. The body is at most 4096 characters, and `reply_to` is refused. Meta delivers
@@ -23,6 +23,8 @@ export declare function refuseSlackFiles(files: ReadonlyArray<{
23
23
  /**
24
24
  * Slack: every file uploaded, which nobody sees, then one share of them all with the text: one
25
25
  * visible message. A file that does not upload shares nothing, so the reply is definitely unsent.
26
+ * @legacy ontology.slack-own-sender The ontology's own send of a message with files, which the
27
+ * agent's Slack channel's deliver route does in its place.
26
28
  */
27
29
  export declare function sendSlackWithFiles(input: ChatSend): Effect.Effect<ProviderOutcome>;
28
30
  /** WhatsApp: up to ten files, one message each, by WhatsApp's bound of each type. */
@@ -34,5 +36,7 @@ export declare function refuseWhatsAppFiles(files: ReadonlyArray<{
34
36
  /**
35
37
  * WhatsApp: one message per file, which WhatsApp fetches by a link granted just before it, the text
36
38
  * as the first's caption, or first on its own when no caption carries it.
39
+ * @legacy ontology.whatsapp-own-sender The ontology's own send of a message with files, which the
40
+ * agent's WhatsApp channel's deliver route does in its place.
37
41
  */
38
42
  export declare function sendWhatsAppWithFiles(input: ChatSend): Effect.Effect<ProviderOutcome>;
@@ -2,7 +2,7 @@ import { Effect } from "effect";
2
2
  import { MAXIMUM_CONNECTION_BODY_BYTES } from "../../../connection.js";
3
3
  import { sendSlackFiles, SLACK_FILES_PER_MESSAGE, slackFileRefusal } from "../../../slack.js";
4
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";
5
+ import { sendWhatsAppFiles, WHATSAPP_DELIVER_FILES, WHATSAPP_FILE_BYTES, whatsappFileRefusal, } from "../../../whatsapp.js";
6
6
  import { channelRequest, definiteTransportFailure, filesOutcome, filesWithBytes, } from "./provider.js";
7
7
  /**
8
8
  * An approved reply with files on Telegram, Slack and WhatsApp, by each channel's sender of the
@@ -110,6 +110,8 @@ export function refuseSlackFiles(files) {
110
110
  /**
111
111
  * Slack: every file uploaded, which nobody sees, then one share of them all with the text: one
112
112
  * visible message. A file that does not upload shares nothing, so the reply is definitely unsent.
113
+ * @legacy ontology.slack-own-sender The ontology's own send of a message with files, which the
114
+ * agent's Slack channel's deliver route does in its place.
113
115
  */
114
116
  export function sendSlackWithFiles(input) {
115
117
  return Effect.gen(function* () {
@@ -146,8 +148,8 @@ export function sendSlackWithFiles(input) {
146
148
  }
147
149
  /** WhatsApp: up to ten files, one message each, by WhatsApp's bound of each type. */
148
150
  export const WHATSAPP_FILE_LIMITS = {
149
- count: 10,
150
- bytes: 10 * WHATSAPP_FILE_BYTES.document,
151
+ count: WHATSAPP_DELIVER_FILES,
152
+ bytes: WHATSAPP_DELIVER_FILES * WHATSAPP_FILE_BYTES.document,
151
153
  transfer: "link",
152
154
  };
153
155
  export function refuseWhatsAppFiles(files) {
@@ -162,6 +164,8 @@ export function refuseWhatsAppFiles(files) {
162
164
  /**
163
165
  * WhatsApp: one message per file, which WhatsApp fetches by a link granted just before it, the text
164
166
  * as the first's caption, or first on its own when no caption carries it.
167
+ * @legacy ontology.whatsapp-own-sender The ontology's own send of a message with files, which the
168
+ * agent's WhatsApp channel's deliver route does in its place.
165
169
  */
166
170
  export function sendWhatsAppWithFiles(input) {
167
171
  return Effect.gen(function* () {
@@ -90,6 +90,12 @@ export declare function postToAgent(agent: AgentChannelTransport, route: string,
90
90
  readonly status: number;
91
91
  readonly answer: Record<string, unknown>;
92
92
  }, unknown>;
93
+ /**
94
+ * What became of each file of a delivery, as an agent's channel answers it (`ChannelDeliveredFile`):
95
+ * one result per file in order, each message named by an id `messageId` matches, or undefined for
96
+ * an answer without that shape.
97
+ */
98
+ export declare function deliveredFiles(value: unknown, count: number, messageId: RegExp): ReadonlyArray<NonNullable<ProviderOutcome["files"]>[number]> | undefined;
93
99
  /** What a provider sends: the exact text its `render` gave, to one resolved destination. */
94
100
  export interface ChatSend {
95
101
  readonly transport: ConnectionTransport["Service"];
@@ -96,6 +96,35 @@ export function postToAgent(agent, route, body, timeoutMs) {
96
96
  catch: (cause) => cause,
97
97
  });
98
98
  }
99
+ /**
100
+ * What became of each file of a delivery, as an agent's channel answers it (`ChannelDeliveredFile`):
101
+ * one result per file in order, each message named by an id `messageId` matches, or undefined for
102
+ * an answer without that shape.
103
+ */
104
+ export function deliveredFiles(value, count, messageId) {
105
+ if (count === 0) {
106
+ return undefined;
107
+ }
108
+ if (!Array.isArray(value) || value.length !== count) {
109
+ return undefined;
110
+ }
111
+ const results = value.map((item, index) => {
112
+ const result = record(item);
113
+ const id = result.message_id;
114
+ return result.index === index &&
115
+ (result.status === "sent" || result.status === "uncertain" || result.status === "failed") &&
116
+ (id === null || (typeof id === "string" && messageId.test(id)))
117
+ ? {
118
+ index,
119
+ status: result.status,
120
+ messageId: result.status === "sent" ? id : null,
121
+ }
122
+ : undefined;
123
+ });
124
+ return results.every((result) => result !== undefined)
125
+ ? results
126
+ : undefined;
127
+ }
99
128
  /** The connection failures that prove the request never reached the provider. */
100
129
  const DEFINITE_CONNECTION_FAILURES = new Set([
101
130
  "authorization_required",
@@ -12,7 +12,13 @@ export declare function slackPayload(finalText: string, plainText: string, butto
12
12
  * message it replies to, else in the chat's thread, such as the one a reviewed reply answers.
13
13
  * Slack's own refusal (`ok: false` with an error code) is definite; a timeout, a 5xx, an
14
14
  * unparseable answer or a success that does not name the message, or its thread, is uncertain.
15
+ * @legacy ontology.slack-own-sender The ontology's own send of a message without files, which the
16
+ * agent's Slack channel's deliver route does in its place.
15
17
  */
16
18
  export declare function sendSlack(input: ChatSend): Effect.Effect<ProviderOutcome>;
17
- /** Slack: the member's Markdown as `markdown_text`, in a channel or a member's direct message. */
19
+ /**
20
+ * Slack: the member's Markdown as `markdown_text`, in a channel or a member's direct message. The
21
+ * ontology renders the message, its text and its buttons, and the agent's Slack channel of the
22
+ * chat's name sends it through its app.
23
+ */
18
24
  export declare const slackProvider: ChatProvider;
@@ -1,18 +1,9 @@
1
- import { Effect } from "effect";
2
- import { renderSlack, SLACK_MESSAGE_LIMIT } from "../../../slack.js";
1
+ import { Cause, Effect } from "effect";
2
+ import { renderSlack, slackDeliverRoute, SLACK_MESSAGE_LIMIT, SLACK_POSSIBLY_POSTED, } from "../../../slack.js";
3
3
  import { refuseSlackFiles, sendSlackWithFiles, SLACK_FILE_LIMITS } from "./files-send.js";
4
- import { record, transportFailure, } from "./provider.js";
4
+ import { agentFileLinks, deliveredFiles, postToAgent, record, transportFailure, } from "./provider.js";
5
5
  /** A message's `ts`, which also names the thread it starts. */
6
6
  const SLACK_TS = /^[0-9]+\.[0-9]+$/;
7
- /**
8
- * Slack's `ok: false` codes that do not prove the message was not posted: Slack says some of the
9
- * operation may have succeeded before the error.
10
- */
11
- const POSSIBLY_POSTED = new Set([
12
- "internal_error",
13
- "fatal_error",
14
- "service_unavailable",
15
- ]);
16
7
  /**
17
8
  * A message with buttons as Slack shows it: the Markdown in a `markdown` block, then a row of
18
9
  * buttons in an `actions` block each, a workspace button's value `ws:<token>`, with the plain text
@@ -38,17 +29,34 @@ export function slackPayload(finalText, plainText, buttons) {
38
29
  ],
39
30
  };
40
31
  }
32
+ /**
33
+ * The thread a message without files goes in: the one of the message it replies to, else the
34
+ * chat's thread, such as the one a reviewed reply answers, when it is a Slack `ts`.
35
+ */
36
+ function messageThread(input) {
37
+ return (input.replyTo ??
38
+ (typeof input.threadId === "string" && SLACK_TS.test(input.threadId) ? input.threadId : null));
39
+ }
40
+ /**
41
+ * The thread a message with files is shared in: the one of the message it replies to, else the
42
+ * chat's thread, whatever it is.
43
+ */
44
+ function filesThread(input) {
45
+ const thread = input.replyTo ?? input.threadId ?? null;
46
+ return thread === "" ? null : thread;
47
+ }
41
48
  /**
42
49
  * One `chat.postMessage` through the connection's `web` API, never retried, in the thread of the
43
50
  * message it replies to, else in the chat's thread, such as the one a reviewed reply answers.
44
51
  * Slack's own refusal (`ok: false` with an error code) is definite; a timeout, a 5xx, an
45
52
  * unparseable answer or a success that does not name the message, or its thread, is uncertain.
53
+ * @legacy ontology.slack-own-sender The ontology's own send of a message without files, which the
54
+ * agent's Slack channel's deliver route does in its place.
46
55
  */
47
56
  export function sendSlack(input) {
48
57
  return Effect.gen(function* () {
49
58
  const payload = slackPayload(input.finalText, input.plainText, input.buttons);
50
- const thread = input.replyTo ??
51
- (typeof input.threadId === "string" && SLACK_TS.test(input.threadId) ? input.threadId : null);
59
+ const thread = messageThread(input);
52
60
  const result = yield* input.transport
53
61
  .request({
54
62
  connection: input.connection,
@@ -85,7 +93,7 @@ export function sendSlack(input) {
85
93
  }
86
94
  if (body.ok === false && typeof body.error === "string" && body.error !== "") {
87
95
  const cause = new Error(`Slack refused the message: ${body.error}.`);
88
- return POSSIBLY_POSTED.has(body.error)
96
+ return SLACK_POSSIBLY_POSTED.has(body.error)
89
97
  ? uncertain(cause)
90
98
  : { payload, status: "failed", messageId: null, url: null, cause };
91
99
  }
@@ -105,7 +113,11 @@ export function sendSlack(input) {
105
113
  return { payload, status: "sent", messageId: body.ts, url: null };
106
114
  });
107
115
  }
108
- /** Slack: the member's Markdown as `markdown_text`, in a channel or a member's direct message. */
116
+ /**
117
+ * Slack: the member's Markdown as `markdown_text`, in a channel or a member's direct message. The
118
+ * ontology renders the message, its text and its buttons, and the agent's Slack channel of the
119
+ * chat's name sends it through its app.
120
+ */
109
121
  export const slackProvider = {
110
122
  provider: "slack",
111
123
  limit: SLACK_MESSAGE_LIMIT,
@@ -123,5 +135,134 @@ export const slackProvider = {
123
135
  refuseButtons: () => undefined,
124
136
  files: SLACK_FILE_LIMITS,
125
137
  refuseFiles: refuseSlackFiles,
126
- send: (input) => ((input.files ?? []).length > 0 ? sendSlackWithFiles(input) : sendSlack(input)),
138
+ send: deliverSlack,
127
139
  };
140
+ /**
141
+ * One message, rendered here and sent by the agent's Slack channel; by the ontology itself for an
142
+ * agent without its deliver route.
143
+ */
144
+ function deliverSlack(input) {
145
+ return Effect.gen(function* () {
146
+ if (input.agent?.origin !== undefined && input.agent.identityToken !== undefined) {
147
+ const delivered = yield* deliverThroughAgent(input);
148
+ if (delivered !== undefined) {
149
+ return delivered;
150
+ }
151
+ }
152
+ // @legacy ontology.slack-own-sender The ontology's own Slack sender, for an agent without the
153
+ // Slack channel's deliver route or without a Slack channel of the chat's name on its
154
+ // connection: the message, or each file's bytes and then their share, through the ontology's
155
+ // connection.
156
+ return yield* (input.files ?? []).length > 0 ? sendSlackWithFiles(input) : sendSlack(input);
157
+ });
158
+ }
159
+ /**
160
+ * How long the agent's Slack channel has to send one message: its `chat.postMessage`, or each
161
+ * file's upload and then their share, through the connection.
162
+ */
163
+ const AGENT_DELIVER_TIMEOUT_MS = 90_000;
164
+ /**
165
+ * One message through the agent's Slack channel (`POST` {@link slackDeliverRoute}), never retried:
166
+ * the channel sends what is rendered here through its app, the message, or the files and then
167
+ * their share with the text. Undefined when the agent has no such route (`404`) or no Slack channel
168
+ * of the chat's name on this connection (`channel_unknown`), so the ontology sends it itself. The
169
+ * agent's other `4xx` sent nothing; a `2xx` says what reached the person; a timeout, a `5xx` or an
170
+ * answer without its shape may have sent it, and is uncertain.
171
+ */
172
+ function deliverThroughAgent(input) {
173
+ return Effect.gen(function* () {
174
+ const files = input.files ?? [];
175
+ const message = slackPayload(input.finalText, input.plainText, input.buttons);
176
+ // What the delivery's history keeps, as the ontology's own sender kept it.
177
+ const payload = files.length === 0 ? message : { initial_comment: input.finalText };
178
+ const outcome = (status, results, rest) => ({
179
+ payload: results === undefined
180
+ ? payload
181
+ : {
182
+ ...payload,
183
+ files: results.map((result) => ({
184
+ index: result.index,
185
+ filename: files[result.index]?.filename ?? "",
186
+ status: result.status,
187
+ messageId: result.messageId,
188
+ })),
189
+ },
190
+ status,
191
+ ...rest,
192
+ ...(results === undefined ? {} : { files: results }),
193
+ });
194
+ const unsent = files.length === 0
195
+ ? undefined
196
+ : files.map((_file, index) => ({ index, status: "failed", messageId: null }));
197
+ const links = yield* agentFileLinks(files).pipe(Effect.exit);
198
+ if (links._tag === "Failure") {
199
+ return outcome("failed", unsent, {
200
+ messageId: null,
201
+ url: null,
202
+ cause: Cause.squash(links.cause),
203
+ });
204
+ }
205
+ const body = {
206
+ operation_id: input.operationId ?? input.destination.id,
207
+ connection: input.connection,
208
+ ...(files.length === 0
209
+ ? {
210
+ channel: input.destination.external_id,
211
+ thread_ts: messageThread(input),
212
+ message: message,
213
+ }
214
+ : {
215
+ // Files are shared in the chat itself: a direct message's channel, not its member's id.
216
+ channel: input.chatId ?? input.destination.external_id,
217
+ thread_ts: filesThread(input),
218
+ // A message of files alone has no text to share them with.
219
+ ...(input.plainText.trim() === "" ? {} : { initial_comment: input.finalText }),
220
+ files: links.value,
221
+ }),
222
+ };
223
+ const answered = yield* postToAgent(input.agent, slackDeliverRoute(input.destination.provider), body, AGENT_DELIVER_TIMEOUT_MS).pipe(Effect.exit);
224
+ if (answered._tag === "Failure") {
225
+ return outcome("uncertain", undefined, {
226
+ messageId: null,
227
+ url: null,
228
+ cause: Cause.squash(answered.cause),
229
+ });
230
+ }
231
+ const { status, answer } = answered.value;
232
+ if (status === 404 || (status === 422 && answer.error === "channel_unknown")) {
233
+ return undefined;
234
+ }
235
+ if (status >= 400 && status < 500) {
236
+ return outcome("failed", unsent, {
237
+ messageId: null,
238
+ url: null,
239
+ cause: new Error(`The agent's Slack channel refused the message (${typeof answer.error === "string" ? answer.error : `status ${status}`}${typeof answer.reference === "string" ? `, reference ${answer.reference}` : ""}).`),
240
+ });
241
+ }
242
+ const results = deliveredFiles(answer.files, files.length, SLACK_TS);
243
+ const id = answer.message_id;
244
+ if (status < 200 ||
245
+ status >= 300 ||
246
+ (answer.status !== "sent" && answer.status !== "uncertain") ||
247
+ (id !== null && (typeof id !== "string" || !SLACK_TS.test(id))) ||
248
+ // A message is sent with its `ts`; a share of files may be one Slack's answer names none of.
249
+ (answer.status === "sent" &&
250
+ ((files.length === 0 && id === null) ||
251
+ results?.some((result) => result.status !== "sent") === true)) ||
252
+ (files.length > 0 && results === undefined)) {
253
+ return outcome("uncertain", undefined, {
254
+ messageId: null,
255
+ url: null,
256
+ cause: new Error(`The agent's Slack channel answered with status ${status}.`),
257
+ });
258
+ }
259
+ return answer.status === "sent"
260
+ ? outcome("sent", results, { messageId: id, url: null })
261
+ : outcome("uncertain", results, {
262
+ messageId: id,
263
+ url: null,
264
+ cause: new Error("The agent's Slack channel could not prove the message sent" +
265
+ `${typeof answer.reference === "string" ? ` (reference ${answer.reference})` : ""}.`),
266
+ });
267
+ });
268
+ }
@@ -2,7 +2,7 @@ import { isTelegramBotUsername, miniAppLink, telegramDeliverRoute, telegramMarkd
2
2
  import { escapeMarkdownV2, TelegramFormatConverter } from "@chat-adapter/telegram";
3
3
  import { Cause, Effect } from "effect";
4
4
  import { refuseTelegramFiles, sendTelegramWithFiles, TELEGRAM_FILE_LIMITS } from "./files-send.js";
5
- import { agentFileLinks, postToAgent, record, transportFailure, } from "./provider.js";
5
+ import { agentFileLinks, deliveredFiles, postToAgent, record, transportFailure, } from "./provider.js";
6
6
  export { TELEGRAM_MESSAGE_LIMIT };
7
7
  const converter = new TelegramFormatConverter();
8
8
  /**
@@ -396,7 +396,7 @@ function deliverThroughAgent(input, message) {
396
396
  : {}),
397
397
  });
398
398
  }
399
- const results = deliveredFiles(answer.files, files.length);
399
+ const results = deliveredFiles(answer.files, files.length, MESSAGE_ID);
400
400
  const id = answer.message_id;
401
401
  const url = typeof answer.url === "string" && answer.url.startsWith("https://t.me/") ? answer.url : null;
402
402
  if (status < 200 ||
@@ -422,28 +422,3 @@ function deliverThroughAgent(input, message) {
422
422
  });
423
423
  });
424
424
  }
425
- /** The result of each file the agent's answer names, one per file in order, or undefined. */
426
- function deliveredFiles(value, count) {
427
- if (count === 0) {
428
- return undefined;
429
- }
430
- if (!Array.isArray(value) || value.length !== count) {
431
- return undefined;
432
- }
433
- const results = value.map((item, index) => {
434
- const result = record(item);
435
- const id = result.message_id;
436
- return result.index === index &&
437
- (result.status === "sent" || result.status === "uncertain" || result.status === "failed") &&
438
- (id === null || (typeof id === "string" && MESSAGE_ID.test(id)))
439
- ? {
440
- index,
441
- status: result.status,
442
- messageId: result.status === "sent" ? id : null,
443
- }
444
- : undefined;
445
- });
446
- return results.every((result) => result !== undefined)
447
- ? results
448
- : undefined;
449
- }
@@ -18,10 +18,14 @@ export declare function whatsappInteractive(finalText: string, rows: ChatButtonR
18
18
  * `graph` API, never retried. A Graph refusal with an error code, such as 131047 outside the
19
19
  * 24-hour customer-service window, is definite; a timeout, a 5xx, an unparseable answer or a
20
20
  * success without the message's id is uncertain. `sent` means Meta accepted the message.
21
+ * @legacy ontology.whatsapp-own-sender The ontology's own send of a message without files, which
22
+ * the agent's WhatsApp channel's deliver route does in its place.
21
23
  */
22
24
  export declare function sendWhatsApp(input: ChatSend): Effect.Effect<ProviderOutcome>;
23
25
  /**
24
26
  * WhatsApp: a paired member's chat with the workspace's number, by their WhatsApp id. WhatsApp
25
- * has no group destinations, and a post cannot reply to a message.
27
+ * has no group destinations, and a post cannot reply to a message. The ontology renders the
28
+ * message, its text, buttons or template, and the agent's WhatsApp channel of the chat's name
29
+ * sends it from its number.
26
30
  */
27
31
  export declare const whatsappProvider: ChatProvider;
@@ -1,9 +1,9 @@
1
- import { Effect } from "effect";
2
- import { renderWhatsApp, WHATSAPP_MESSAGE_LIMIT } from "../../../whatsapp.js";
1
+ import { Cause, Effect } from "effect";
2
+ import { renderWhatsApp, whatsappDeliverRoute, WHATSAPP_MESSAGE_LIMIT, } from "../../../whatsapp.js";
3
3
  import { whatsappTemplate } from "./whatsapp-template.js";
4
4
  import { REFUSALS, WAMID } from "./whatsapp-refusals.js";
5
5
  import { refuseWhatsAppFiles, sendWhatsAppWithFiles, WHATSAPP_FILE_LIMITS } from "./files-send.js";
6
- import { record, transportFailure, } from "./provider.js";
6
+ import { agentFileLinks, deliveredFiles, postToAgent, record, transportFailure, } from "./provider.js";
7
7
  /** A WhatsApp id: the member's number, digits only. */
8
8
  const WA_ID = /^[1-9][0-9]{5,19}$/;
9
9
  /** The most characters of an interactive message's body, under which WhatsApp shows buttons. */
@@ -66,18 +66,27 @@ export function whatsappInteractive(finalText, rows) {
66
66
  },
67
67
  };
68
68
  }
69
+ /**
70
+ * A message without files as WhatsApp is sent it: the approved template the delivery read, else
71
+ * the text, as an interactive message with its buttons when it has them. Link previews stay off.
72
+ */
73
+ function whatsappMessage(input) {
74
+ return (input.payload ??
75
+ (input.buttons === undefined
76
+ ? { type: "text", text: { body: input.finalText, preview_url: false } }
77
+ : whatsappInteractive(input.finalText, input.buttons)));
78
+ }
69
79
  /**
70
80
  * One text message from the workspace's number, `POST /phone/messages` on the connection's
71
81
  * `graph` API, never retried. A Graph refusal with an error code, such as 131047 outside the
72
82
  * 24-hour customer-service window, is definite; a timeout, a 5xx, an unparseable answer or a
73
83
  * success without the message's id is uncertain. `sent` means Meta accepted the message.
84
+ * @legacy ontology.whatsapp-own-sender The ontology's own send of a message without files, which
85
+ * the agent's WhatsApp channel's deliver route does in its place.
74
86
  */
75
87
  export function sendWhatsApp(input) {
76
88
  return Effect.gen(function* () {
77
- const payload = input.payload ??
78
- (input.buttons === undefined
79
- ? { type: "text", text: { body: input.finalText, preview_url: false } }
80
- : whatsappInteractive(input.finalText, input.buttons));
89
+ const payload = whatsappMessage(input);
81
90
  const result = yield* input.transport
82
91
  .request({
83
92
  connection: input.connection,
@@ -141,7 +150,9 @@ export function sendWhatsApp(input) {
141
150
  }
142
151
  /**
143
152
  * WhatsApp: a paired member's chat with the workspace's number, by their WhatsApp id. WhatsApp
144
- * has no group destinations, and a post cannot reply to a message.
153
+ * has no group destinations, and a post cannot reply to a message. The ontology renders the
154
+ * message, its text, buttons or template, and the agent's WhatsApp channel of the chat's name
155
+ * sends it from its number.
145
156
  */
146
157
  export const whatsappProvider = {
147
158
  provider: "whatsapp",
@@ -158,6 +169,138 @@ export const whatsappProvider = {
158
169
  refuseButtons: refuseWhatsAppButtons,
159
170
  files: WHATSAPP_FILE_LIMITS,
160
171
  refuseFiles: refuseWhatsAppFiles,
161
- send: (input) => (input.files ?? []).length > 0 ? sendWhatsAppWithFiles(input) : sendWhatsApp(input),
172
+ send: deliverWhatsApp,
162
173
  template: whatsappTemplate,
163
174
  };
175
+ /**
176
+ * One message, rendered here and sent by the agent's WhatsApp channel; by the ontology itself for
177
+ * an agent without its deliver route.
178
+ */
179
+ function deliverWhatsApp(input) {
180
+ return Effect.gen(function* () {
181
+ if (input.agent?.origin !== undefined && input.agent.identityToken !== undefined) {
182
+ const delivered = yield* deliverThroughAgent(input);
183
+ if (delivered !== undefined) {
184
+ return delivered;
185
+ }
186
+ }
187
+ // @legacy ontology.whatsapp-own-sender The ontology's own WhatsApp sender, for an agent
188
+ // without the WhatsApp channel's deliver route or without a WhatsApp channel of the chat's
189
+ // name on its connection: the message, or each file by a link granted just before it, through
190
+ // the ontology's connection.
191
+ return yield* (input.files ?? []).length > 0
192
+ ? sendWhatsAppWithFiles(input)
193
+ : sendWhatsApp(input);
194
+ });
195
+ }
196
+ /**
197
+ * How long the agent's WhatsApp channel has to send one message: its text or template, or its
198
+ * caption and each of its files, one message each, through the connection.
199
+ */
200
+ const AGENT_DELIVER_TIMEOUT_MS = 90_000;
201
+ /** The refusals the agent's channel may name, as Meta's codes name them. */
202
+ const AGENT_REFUSALS = new Set(Object.values(REFUSALS));
203
+ /**
204
+ * One message through the agent's WhatsApp channel (`POST` {@link whatsappDeliverRoute}), never
205
+ * retried: the channel sends what is rendered here from its number, the message, or the caption
206
+ * and then each file by its link. Undefined when the agent has no such route (`404`) or no
207
+ * WhatsApp channel of the chat's name on this connection (`channel_unknown`), so the ontology
208
+ * sends it itself. The agent's other `4xx` sent nothing, with Meta's refusal of a message without
209
+ * files where it names one; a `2xx` says what reached the person; a timeout, a `5xx` or an answer
210
+ * without its shape may have sent it, and is uncertain.
211
+ */
212
+ function deliverThroughAgent(input) {
213
+ return Effect.gen(function* () {
214
+ const files = input.files ?? [];
215
+ const message = whatsappMessage(input);
216
+ // What the delivery's history keeps, as the ontology's own sender kept it.
217
+ const payload = files.length === 0 ? message : { caption: input.finalText };
218
+ const outcome = (status, results, rest) => ({
219
+ payload: results === undefined
220
+ ? payload
221
+ : {
222
+ ...payload,
223
+ files: results.map((result) => ({
224
+ index: result.index,
225
+ filename: files[result.index]?.filename ?? "",
226
+ status: result.status,
227
+ messageId: result.messageId,
228
+ })),
229
+ },
230
+ status,
231
+ ...rest,
232
+ ...(results === undefined ? {} : { files: results }),
233
+ });
234
+ const unsent = files.length === 0
235
+ ? undefined
236
+ : files.map((_file, index) => ({ index, status: "failed", messageId: null }));
237
+ const links = yield* agentFileLinks(files).pipe(Effect.exit);
238
+ if (links._tag === "Failure") {
239
+ return outcome("failed", unsent, {
240
+ messageId: null,
241
+ url: null,
242
+ cause: Cause.squash(links.cause),
243
+ });
244
+ }
245
+ const body = {
246
+ operation_id: input.operationId ?? input.destination.id,
247
+ connection: input.connection,
248
+ to: input.destination.external_id,
249
+ ...(files.length === 0
250
+ ? { message: message }
251
+ : {
252
+ // A message of files alone has no text to caption them with.
253
+ ...(input.plainText.trim() === "" ? {} : { caption: input.finalText }),
254
+ files: links.value,
255
+ }),
256
+ };
257
+ const answered = yield* postToAgent(input.agent, whatsappDeliverRoute(input.destination.provider), body, AGENT_DELIVER_TIMEOUT_MS).pipe(Effect.exit);
258
+ if (answered._tag === "Failure") {
259
+ return outcome("uncertain", undefined, {
260
+ messageId: null,
261
+ url: null,
262
+ cause: Cause.squash(answered.cause),
263
+ });
264
+ }
265
+ const { status, answer } = answered.value;
266
+ if (status === 404 || (status === 422 && answer.error === "channel_unknown")) {
267
+ return undefined;
268
+ }
269
+ if (status >= 400 && status < 500) {
270
+ const refusal = files.length === 0 &&
271
+ typeof answer.refusal === "string" &&
272
+ AGENT_REFUSALS.has(answer.refusal)
273
+ ? answer.refusal
274
+ : undefined;
275
+ return outcome("failed", unsent, {
276
+ messageId: null,
277
+ url: null,
278
+ cause: new Error(`The agent's WhatsApp channel refused the message (${typeof answer.error === "string" ? answer.error : `status ${status}`}${typeof answer.reference === "string" ? `, reference ${answer.reference}` : ""}).`),
279
+ ...(refusal === undefined ? {} : { refusal }),
280
+ });
281
+ }
282
+ const results = deliveredFiles(answer.files, files.length, WAMID);
283
+ const id = answer.message_id;
284
+ if (status < 200 ||
285
+ status >= 300 ||
286
+ (answer.status !== "sent" && answer.status !== "uncertain") ||
287
+ (id !== null && (typeof id !== "string" || !WAMID.test(id))) ||
288
+ (answer.status === "sent" &&
289
+ (id === null || results?.some((result) => result.status !== "sent") === true)) ||
290
+ (files.length > 0 && results === undefined)) {
291
+ return outcome("uncertain", undefined, {
292
+ messageId: null,
293
+ url: null,
294
+ cause: new Error(`The agent's WhatsApp channel answered with status ${status}.`),
295
+ });
296
+ }
297
+ return answer.status === "sent"
298
+ ? outcome("sent", results, { messageId: id, url: null })
299
+ : outcome("uncertain", results, {
300
+ messageId: id,
301
+ url: null,
302
+ cause: new Error("The agent's WhatsApp channel could not prove every message sent" +
303
+ `${typeof answer.reference === "string" ? ` (reference ${answer.reference})` : ""}.`),
304
+ });
305
+ });
306
+ }
@@ -1,14 +1,15 @@
1
1
  import { type ChannelFile, type ChannelPart, type ChannelRequest, type ChannelStoredFile, type DefiniteFailure } from "./channel-files.js";
2
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. The bytes go on its `files` API, within one request's body,
9
- * or, given a `fetch`, straight to the upload address, which carries its own authorization and
10
- * needs no credential of the connection's: a stored file then streams from the workspace's file
11
- * storage to Slack without being held whole, up to Slack's own bound.
3
+ * Slack's message with files, which the agent's `attachments_send`, the agent's Slack channel's
4
+ * deliver route and the ontology's own sender all send, with Slack's external upload: each file's
5
+ * bytes go to the address `files.getUploadURLExternal` answers, then one
6
+ * `files.completeUploadExternal` shares all of them in the chat with the text, as one visible
7
+ * message. Nothing is visible until that share, so a file that fails to upload is left out without
8
+ * anything reaching the person. The Web API calls go on the connection's `web` API. The bytes go on
9
+ * its `files` API, within one request's body, or, given a `fetch`, straight to the upload address,
10
+ * which carries its own authorization and needs no credential of the connection's: a stored file
11
+ * then streams from the workspace's file storage to Slack without being held whole, up to Slack's
12
+ * own bound.
12
13
  */
13
14
  /** The most bytes of one file a single connection request carries to Slack. */
14
15
  export declare const SLACK_FILE_BYTES: number;
@@ -16,6 +17,11 @@ export declare const SLACK_FILE_BYTES: number;
16
17
  export declare const SLACK_UPLOAD_BYTES: number;
17
18
  /** The most files one `files.completeUploadExternal` shares. */
18
19
  export declare const SLACK_FILES_PER_MESSAGE = 10;
20
+ /**
21
+ * Slack's `ok: false` codes that do not prove a message or a share was not posted: Slack says some
22
+ * of the operation may have succeeded before the error. Every other code proves nothing was.
23
+ */
24
+ export declare const SLACK_POSSIBLY_POSTED: ReadonlySet<string>;
19
25
  /**
20
26
  * Why Slack cannot take this file through one connection request, or, uploaded straight to its
21
27
  * address (`direct`), at all; undefined when it can.
@@ -1,15 +1,16 @@
1
1
  import { ChannelAnswerError, fileSize, isRecord, isStoredFile, replyJson, unrelayed, } from "./channel-files.js";
2
2
  import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
3
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. The bytes go on its `files` API, within one request's body,
10
- * or, given a `fetch`, straight to the upload address, which carries its own authorization and
11
- * needs no credential of the connection's: a stored file then streams from the workspace's file
12
- * storage to Slack without being held whole, up to Slack's own bound.
4
+ * Slack's message with files, which the agent's `attachments_send`, the agent's Slack channel's
5
+ * deliver route and the ontology's own sender all send, with Slack's external upload: each file's
6
+ * bytes go to the address `files.getUploadURLExternal` answers, then one
7
+ * `files.completeUploadExternal` shares all of them in the chat with the text, as one visible
8
+ * message. Nothing is visible until that share, so a file that fails to upload is left out without
9
+ * anything reaching the person. The Web API calls go on the connection's `web` API. The bytes go on
10
+ * its `files` API, within one request's body, or, given a `fetch`, straight to the upload address,
11
+ * which carries its own authorization and needs no credential of the connection's: a stored file
12
+ * then streams from the workspace's file storage to Slack without being held whole, up to Slack's
13
+ * own bound.
13
14
  */
14
15
  /** The most bytes of one file a single connection request carries to Slack. */
15
16
  export const SLACK_FILE_BYTES = MAXIMUM_CONNECTION_BODY_BYTES;
@@ -22,10 +23,10 @@ export const SLACK_FILES_PER_MESSAGE = 10;
22
23
  /** Where Slack's upload addresses are, which the connection's `files` API reaches. */
23
24
  const SLACK_FILES = "https://files.slack.com/";
24
25
  /**
25
- * Slack's `ok: false` codes that do not prove the share was not posted: Slack says some of the
26
- * operation may have succeeded before the error.
26
+ * Slack's `ok: false` codes that do not prove a message or a share was not posted: Slack says some
27
+ * of the operation may have succeeded before the error. Every other code proves nothing was.
27
28
  */
28
- const POSSIBLY_POSTED = new Set([
29
+ export const SLACK_POSSIBLY_POSTED = new Set([
29
30
  "internal_error",
30
31
  "fatal_error",
31
32
  "service_unavailable",
@@ -244,7 +245,7 @@ export async function sendSlackFiles(options) {
244
245
  isRecord(answer) &&
245
246
  answer.ok === false &&
246
247
  error !== "" &&
247
- !POSSIBLY_POSTED.has(error);
248
+ !SLACK_POSSIBLY_POSTED.has(error);
248
249
  return {
249
250
  uploads,
250
251
  share: {
package/dist/slack.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ChannelDeliverFile, ChannelDeliveredFile } from "./channel-files.js";
1
2
  /**
2
3
  * Slack's text for an exact chat post. The ontology service sends it and the agent's
3
4
  * confirmation computes it from the same function, so the digest the member approves and the
@@ -13,6 +14,75 @@ export declare function escapeSlackMarkdown(text: string): string;
13
14
  * Markdown.
14
15
  */
15
16
  export declare function renderSlack(markdown: string, attribution: string, separator?: string): string;
16
- export type { ChannelCall, ChannelCallFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
17
+ /**
18
+ * Where the agent's Slack channel `name` delivers a message the ontology sends: a draft a member
19
+ * approved, a reply its review let go, a member's or a service's post. The ontology decides and
20
+ * renders it, its exact Markdown with its attribution and its buttons; the channel sends it through
21
+ * its app as given, in one operation. Only the deployment's own functions may call it.
22
+ */
23
+ export declare function slackDeliverRoute(name: string): string;
24
+ /**
25
+ * One message as `chat.postMessage` takes it, without where it goes: the Markdown as
26
+ * `markdown_text`, or, with buttons, the text for notifications and the `blocks` that show the
27
+ * Markdown and each row of buttons.
28
+ */
29
+ export type SlackDeliverMessage = {
30
+ readonly markdown_text: string;
31
+ } | {
32
+ readonly text: string;
33
+ readonly blocks: ReadonlyArray<Readonly<Record<string, unknown>>>;
34
+ };
35
+ /** One message for the agent's Slack channel to send (`POST` {@link slackDeliverRoute}). */
36
+ export interface SlackDeliver {
37
+ /** The ontology's delivery, which the agent's diagnostics name. */
38
+ readonly operation_id: string;
39
+ /**
40
+ * The connection the ontology's `chat` names for the channel: the channel sends only through
41
+ * the same app, and answers `channel_unknown` otherwise.
42
+ */
43
+ readonly connection: string;
44
+ /**
45
+ * Where it goes, by Slack's id: a channel, or a member, whose direct message Slack posts a message
46
+ * to; files are shared in the direct message itself, by its own id.
47
+ */
48
+ readonly channel: string;
49
+ /** The `ts` of the thread it goes in, which Slack must confirm; `null` for none. */
50
+ readonly thread_ts: string | null;
51
+ /** The message, for one without files. */
52
+ readonly message?: SlackDeliverMessage;
53
+ /** The text of a message with files, shared with them as one message. */
54
+ readonly initial_comment?: string;
55
+ /**
56
+ * The files, in order, each uploaded and then all shared at once with the text: nothing is
57
+ * shared unless every one uploaded. At most `SLACK_FILES_PER_MESSAGE`.
58
+ */
59
+ readonly files?: ReadonlyArray<ChannelDeliverFile>;
60
+ }
61
+ /**
62
+ * The agent's answer once it sent something: `sent` when Slack's answer proves the message, or the
63
+ * share of the files, posted; `uncertain` when it may have, with what became of each file. A `4xx`
64
+ * with {@link SlackDeliverRefused} sent nothing (`404` alone: an agent without the route); anything
65
+ * else may have sent it.
66
+ */
67
+ export interface SlackDelivered {
68
+ readonly status: "sent" | "uncertain";
69
+ /** The message's `ts`; a share of files Slack's answer names none of has `null`. */
70
+ readonly message_id: string | null;
71
+ readonly files?: ReadonlyArray<ChannelDeliveredFile>;
72
+ /** The agent's diagnostic of what did not go, when something did not. */
73
+ readonly reference?: string;
74
+ }
75
+ /**
76
+ * Why the agent sent nothing (`4xx`): `channel_unknown` when it has no Slack channel of the name on
77
+ * the connection, so the ontology sends the message itself; `provider_refused` when Slack refused
78
+ * it, or refused a file, so that nothing was shared; `connection_refused` when SegmentStream's
79
+ * connection refused the call; or the request's own fault, such as `invalid_request` or
80
+ * `file_too_large`.
81
+ */
82
+ export interface SlackDeliverRefused {
83
+ readonly error: string;
84
+ readonly reference?: string;
85
+ }
86
+ export type { ChannelCall, ChannelCallFile, ChannelDeliverFile, ChannelDeliveredFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
17
87
  export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
18
- export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, SLACK_UPLOAD_BYTES, type SlackFilesResult, } from "./slack-files.js";
88
+ export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, SLACK_POSSIBLY_POSTED, SLACK_UPLOAD_BYTES, type SlackFilesResult, } from "./slack-files.js";
package/dist/slack.js CHANGED
@@ -21,5 +21,14 @@ export function renderSlack(markdown, attribution, separator = "\n\n") {
21
21
  ? markdown
22
22
  : `${markdown}${escapeSlackMarkdown(separator)}_${escapeSlackMarkdown(attribution)}_`;
23
23
  }
24
+ /**
25
+ * Where the agent's Slack channel `name` delivers a message the ontology sends: a draft a member
26
+ * approved, a reply its review let go, a member's or a service's post. The ontology decides and
27
+ * renders it, its exact Markdown with its attribution and its buttons; the channel sends it through
28
+ * its app as given, in one operation. Only the deployment's own functions may call it.
29
+ */
30
+ export function slackDeliverRoute(name) {
31
+ return `/eve/segmentstream/v1/slack/${name}/deliver`;
32
+ }
24
33
  export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
25
- export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, SLACK_UPLOAD_BYTES, } from "./slack-files.js";
34
+ export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, SLACK_POSSIBLY_POSTED, SLACK_UPLOAD_BYTES, } from "./slack-files.js";
@@ -33,10 +33,34 @@ export interface WhatsAppLinkedFile {
33
33
  readonly contentType: string;
34
34
  readonly index?: number;
35
35
  }
36
+ /** Meta's refusals of a message that code acts on, as `WHATSAPP_REFUSALS` names them by code. */
37
+ export type WhatsAppRefusal = "outside_reply_window" | "recipient_unreachable" | "recipient_opted_out";
38
+ /** Meta's message types: a file's, a text, a text with buttons, or an approved template. */
39
+ export type WhatsAppMessageType = WhatsAppFileType | "text" | "interactive" | "template";
36
40
  /** A message WhatsApp accepted, with Meta's type of it and its text or caption. */
37
41
  export interface WhatsAppSentPart extends ChannelPart {
38
- readonly type: WhatsAppFileType | "text";
42
+ readonly type: WhatsAppMessageType;
43
+ /** Meta's refusal of a `failed` message, when its code is one that code acts on. */
44
+ readonly refusal?: WhatsAppRefusal;
39
45
  }
46
+ /**
47
+ * One message to `recipient`, `{ to }` by phone number or `{ recipient }` by business-scoped user
48
+ * id: Meta's `type` and the object of that type, such as `text` and `{ body, preview_url }`, in one
49
+ * `POST /phone/messages` on the connection's `graph` API, never retried; `replyTo` answers a
50
+ * message. It is `sent` when Meta names it; `failed` when Meta refused it with an error code, or
51
+ * when the connection refused the call before relaying it, as `definite` says; and `uncertain`
52
+ * otherwise, as on a 5xx, a lost answer or a success without the message's id.
53
+ */
54
+ export declare function sendWhatsAppMessage(options: {
55
+ readonly request: ChannelRequest;
56
+ readonly recipient: Readonly<Record<string, string>>;
57
+ readonly type: WhatsAppMessageType;
58
+ readonly message: Readonly<Record<string, unknown>>;
59
+ readonly replyTo?: string;
60
+ readonly definite?: DefiniteFailure;
61
+ /** The files and the text the message carries, as its part names them; a text by default. */
62
+ readonly part?: Pick<ChannelPart, "files" | "text">;
63
+ }): Promise<WhatsAppSentPart>;
40
64
  /**
41
65
  * Sends one message per file to `recipient`, `{ to }` by phone number or `{ recipient }` by
42
66
  * business-scoped user id, `caption` with the first; `replyTo` answers a message with the first.
@@ -1,4 +1,5 @@
1
1
  import { ChannelAnswerError, isRecord, jsonCall, replyJson, unrelayed, } from "./channel-files.js";
2
+ import { REFUSALS } from "./service/chat/providers/whatsapp-refusals.js";
2
3
  /** The most bytes WhatsApp fetches of a file of each type. */
3
4
  export const WHATSAPP_FILE_BYTES = {
4
5
  image: 5 * 1024 * 1024,
@@ -38,6 +39,60 @@ export function whatsappFileRefusal(file) {
38
39
  }
39
40
  return undefined;
40
41
  }
42
+ /**
43
+ * One message to `recipient`, `{ to }` by phone number or `{ recipient }` by business-scoped user
44
+ * id: Meta's `type` and the object of that type, such as `text` and `{ body, preview_url }`, in one
45
+ * `POST /phone/messages` on the connection's `graph` API, never retried; `replyTo` answers a
46
+ * message. It is `sent` when Meta names it; `failed` when Meta refused it with an error code, or
47
+ * when the connection refused the call before relaying it, as `definite` says; and `uncertain`
48
+ * otherwise, as on a 5xx, a lost answer or a success without the message's id.
49
+ */
50
+ export async function sendWhatsAppMessage(options) {
51
+ const { type } = options;
52
+ const part = options.part ?? { files: [], text: true };
53
+ let reply;
54
+ try {
55
+ reply = await options.request(jsonCall("graph", "/phone/messages", {
56
+ messaging_product: "whatsapp",
57
+ recipient_type: "individual",
58
+ ...options.recipient,
59
+ ...(options.replyTo === undefined ? {} : { context: { message_id: options.replyTo } }),
60
+ type,
61
+ [type]: options.message,
62
+ }));
63
+ }
64
+ catch (error) {
65
+ return { ...unrelayed(part, error, options.definite), type };
66
+ }
67
+ const answer = replyJson(reply);
68
+ const id = isRecord(answer)
69
+ ? isRecord(Array.isArray(answer.messages) ? answer.messages[0] : undefined)
70
+ ? answer.messages[0].id
71
+ : undefined
72
+ : undefined;
73
+ if (reply.status >= 200 && reply.status < 300 && typeof id === "string" && WAMID.test(id)) {
74
+ return { ...part, type, status: "sent", messageIds: [id] };
75
+ }
76
+ const error = isRecord(answer) && isRecord(answer.error) ? answer.error : undefined;
77
+ const refused = reply.status >= 400 && reply.status < 500 && Number.isInteger(error?.code);
78
+ const refusal = refused ? REFUSALS[Number(error.code)] : undefined;
79
+ return {
80
+ ...part,
81
+ type,
82
+ status: refused ? "failed" : "uncertain",
83
+ messageIds: [],
84
+ code: reply.status === 413
85
+ ? "too_large"
86
+ : reply.status === 401 || reply.status === 403
87
+ ? "forbidden"
88
+ : reply.status >= 200 && reply.status < 300
89
+ ? "invalid_response"
90
+ : "send_failed",
91
+ cause: new ChannelAnswerError(`WhatsApp answered with status ${reply.status}` +
92
+ (Number.isInteger(error?.code) ? ` and code ${String(error.code)}.` : "."), reply.status, reply),
93
+ ...(refusal === undefined ? {} : { refusal }),
94
+ };
95
+ }
41
96
  /**
42
97
  * Sends one message per file to `recipient`, `{ to }` by phone number or `{ recipient }` by
43
98
  * business-scoped user id, `caption` with the first; `replyTo` answers a message with the first.
@@ -51,48 +106,20 @@ export async function sendWhatsAppFiles(options) {
51
106
  let caption = options.caption === "" ? undefined : options.caption;
52
107
  const first = options.files[0];
53
108
  async function send(part, type, message) {
54
- let reply;
55
- try {
56
- reply = await options.request(jsonCall("graph", "/phone/messages", {
57
- messaging_product: "whatsapp",
58
- recipient_type: "individual",
59
- ...options.recipient,
60
- ...(replyTo === undefined ? {} : { context: { message_id: replyTo } }),
61
- type,
62
- [type]: message,
63
- }));
64
- }
65
- catch (error) {
66
- return { ...unrelayed(part, error, options.definite), type };
67
- }
68
- replyTo = undefined;
69
- const answer = replyJson(reply);
70
- const id = isRecord(answer)
71
- ? isRecord(Array.isArray(answer.messages) ? answer.messages[0] : undefined)
72
- ? answer.messages[0].id
73
- : undefined
74
- : undefined;
75
- if (reply.status >= 200 && reply.status < 300 && typeof id === "string" && WAMID.test(id)) {
76
- return { ...part, type, status: "sent", messageIds: [id] };
77
- }
78
- const error = isRecord(answer) && isRecord(answer.error) ? answer.error : undefined;
79
- return {
80
- ...part,
109
+ const sent = await sendWhatsAppMessage({
110
+ request: options.request,
111
+ recipient: options.recipient,
81
112
  type,
82
- status: reply.status >= 400 && reply.status < 500 && Number.isInteger(error?.code)
83
- ? "failed"
84
- : "uncertain",
85
- messageIds: [],
86
- code: reply.status === 413
87
- ? "too_large"
88
- : reply.status === 401 || reply.status === 403
89
- ? "forbidden"
90
- : reply.status >= 200 && reply.status < 300
91
- ? "invalid_response"
92
- : "send_failed",
93
- cause: new ChannelAnswerError(`WhatsApp answered with status ${reply.status}` +
94
- (Number.isInteger(error?.code) ? ` and code ${String(error.code)}.` : "."), reply.status, reply),
95
- };
113
+ message,
114
+ ...(replyTo === undefined ? {} : { replyTo }),
115
+ ...(options.definite === undefined ? {} : { definite: options.definite }),
116
+ part,
117
+ });
118
+ // A message Meta answered, whatever it answered, carried the reply: the next ones do not.
119
+ if (sent.cause === undefined || sent.cause instanceof ChannelAnswerError) {
120
+ replyTo = undefined;
121
+ }
122
+ return sent;
96
123
  }
97
124
  if (caption !== undefined &&
98
125
  (caption.length > WHATSAPP_CAPTION_LIMIT ||
@@ -1,5 +1,7 @@
1
+ import type { ChannelDeliverFile, ChannelDeliveredFile } from "./channel-files.js";
2
+ import type { WhatsAppRefusal } from "./whatsapp-files.js";
1
3
  /**
2
- * WhatsApp's text for an exact chat post. The ontology service sends it and the agent's
4
+ * WhatsApp's text for an exact chat post. The ontology service renders it and the agent's
3
5
  * confirmation computes it from the same function, so the digest the member approves and the
4
6
  * text delivered are the same.
5
7
  */
@@ -18,6 +20,84 @@ export declare function renderWhatsApp(text: string, attribution: string, separa
18
20
  * status's refusal in the message's `failure` with the same code the ontology keeps a send's with.
19
21
  */
20
22
  export { REFUSALS as WHATSAPP_REFUSALS } from "./service/chat/providers/whatsapp-refusals.js";
21
- export type { ChannelCall, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
23
+ /** The most files one message the ontology sends carries, each a WhatsApp message of its own. */
24
+ export declare const WHATSAPP_DELIVER_FILES = 10;
25
+ /**
26
+ * Where the agent's WhatsApp channel `name` delivers a message the ontology sends: a draft a member
27
+ * approved, a reply its review let go, a member's or a service's post. The ontology decides and
28
+ * renders it, its exact text with its attribution, its buttons or its approved template with the
29
+ * values; the channel sends it from its number as given, its messages in order in one operation.
30
+ * Only the deployment's own functions may call it.
31
+ */
32
+ export declare function whatsappDeliverRoute(name: string): string;
33
+ /**
34
+ * One message as WhatsApp's Cloud API takes it, `type` naming the field that holds it: a text
35
+ * (`{ body, preview_url }`), a text with its buttons (`interactive`: reply buttons or one link), or
36
+ * an approved template with its values (`{ name, language: { code }, components? }`).
37
+ */
38
+ export type WhatsAppDeliverMessage = {
39
+ readonly type: "text";
40
+ readonly text: {
41
+ readonly body: string;
42
+ readonly preview_url: boolean;
43
+ };
44
+ } | {
45
+ readonly type: "interactive";
46
+ readonly interactive: Readonly<Record<string, unknown>>;
47
+ } | {
48
+ readonly type: "template";
49
+ readonly template: Readonly<Record<string, unknown>>;
50
+ };
51
+ /** One message for the agent's WhatsApp channel to send (`POST` {@link whatsappDeliverRoute}). */
52
+ export interface WhatsAppDeliver {
53
+ /** The ontology's delivery, which the agent's diagnostics name. */
54
+ readonly operation_id: string;
55
+ /**
56
+ * The connection the ontology's `chat` names for the channel: the channel sends only from the
57
+ * same number, and answers `channel_unknown` otherwise.
58
+ */
59
+ readonly connection: string;
60
+ /** The person, by their WhatsApp id: their number, digits only. */
61
+ readonly to: string;
62
+ /** The message, for one without files. */
63
+ readonly message?: WhatsAppDeliverMessage;
64
+ /**
65
+ * The text of a message with files: the first file's caption, or a text message of its own
66
+ * before them when it is longer than a caption or the first file is audio, which takes none.
67
+ */
68
+ readonly caption?: string;
69
+ /**
70
+ * The files, in order, each a message of its own that WhatsApp fetches by the file's link, at
71
+ * most {@link WHATSAPP_DELIVER_FILES}.
72
+ */
73
+ readonly files?: ReadonlyArray<ChannelDeliverFile>;
74
+ }
75
+ /**
76
+ * The agent's answer once it sent something: `sent` when Meta named every message, `uncertain` when
77
+ * some may not have reached the person, with what became of each file. A `4xx` with
78
+ * {@link WhatsAppDeliverRefused} sent nothing (`404` alone: an agent without the route); anything
79
+ * else may have sent it.
80
+ */
81
+ export interface WhatsAppDelivered {
82
+ readonly status: "sent" | "uncertain";
83
+ /** The first message that reached the person, by Meta's id of it (`wamid.…`). */
84
+ readonly message_id: string | null;
85
+ readonly files?: ReadonlyArray<ChannelDeliveredFile>;
86
+ /** The agent's diagnostic of what did not go, when something did not. */
87
+ readonly reference?: string;
88
+ }
89
+ /**
90
+ * Why the agent sent nothing (`4xx`): `channel_unknown` when it has no WhatsApp channel of the name
91
+ * on the connection, so the ontology sends the message itself; `provider_refused` when Meta refused
92
+ * it; `connection_refused` when SegmentStream's connection refused the call; or the request's own
93
+ * fault, such as `invalid_request` or `file_too_large`.
94
+ */
95
+ export interface WhatsAppDeliverRefused {
96
+ readonly error: string;
97
+ /** Meta's refusal of a message without files, for code to act on, by `WHATSAPP_REFUSALS`. */
98
+ readonly refusal?: WhatsAppRefusal;
99
+ readonly reference?: string;
100
+ }
101
+ export type { ChannelCall, ChannelDeliverFile, ChannelDeliveredFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
22
102
  export { ChannelAnswerError } from "./channel-files.js";
23
- export { sendWhatsAppFiles, whatsappFileRefusal, whatsappFileType, WHATSAPP_CAPTION_LIMIT, WHATSAPP_FILE_BYTES, type WhatsAppFileType, type WhatsAppLinkedFile, type WhatsAppSentPart, } from "./whatsapp-files.js";
103
+ export { sendWhatsAppFiles, sendWhatsAppMessage, whatsappFileRefusal, whatsappFileType, WHATSAPP_CAPTION_LIMIT, WHATSAPP_FILE_BYTES, type WhatsAppFileType, type WhatsAppLinkedFile, type WhatsAppMessageType, type WhatsAppRefusal, type WhatsAppSentPart, } from "./whatsapp-files.js";
package/dist/whatsapp.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * WhatsApp's text for an exact chat post. The ontology service sends it and the agent's
2
+ * WhatsApp's text for an exact chat post. The ontology service renders it and the agent's
3
3
  * confirmation computes it from the same function, so the digest the member approves and the
4
4
  * text delivered are the same.
5
5
  */
@@ -35,5 +35,17 @@ export function renderWhatsApp(text, attribution, separator = "\n\n") {
35
35
  * status's refusal in the message's `failure` with the same code the ontology keeps a send's with.
36
36
  */
37
37
  export { REFUSALS as WHATSAPP_REFUSALS } from "./service/chat/providers/whatsapp-refusals.js";
38
+ /** The most files one message the ontology sends carries, each a WhatsApp message of its own. */
39
+ export const WHATSAPP_DELIVER_FILES = 10;
40
+ /**
41
+ * Where the agent's WhatsApp channel `name` delivers a message the ontology sends: a draft a member
42
+ * approved, a reply its review let go, a member's or a service's post. The ontology decides and
43
+ * renders it, its exact text with its attribution, its buttons or its approved template with the
44
+ * values; the channel sends it from its number as given, its messages in order in one operation.
45
+ * Only the deployment's own functions may call it.
46
+ */
47
+ export function whatsappDeliverRoute(name) {
48
+ return `/eve/segmentstream/v1/whatsapp/${name}/deliver`;
49
+ }
38
50
  export { ChannelAnswerError } from "./channel-files.js";
39
- export { sendWhatsAppFiles, whatsappFileRefusal, whatsappFileType, WHATSAPP_CAPTION_LIMIT, WHATSAPP_FILE_BYTES, } from "./whatsapp-files.js";
51
+ export { sendWhatsAppFiles, sendWhatsAppMessage, whatsappFileRefusal, whatsappFileType, WHATSAPP_CAPTION_LIMIT, WHATSAPP_FILE_BYTES, } from "./whatsapp-files.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.184.0",
3
+ "version": "0.186.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",