@segmentstream/ontology 0.183.0 → 0.184.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,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.184.0
4
+
5
+ The ontology's Telegram messages, a post in either voice (`agent_chat.send`), a draft a member
6
+ approves and a reply its review lets go, are rendered as before and handed to the agent's Telegram
7
+ channel of the chat's name at `POST /eve/segmentstream/v1/telegram/<name>/deliver`, which sends them
8
+ through its bot: the exact text in MarkdownV2 with its attribution, links to the app and link
9
+ preview, its text messages in order, the buttons under the last, and the files after the text or
10
+ under it as their caption, each by a short-lived link granted just before. What the channel answers
11
+ is recorded as the ontology's own send was: `sent`, `failed` (with `recipient_unreachable` for a
12
+ person who blocked the bot) or `uncertain`, with each file's result.
13
+
14
+ `@segmentstream/ontology/telegram` exports the route and its wire types: `telegramDeliverRoute`,
15
+ `TelegramDeliver`, `TelegramDeliverPart`, `TelegramDeliverText`, `TelegramDelivered`,
16
+ `TelegramDeliverRefused`, `TELEGRAM_DELIVER_PARTS` and `TELEGRAM_MESSAGE_LIMIT`, and
17
+ `ChannelDeliverFile` and `ChannelDeliveredFile` for a file handed over by its link and what became
18
+ of it.
19
+
20
+ An agent from before the route answers 404, and one without a Telegram channel of the chat's name
21
+ on the connection `chat` names answers `channel_unknown`: the ontology then sends the message
22
+ through that connection itself, as before. This release works with the agent SDK's previous
23
+ release, and the agent SDK's next release works with this ontology SDK's previous one, which never
24
+ calls the route.
25
+
26
+ Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and give
27
+ the agent a Telegram channel of the name of each Telegram channel in the ontology's `chat`, on the
28
+ same connection (`channels.telegram.connection` in `agent/segmentstream.json` naming the connection
29
+ of `chat.telegram`, and so for a channel of another name). The ontology's own Telegram sender, which
30
+ sends for an agent without such a channel, is deprecated and stops on 2027-05-28
31
+ (`ontology.telegram-own-sender`).
32
+
3
33
  ## 0.183.0
4
34
 
5
35
  `agent_chat.send` is the one action that sends a message to a chat, in the voice its new `as`
@@ -88,6 +88,23 @@ export interface ChannelPart {
88
88
  readonly code?: string;
89
89
  readonly cause?: unknown;
90
90
  }
91
+ /**
92
+ * A file the ontology hands an agent's channel to deliver with a message: by a short-lived link to
93
+ * the workspace's file storage, granted just before the message is handed over, which the channel
94
+ * reads it by. `size` is the revision's the ontology checked: bytes of another size are not it.
95
+ */
96
+ export interface ChannelDeliverFile {
97
+ readonly filename: string;
98
+ readonly content_type: string;
99
+ readonly size: number;
100
+ readonly url: string;
101
+ }
102
+ /** What became of one file of a delivery, by its index among the files the request named. */
103
+ export interface ChannelDeliveredFile {
104
+ readonly index: number;
105
+ readonly status: "sent" | "uncertain" | "failed";
106
+ readonly message_id: string | null;
107
+ }
91
108
  /**
92
109
  * The provider's answer to a call that did not prove its message sent, kept whole for operators:
93
110
  * its status and its body, such as Telegram's `description` or Meta's error. Whoever logs it
package/dist/email.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ChannelDeliverFile } from "./channel-files.js";
1
2
  /** The most characters of a reply the mail channel sends in one message. */
2
3
  export declare const EMAIL_MESSAGE_LIMIT = 100000;
3
4
  /** The most addresses one reply goes to, in `To` and `Cc` together. */
@@ -115,12 +116,7 @@ export interface EmailDeliver {
115
116
  /** The reply's key (`X-SegmentStream-Reply`), so a send after a lost answer is found, not repeated. */
116
117
  readonly key: string;
117
118
  /** The reply's files, each by a short-lived link to the workspace's file storage. */
118
- readonly files?: ReadonlyArray<{
119
- readonly filename: string;
120
- readonly content_type: string;
121
- readonly size: number;
122
- readonly url: string;
123
- }>;
119
+ readonly files?: ReadonlyArray<ChannelDeliverFile>;
124
120
  }
125
121
  /**
126
122
  * The agent's answer: `200 { message_id }` once Gmail took the reply. A `4xx` with `{ error }` sent
@@ -136,5 +132,5 @@ export interface EmailDelivered {
136
132
  export declare function emailReplyMessage(reply: EmailReply): string;
137
133
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
138
134
  export declare function base64Url(text: string): string;
139
- export type { ChannelCall, ChannelReply, ChannelRequest } from "./channel-files.js";
135
+ export type { ChannelCall, ChannelDeliverFile, ChannelReply, ChannelRequest, } from "./channel-files.js";
140
136
  export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, mailboxSignature, mailboxSignatures, MAILBOX_SIGNATURE_LIFETIME_MS, sendGmailMessage, } from "./gmail-send.js";
@@ -1,11 +1,11 @@
1
- import { Effect } from "effect";
1
+ import { Cause, Effect } from "effect";
2
2
  import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
3
3
  import { base64Url, emailDeliverRoute, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
4
4
  import { mailboxSignature } from "../../../gmail-send.js";
5
5
  import { ActionRejected } from "../../../errors.js";
6
6
  import { EMAIL_PATTERN } from "../../../property.js";
7
7
  import { describeChatError } from "../diagnostics.js";
8
- import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportCall, transportFailure, } from "./provider.js";
8
+ import { agentFileLinks, channelRequest, definiteTransportFailure, filesWithBytes, postToAgent, record, transportCall, transportFailure, } from "./provider.js";
9
9
  /** A Gmail id, of a thread or a message. */
10
10
  const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
11
11
  const decoder = new TextDecoder();
@@ -117,7 +117,6 @@ const AGENT_DELIVER_TIMEOUT_MS = 90_000;
117
117
  */
118
118
  function deliverThroughAgent(input, reply) {
119
119
  return Effect.gen(function* () {
120
- const agent = input.agent;
121
120
  const payload = {
122
121
  threadId: reply.threadId,
123
122
  to: reply.to,
@@ -132,20 +131,9 @@ function deliverThroughAgent(input, reply) {
132
131
  url: null,
133
132
  cause,
134
133
  });
135
- // Each link is granted just before the reply goes, as the person may still read its file.
136
- const links = yield* Effect.tryPromise(() => Promise.all(reply.files.map(async (file) => {
137
- if (file.link === undefined) {
138
- throw new Error("A file of the reply has no link to read it by.");
139
- }
140
- return {
141
- filename: file.filename,
142
- content_type: file.contentType,
143
- size: file.size,
144
- url: await file.link(),
145
- };
146
- }))).pipe(Effect.exit);
134
+ const links = yield* agentFileLinks(reply.files).pipe(Effect.exit);
147
135
  if (links._tag === "Failure") {
148
- return failed(links.cause);
136
+ return failed(Cause.squash(links.cause));
149
137
  }
150
138
  const body = {
151
139
  thread_id: reply.threadId,
@@ -155,32 +143,20 @@ function deliverThroughAgent(input, reply) {
155
143
  key: reply.key,
156
144
  ...(links.value.length === 0 ? {} : { files: links.value }),
157
145
  };
158
- const answered = yield* Effect.tryPromise(async () => {
159
- const response = await agent.fetch(new Request(new URL(emailDeliverRoute(input.destination.provider), agent.origin), {
160
- method: "POST",
161
- headers: {
162
- authorization: `Bearer ${agent.identityToken}`,
163
- "content-type": "application/json",
164
- },
165
- body: JSON.stringify(body),
166
- signal: AbortSignal.timeout(AGENT_DELIVER_TIMEOUT_MS),
167
- }));
168
- return { status: response.status, text: await response.text() };
169
- }).pipe(Effect.exit);
146
+ const answered = yield* postToAgent(input.agent, emailDeliverRoute(input.destination.provider), body, AGENT_DELIVER_TIMEOUT_MS).pipe(Effect.exit);
170
147
  if (answered._tag === "Failure") {
171
- return { payload, status: "uncertain", messageId: null, url: null, cause: answered.cause };
148
+ return {
149
+ payload,
150
+ status: "uncertain",
151
+ messageId: null,
152
+ url: null,
153
+ cause: Cause.squash(answered.cause),
154
+ };
172
155
  }
173
- const { status, text } = answered.value;
156
+ const { status, answer } = answered.value;
174
157
  if (status === 404) {
175
158
  return undefined;
176
159
  }
177
- let answer = {};
178
- try {
179
- answer = record(JSON.parse(text));
180
- }
181
- catch {
182
- // The status still says what happened; the body only adds the message's id.
183
- }
184
160
  if (status >= 400 && status < 500) {
185
161
  return failed(new Error(`The agent's email channel refused the reply (${typeof answer.error === "string" ? answer.error : `status ${status}`}).`));
186
162
  }
@@ -10,6 +10,8 @@ export declare function refuseTelegramFiles(files: ReadonlyArray<{
10
10
  * Telegram: one message when the text fits a caption and the files go as one file or one album of
11
11
  * one type; otherwise the text, then the files. The text keeps its MarkdownV2, sent again plain when
12
12
  * Telegram refuses its formatting, as a text reply is.
13
+ * @legacy ontology.telegram-own-sender The ontology's own send of a message with files, which the
14
+ * agent's Telegram channel's deliver route does in its place.
13
15
  */
14
16
  export declare function sendTelegramWithFiles(input: ChatSend, sendText: (input: ChatSend) => Effect.Effect<ProviderOutcome>): Effect.Effect<ProviderOutcome>;
15
17
  /** Slack: up to ten files, each one request of the connection. */
@@ -36,6 +36,8 @@ export function refuseTelegramFiles(files) {
36
36
  * Telegram: one message when the text fits a caption and the files go as one file or one album of
37
37
  * one type; otherwise the text, then the files. The text keeps its MarkdownV2, sent again plain when
38
38
  * Telegram refuses its formatting, as a text reply is.
39
+ * @legacy ontology.telegram-own-sender The ontology's own send of a message with files, which the
40
+ * agent's Telegram channel's deliver route does in its place.
39
41
  */
40
42
  export function sendTelegramWithFiles(input, sendText) {
41
43
  return Effect.gen(function* () {
@@ -1,5 +1,5 @@
1
1
  import { Effect, type Exit } from "effect";
2
- import type { ChannelCall, ChannelPart, ChannelRequest } from "../../../channel-files.js";
2
+ import type { ChannelCall, ChannelDeliverFile, 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 ConnectionCall, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
@@ -76,6 +76,20 @@ export interface AgentChannelTransport {
76
76
  readonly identityToken: string | undefined;
77
77
  readonly fetch: (request: Request) => Promise<Response>;
78
78
  }
79
+ /**
80
+ * A send's files as an agent's channel reads them: each by a link to the workspace's file storage,
81
+ * granted now, just before the message is handed over, as the person may still read its file.
82
+ */
83
+ export declare function agentFileLinks(files: ReadonlyArray<ChatSendFile>): Effect.Effect<ReadonlyArray<ChannelDeliverFile>, unknown>;
84
+ /**
85
+ * One `POST` of `body` to an agent's channel route on the deployment's production origin, with
86
+ * the service's Vercel OIDC token, never retried: the agent's status and its JSON answer, `{}` when
87
+ * it answered none. It fails when no answer came, as on a timeout: the agent may have acted on it.
88
+ */
89
+ export declare function postToAgent(agent: AgentChannelTransport, route: string, body: unknown, timeoutMs: number): Effect.Effect<{
90
+ readonly status: number;
91
+ readonly answer: Record<string, unknown>;
92
+ }, unknown>;
79
93
  /** What a provider sends: the exact text its `render` gave, to one resolved destination. */
80
94
  export interface ChatSend {
81
95
  readonly transport: ConnectionTransport["Service"];
@@ -43,6 +43,59 @@ export function filesOutcome(payload, files, parts) {
43
43
  }),
44
44
  };
45
45
  }
46
+ /**
47
+ * A send's files as an agent's channel reads them: each by a link to the workspace's file storage,
48
+ * granted now, just before the message is handed over, as the person may still read its file.
49
+ */
50
+ export function agentFileLinks(files) {
51
+ return Effect.tryPromise({
52
+ try: () => Promise.all(files.map(async (file) => {
53
+ if (file.link === undefined) {
54
+ throw new Error("A file of the message has no link to read it by.");
55
+ }
56
+ return {
57
+ filename: file.filename,
58
+ content_type: file.contentType,
59
+ size: file.size,
60
+ url: await file.link(),
61
+ };
62
+ })),
63
+ catch: (cause) => cause,
64
+ });
65
+ }
66
+ /**
67
+ * One `POST` of `body` to an agent's channel route on the deployment's production origin, with
68
+ * the service's Vercel OIDC token, never retried: the agent's status and its JSON answer, `{}` when
69
+ * it answered none. It fails when no answer came, as on a timeout: the agent may have acted on it.
70
+ */
71
+ export function postToAgent(agent, route, body, timeoutMs) {
72
+ return Effect.tryPromise({
73
+ try: async () => {
74
+ if (agent.origin === undefined || agent.identityToken === undefined) {
75
+ throw new Error("The agent's channels are reachable only from the production deployment.");
76
+ }
77
+ const response = await agent.fetch(new Request(new URL(route, agent.origin), {
78
+ method: "POST",
79
+ headers: {
80
+ authorization: `Bearer ${agent.identityToken}`,
81
+ "content-type": "application/json",
82
+ },
83
+ body: JSON.stringify(body),
84
+ signal: AbortSignal.timeout(timeoutMs),
85
+ }));
86
+ const text = await response.text();
87
+ let answer = {};
88
+ try {
89
+ answer = record(JSON.parse(text));
90
+ }
91
+ catch {
92
+ // The status still says what happened; the body only adds to it.
93
+ }
94
+ return { status: response.status, answer };
95
+ },
96
+ catch: (cause) => cause,
97
+ });
98
+ }
46
99
  /** The connection failures that prove the request never reached the provider. */
47
100
  const DEFINITE_CONNECTION_FAILURES = new Set([
48
101
  "authorization_required",
@@ -1,10 +1,10 @@
1
- import { type TelegramPreviewContext } from "../../../telegram.js";
1
+ import { TELEGRAM_MESSAGE_LIMIT, type TelegramDeliverPart, type TelegramPreviewContext } from "../../../telegram.js";
2
2
  import { Effect } from "effect";
3
3
  import type { ChatButtonRows } from "../../../chat.js";
4
4
  import type { ConnectionTransport } from "../../../connection.js";
5
5
  import type { Destination } from "../resolve.js";
6
6
  import { type ChatProvider, type ProviderOutcome } from "./provider.js";
7
- export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
7
+ export { TELEGRAM_MESSAGE_LIMIT };
8
8
  /**
9
9
  * Render source independently so user Markdown cannot open an entity around the footer. Without an
10
10
  * attribution, as for a reply the agent sends after a member approved it, there is no footer.
@@ -12,27 +12,40 @@ export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
12
12
  export declare function renderTelegram(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string;
13
13
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
14
14
  export declare function telegramKeyboard(rows: ChatButtonRows, links?: ReadonlyMap<string, string>): Readonly<Record<string, unknown>>;
15
- interface TelegramSend {
15
+ /** Where a text goes: the chat, its forum topic and the message it answers. */
16
+ interface TelegramTarget {
16
17
  readonly transport: ConnectionTransport["Service"];
17
18
  readonly connection: string;
18
19
  readonly destination: Destination;
20
+ readonly replyTo: string | null;
21
+ /** The forum topic to send in, for a group with topics. */
22
+ readonly threadId?: string | null;
23
+ }
24
+ interface TelegramSend extends TelegramTarget {
19
25
  /** Links parsed before MarkdownV2 escaping, with the literal attribution added separately. */
20
26
  readonly formattedLinks?: readonly string[];
21
27
  readonly previews?: TelegramPreviewContext;
22
28
  readonly finalText: string;
23
29
  readonly plainText: string;
24
- readonly replyTo: string | null;
25
- /** The forum topic to send in, for a group with topics. */
26
- readonly threadId?: string | null;
27
30
  readonly link_preview_options?: Readonly<Record<string, unknown>>;
28
31
  readonly disable_web_page_preview?: boolean;
29
32
  /** The message's buttons, kept on the plain retry. */
30
33
  readonly replyMarkup?: Readonly<Record<string, unknown>>;
31
34
  }
35
+ /**
36
+ * One text's `sendMessage` fields as Telegram is sent them: the MarkdownV2 text and, for the one
37
+ * retry a refusal of its formatting allows, the plain text, each with the link preview its own
38
+ * links choose.
39
+ */
40
+ export declare function telegramPart(input: Pick<TelegramSend, "finalText" | "plainText" | "formattedLinks" | "previews" | "link_preview_options" | "disable_web_page_preview">): TelegramDeliverPart;
32
41
  /** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
33
42
  * Never retry an unknown outcome; never chunk, truncate or invoke an agent.
43
+ * @legacy ontology.telegram-own-sender The ontology's own send of a text, which the agent's
44
+ * Telegram channel's deliver route does in its place.
34
45
  */
35
46
  export declare function sendTelegram(input: TelegramSend): Effect.Effect<ProviderOutcome>;
36
- /** Telegram: MarkdownV2 with one plain retry after a definite entity parse refusal. */
47
+ /**
48
+ * Telegram: the ontology renders the message, its MarkdownV2 with one plain retry after a definite
49
+ * entity parse refusal, and the agent's Telegram channel of the chat's name sends it.
50
+ */
37
51
  export declare const telegramProvider: ChatProvider;
38
- export {};
@@ -1,9 +1,9 @@
1
- import { isTelegramBotUsername, miniAppLink, telegramMarkdownLinks, telegramMarkdownWithLinks, telegramTextLinks, telegramPreviewOptions, } from "../../../telegram.js";
1
+ import { isTelegramBotUsername, miniAppLink, telegramDeliverRoute, telegramMarkdownLinks, telegramMarkdownWithLinks, telegramTextLinks, telegramPreviewOptions, TELEGRAM_MESSAGE_LIMIT, } from "../../../telegram.js";
2
2
  import { escapeMarkdownV2, TelegramFormatConverter } from "@chat-adapter/telegram";
3
- import { Effect } from "effect";
3
+ import { Cause, Effect } from "effect";
4
4
  import { refuseTelegramFiles, sendTelegramWithFiles, TELEGRAM_FILE_LIMITS } from "./files-send.js";
5
- import { record, transportFailure, } from "./provider.js";
6
- export const TELEGRAM_MESSAGE_LIMIT = 4096;
5
+ import { agentFileLinks, postToAgent, record, transportFailure, } from "./provider.js";
6
+ export { TELEGRAM_MESSAGE_LIMIT };
7
7
  const converter = new TelegramFormatConverter();
8
8
  /**
9
9
  * Render source independently so user Markdown cannot open an entity around the footer. Without an
@@ -88,21 +88,42 @@ export function telegramKeyboard(rows, links = new Map()) {
88
88
  : { text: button.text, callback_data: `ws:${button.token}` })),
89
89
  };
90
90
  }
91
+ /**
92
+ * One text's `sendMessage` fields as Telegram is sent them: the MarkdownV2 text and, for the one
93
+ * retry a refusal of its formatting allows, the plain text, each with the link preview its own
94
+ * links choose.
95
+ */
96
+ export function telegramPart(input) {
97
+ const caller = {
98
+ link_preview_options: input.link_preview_options,
99
+ disable_web_page_preview: input.disable_web_page_preview,
100
+ };
101
+ const preview = (links) => telegramPreviewOptions(caller, links, input.previews);
102
+ return {
103
+ formatted: {
104
+ text: input.finalText,
105
+ parse_mode: "MarkdownV2",
106
+ ...preview(input.formattedLinks ?? telegramMarkdownLinks(input.plainText)),
107
+ },
108
+ plain: { text: input.plainText, ...preview(telegramTextLinks(input.plainText)) },
109
+ };
110
+ }
91
111
  /** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
92
112
  * Never retry an unknown outcome; never chunk, truncate or invoke an agent.
113
+ * @legacy ontology.telegram-own-sender The ontology's own send of a text, which the agent's
114
+ * Telegram channel's deliver route does in its place.
93
115
  */
94
116
  export function sendTelegram(input) {
117
+ return sendTelegramPart(input, telegramPart(input), input.replyMarkup);
118
+ }
119
+ function sendTelegramPart(target, part, replyMarkup) {
95
120
  return Effect.gen(function* () {
96
- const markup = input.replyMarkup === undefined ? {} : { reply_markup: input.replyMarkup };
97
- const formatted = yield* attemptTelegram(input, {
98
- text: input.finalText,
99
- parse_mode: "MarkdownV2",
100
- ...markup,
101
- });
121
+ const markup = replyMarkup === undefined ? {} : { reply_markup: replyMarkup };
122
+ const formatted = yield* attemptTelegram(target, part.formatted, markup);
102
123
  if (!formatted.formattingRefused) {
103
124
  return formatted;
104
125
  }
105
- const plain = yield* attemptTelegram(input, { text: input.plainText, ...markup });
126
+ const plain = yield* attemptTelegram(target, part.plain, markup);
106
127
  return {
107
128
  ...plain,
108
129
  cause: plain.cause === undefined
@@ -111,8 +132,14 @@ export function sendTelegram(input) {
111
132
  };
112
133
  });
113
134
  }
114
- function attemptTelegram(input, payload) {
135
+ function attemptTelegram(input, text, markup) {
115
136
  return Effect.gen(function* () {
137
+ // What the delivery's history keeps: the text and its format, with its buttons.
138
+ const payload = {
139
+ text: text.text,
140
+ ...(text.parse_mode === undefined ? {} : { parse_mode: text.parse_mode }),
141
+ ...markup,
142
+ };
116
143
  const result = yield* input.transport
117
144
  .request({
118
145
  connection: input.connection,
@@ -127,13 +154,8 @@ function attemptTelegram(input, payload) {
127
154
  !/^[1-9][0-9]*$/.test(input.threadId)
128
155
  ? {}
129
156
  : { message_thread_id: Number(input.threadId) }),
130
- ...payload,
131
- ...telegramPreviewOptions({
132
- link_preview_options: input.link_preview_options,
133
- disable_web_page_preview: input.disable_web_page_preview,
134
- }, payload.parse_mode === "MarkdownV2"
135
- ? (input.formattedLinks ?? telegramMarkdownLinks(input.plainText))
136
- : telegramTextLinks(payload.text), input.previews),
157
+ ...text,
158
+ ...markup,
137
159
  ...(input.replyTo === null
138
160
  ? {}
139
161
  : {
@@ -202,7 +224,10 @@ function attemptTelegram(input, payload) {
202
224
  return { payload, status: "sent", messageId, url };
203
225
  });
204
226
  }
205
- /** Telegram: MarkdownV2 with one plain retry after a definite entity parse refusal. */
227
+ /**
228
+ * Telegram: the ontology renders the message, its MarkdownV2 with one plain retry after a definite
229
+ * entity parse refusal, and the agent's Telegram channel of the chat's name sends it.
230
+ */
206
231
  export const telegramProvider = {
207
232
  provider: "telegram",
208
233
  limit: TELEGRAM_MESSAGE_LIMIT,
@@ -221,30 +246,20 @@ export const telegramProvider = {
221
246
  refuseButtons: () => undefined,
222
247
  files: TELEGRAM_FILE_LIMITS,
223
248
  refuseFiles: refuseTelegramFiles,
224
- send: (input) => (input.files ?? []).length > 0 ? sendTelegramFilesReply(input) : sendTelegramText(input),
249
+ send: sendTelegramMessage,
225
250
  };
226
251
  /**
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.
252
+ * The member's Markdown as Telegram is sent it, with the chat's links to the app and previews: only
253
+ * where a link to the app leads changes, so the text reads as the member approved it. A text that
254
+ * goes as the caption of files is the same, so its links open in the bot's Mini App too.
229
255
  */
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) {
256
+ function telegramMessage(input) {
241
257
  return Effect.gen(function* () {
242
258
  const written = [
243
259
  ...telegramMarkdownLinks(input.text),
244
260
  ...telegramTextLinks(input.separator),
245
261
  ...telegramTextLinks(input.attribution),
246
262
  ];
247
- // Only where a link to the app leads changes: the text reads as the member approved it.
248
263
  const buttonUrls = (input.buttons ?? []).flatMap((row) => row.flatMap((button) => ("url" in button ? [button.url] : [])));
249
264
  const links = yield* miniAppLinksOf(input, [
250
265
  ...telegramMarkdownLinks(input.text),
@@ -256,22 +271,179 @@ function sendTelegramText(input) {
256
271
  const preview = input.previews?.settings?.linkPreviews === "all" && first !== undefined && links.has(first)
257
272
  ? { link_preview_options: { url: first } }
258
273
  : {};
259
- return yield* sendTelegram({
260
- transport: input.transport,
261
- connection: input.connection,
262
- destination: input.destination,
263
- finalText: links.size === 0
264
- ? input.finalText
265
- : renderTelegram(input.text, input.attribution, input.separator, links),
266
- formattedLinks: written,
267
- ...(input.previews === undefined ? {} : { previews: input.previews }),
268
- ...preview,
269
- plainText: input.plainText,
270
- replyTo: input.replyTo,
271
- ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
274
+ return {
275
+ part: telegramPart({
276
+ finalText: links.size === 0
277
+ ? input.finalText
278
+ : renderTelegram(input.text, input.attribution, input.separator, links),
279
+ plainText: input.plainText,
280
+ formattedLinks: written,
281
+ ...(input.previews === undefined ? {} : { previews: input.previews }),
282
+ ...preview,
283
+ }),
272
284
  ...(input.buttons === undefined
273
285
  ? {}
274
286
  : { replyMarkup: telegramKeyboard(input.buttons, links) }),
287
+ };
288
+ });
289
+ }
290
+ /**
291
+ * One message, rendered here and sent by the agent's Telegram channel; by the ontology itself for
292
+ * an agent without its deliver route.
293
+ */
294
+ function sendTelegramMessage(input) {
295
+ return Effect.gen(function* () {
296
+ const message = yield* telegramMessage(input);
297
+ if (input.agent?.origin !== undefined && input.agent.identityToken !== undefined) {
298
+ const delivered = yield* deliverThroughAgent(input, message);
299
+ if (delivered !== undefined) {
300
+ return delivered;
301
+ }
302
+ }
303
+ // @legacy ontology.telegram-own-sender The ontology's own Telegram sender, for an agent
304
+ // without the Telegram channel's deliver route or without a Telegram channel of the chat's
305
+ // name on its connection: the text, then the files' bytes, read and checked before the message
306
+ // was reserved, through the ontology's connection.
307
+ const text = () => sendTelegramPart(input, message.part, message.replyMarkup);
308
+ return yield* (input.files ?? []).length > 0
309
+ ? sendTelegramWithFiles({ ...input, finalText: message.part.formatted.text }, text)
310
+ : text();
311
+ });
312
+ }
313
+ /**
314
+ * How long the agent's Telegram channel has to send one message: its texts, then its files, each
315
+ * through the connection.
316
+ */
317
+ const AGENT_DELIVER_TIMEOUT_MS = 90_000;
318
+ /** A message id Telegram names. */
319
+ const MESSAGE_ID = /^[1-9][0-9]*$/;
320
+ /**
321
+ * One message through the agent's Telegram channel (`POST` {@link telegramDeliverRoute}), never
322
+ * retried: the channel sends the parts rendered here in order, through its bot, then the files by
323
+ * their links. Undefined when the agent has no such route (`404`) or no Telegram channel of the
324
+ * chat's name on this connection (`channel_unknown`), so the ontology sends it itself. The agent's
325
+ * other `4xx` sent nothing; a `2xx` says what reached the person; a timeout, a `5xx` or an answer
326
+ * without its shape may have sent it, and is uncertain.
327
+ */
328
+ function deliverThroughAgent(input, message) {
329
+ return Effect.gen(function* () {
330
+ const files = input.files ?? [];
331
+ const markup = message.replyMarkup === undefined ? {} : { reply_markup: message.replyMarkup };
332
+ const payload = {
333
+ text: message.part.formatted.text,
334
+ parse_mode: "MarkdownV2",
335
+ ...markup,
336
+ };
337
+ // What became of each file, as the history keeps it, by its name.
338
+ const outcome = (status, results, rest) => ({
339
+ payload: results === undefined
340
+ ? payload
341
+ : {
342
+ ...payload,
343
+ files: results.map((result) => ({
344
+ ...result,
345
+ filename: files[result.index]?.filename ?? "",
346
+ })),
347
+ },
348
+ status,
349
+ ...rest,
350
+ ...(results === undefined ? {} : { files: results }),
275
351
  });
352
+ const unsent = files.length === 0
353
+ ? undefined
354
+ : files.map((_file, index) => ({ index, status: "failed", messageId: null }));
355
+ const links = yield* agentFileLinks(files).pipe(Effect.exit);
356
+ if (links._tag === "Failure") {
357
+ return outcome("failed", unsent, {
358
+ messageId: null,
359
+ url: null,
360
+ cause: Cause.squash(links.cause),
361
+ });
362
+ }
363
+ const thread = typeof input.threadId === "string" && /^[1-9][0-9]*$/u.test(input.threadId)
364
+ ? input.threadId
365
+ : null;
366
+ const body = {
367
+ operation_id: input.operationId ?? input.destination.id,
368
+ connection: input.connection,
369
+ chat_id: input.destination.external_id,
370
+ thread_id: thread,
371
+ reply_to: input.replyTo,
372
+ // A message of files alone has no text to send, nor to caption them with.
373
+ parts: input.plainText.trim() === "" ? [] : [message.part],
374
+ ...markup,
375
+ ...(links.value.length === 0 ? {} : { files: links.value }),
376
+ };
377
+ const answered = yield* postToAgent(input.agent, telegramDeliverRoute(input.destination.provider), body, AGENT_DELIVER_TIMEOUT_MS).pipe(Effect.exit);
378
+ if (answered._tag === "Failure") {
379
+ return outcome("uncertain", undefined, {
380
+ messageId: null,
381
+ url: null,
382
+ cause: Cause.squash(answered.cause),
383
+ });
384
+ }
385
+ const { status, answer } = answered.value;
386
+ if (status === 404 || (status === 422 && answer.error === "channel_unknown")) {
387
+ return undefined;
388
+ }
389
+ if (status >= 400 && status < 500) {
390
+ return outcome("failed", unsent, {
391
+ messageId: null,
392
+ url: null,
393
+ cause: new Error(`The agent's Telegram channel refused the message (${typeof answer.error === "string" ? answer.error : `status ${status}`}${typeof answer.reference === "string" ? `, reference ${answer.reference}` : ""}).`),
394
+ ...(answer.refusal === "recipient_unreachable"
395
+ ? { refusal: "recipient_unreachable" }
396
+ : {}),
397
+ });
398
+ }
399
+ const results = deliveredFiles(answer.files, files.length);
400
+ const id = answer.message_id;
401
+ const url = typeof answer.url === "string" && answer.url.startsWith("https://t.me/") ? answer.url : null;
402
+ if (status < 200 ||
403
+ status >= 300 ||
404
+ (answer.status !== "sent" && answer.status !== "uncertain") ||
405
+ (id !== null && (typeof id !== "string" || !MESSAGE_ID.test(id))) ||
406
+ (answer.status === "sent" &&
407
+ (id === null || results?.some((result) => result.status !== "sent") === true)) ||
408
+ (files.length > 0 && results === undefined)) {
409
+ return outcome("uncertain", undefined, {
410
+ messageId: null,
411
+ url: null,
412
+ cause: new Error(`The agent's Telegram channel answered with status ${status}.`),
413
+ });
414
+ }
415
+ return answer.status === "sent"
416
+ ? outcome("sent", results, { messageId: id, url })
417
+ : outcome("uncertain", results, {
418
+ messageId: id,
419
+ url,
420
+ cause: new Error("The agent's Telegram channel could not prove every message sent" +
421
+ `${typeof answer.reference === "string" ? ` (reference ${answer.reference})` : ""}.`),
422
+ });
423
+ });
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;
276
445
  });
446
+ return results.every((result) => result !== undefined)
447
+ ? results
448
+ : undefined;
277
449
  }
@@ -1,4 +1,5 @@
1
1
  import { TelegramFormatConverter } from "@chat-adapter/telegram";
2
+ import type { ChannelDeliverFile, ChannelDeliveredFile } from "./channel-files.js";
2
3
  /**
3
4
  * Private chats and basic groups number messages per account. Supergroup and channel
4
5
  * message numbers are shared. Their Bot API peer IDs start below -1000000000000.
@@ -66,6 +67,88 @@ export declare function telegramStartParam(page: string): string | undefined;
66
67
  export declare function miniAppLink(url: string, origins: ReadonlySet<string>, botUsername: string): string | undefined;
67
68
  /** A username Telegram accepts in a `t.me` link; any other leaves every link as it is. */
68
69
  export declare function isTelegramBotUsername(username: string): boolean;
69
- export type { ChannelCall, ChannelCallFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
70
+ /** The most characters Telegram takes in one message's text. */
71
+ export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
72
+ /**
73
+ * Where the agent's Telegram channel `name` delivers a message the ontology sends: a draft a member
74
+ * approved, a reply its review let go, a member's or a service's post. The ontology decides and
75
+ * renders it, its exact text with its attribution, links and previews; the channel sends it
76
+ * through its bot, its parts in order in one operation. Only the deployment's own functions may
77
+ * call it.
78
+ */
79
+ export declare function telegramDeliverRoute(name: string): string;
80
+ /** One text as `sendMessage` takes it: the text, its format, and its link preview. */
81
+ export interface TelegramDeliverText {
82
+ readonly text: string;
83
+ readonly parse_mode?: "MarkdownV2";
84
+ readonly link_preview_options?: Readonly<Record<string, unknown>>;
85
+ readonly disable_web_page_preview?: boolean;
86
+ }
87
+ /**
88
+ * One text message of a delivery: as Telegram formats it, and the same text without formatting,
89
+ * which is sent once in its place only when Telegram refuses the formatting.
90
+ */
91
+ export interface TelegramDeliverPart {
92
+ readonly formatted: TelegramDeliverText;
93
+ readonly plain: TelegramDeliverText;
94
+ }
95
+ /** The most text messages one delivery carries. */
96
+ export declare const TELEGRAM_DELIVER_PARTS = 20;
97
+ /** One message for the agent's Telegram channel to send (`POST` {@link telegramDeliverRoute}). */
98
+ export interface TelegramDeliver {
99
+ /** The ontology's delivery, which the agent's diagnostics name. */
100
+ readonly operation_id: string;
101
+ /**
102
+ * The connection the ontology's `chat` names for the channel: the channel sends only through
103
+ * the same bot, and answers `channel_unknown` otherwise.
104
+ */
105
+ readonly connection: string;
106
+ /** The chat, by its Bot API id. */
107
+ readonly chat_id: string;
108
+ /** The forum topic to send in (`message_thread_id`); null outside one. */
109
+ readonly thread_id: string | null;
110
+ /** The message each text message answers, which Telegram must quote; null for none. */
111
+ readonly reply_to: string | null;
112
+ /**
113
+ * The text messages, in order, each rendered from a text of at most
114
+ * {@link TELEGRAM_MESSAGE_LIMIT} characters; none for files alone. A single text that fits a
115
+ * caption goes as the caption of files sent as one message.
116
+ */
117
+ readonly parts: ReadonlyArray<TelegramDeliverPart>;
118
+ /** The buttons under the last text message: Telegram's inline keyboard. */
119
+ readonly reply_markup?: Readonly<Record<string, unknown>>;
120
+ /** The files after the text, in order, each by its link. */
121
+ readonly files?: ReadonlyArray<ChannelDeliverFile>;
122
+ }
123
+ /**
124
+ * The agent's answer once it sent something: `sent` when Telegram's answers prove every message,
125
+ * `uncertain` when some may not have reached the person, with what became of each file. A `4xx`
126
+ * with {@link TelegramDeliverRefused} sent nothing (`404` alone: an agent without the route);
127
+ * anything else may have sent it.
128
+ */
129
+ export interface TelegramDelivered {
130
+ readonly status: "sent" | "uncertain";
131
+ /** The first message that reached the person. */
132
+ readonly message_id: string | null;
133
+ /** That message's link, for a group Telegram links to; null otherwise and with files. */
134
+ readonly url: string | null;
135
+ readonly files?: ReadonlyArray<ChannelDeliveredFile>;
136
+ /** The agent's diagnostic of what did not go, when something did not. */
137
+ readonly reference?: string;
138
+ }
139
+ /**
140
+ * Why the agent sent nothing (`4xx`): `channel_unknown` when it has no Telegram channel of the
141
+ * name on the connection, so the ontology sends the message itself; `provider_refused` when
142
+ * Telegram refused it; `thread_unavailable` when Telegram no longer has the topic;
143
+ * `connection_refused` when SegmentStream's connection refused the call; or the request's own
144
+ * fault, such as `invalid_request` or `file_unavailable`.
145
+ */
146
+ export interface TelegramDeliverRefused {
147
+ readonly error: string;
148
+ /** Telegram's refusal for code to act on: a person who blocked the bot or never started it. */
149
+ readonly refusal?: "recipient_unreachable";
150
+ readonly reference?: string;
151
+ }
152
+ export type { ChannelCall, ChannelCallFile, ChannelDeliverFile, ChannelDeliveredFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
70
153
  export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
71
154
  export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_INLINE_FILE_BYTES, TELEGRAM_PHOTO_BYTES, type TelegramEntity, type TelegramFilesTarget, type TelegramFormattedText, } from "./telegram-files.js";
package/dist/telegram.js CHANGED
@@ -314,5 +314,19 @@ export function miniAppLink(url, origins, botUsername) {
314
314
  export function isTelegramBotUsername(username) {
315
315
  return /^[A-Za-z0-9_]{1,64}$/u.test(username);
316
316
  }
317
+ /** The most characters Telegram takes in one message's text. */
318
+ export const TELEGRAM_MESSAGE_LIMIT = 4096;
319
+ /**
320
+ * Where the agent's Telegram channel `name` delivers a message the ontology sends: a draft a member
321
+ * approved, a reply its review let go, a member's or a service's post. The ontology decides and
322
+ * renders it, its exact text with its attribution, links and previews; the channel sends it
323
+ * through its bot, its parts in order in one operation. Only the deployment's own functions may
324
+ * call it.
325
+ */
326
+ export function telegramDeliverRoute(name) {
327
+ return `/eve/segmentstream/v1/telegram/${name}/deliver`;
328
+ }
329
+ /** The most text messages one delivery carries. */
330
+ export const TELEGRAM_DELIVER_PARTS = 20;
317
331
  export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
318
332
  export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_INLINE_FILE_BYTES, TELEGRAM_PHOTO_BYTES, } from "./telegram-files.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.183.0",
3
+ "version": "0.184.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",