@segmentstream/ontology 0.194.0 → 0.195.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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.195.0
4
+
5
+ A Telegram message the ontology sends, a post in either voice, an approved draft or a reply its
6
+ review lets go, shows its Markdown's tables as tables. For Markdown with a table, which MarkdownV2
7
+ shows only as code, the ontology hands the agent's Telegram channel the same message as one rich
8
+ message too (`rich` of the deliver request): the member's Markdown with its links to the app, its
9
+ tables' included, then the attribution in italics in a paragraph of its own. It does so only for a
10
+ message without files that one rich message holds, at most 32,768 characters, 500 blocks and 20
11
+ columns to a table; the MarkdownV2 text and its plain fallback are handed over as before, and the
12
+ channel sends them when Telegram refuses the rich message. The workspace writes Markdown as before.
13
+
14
+ An agent SDK from before rich messages ignores `rich` and sends the text as before, and the
15
+ ontology's own sender, for an agent without the deliver route, sends the text too.
16
+
3
17
  ## 0.194.0
4
18
 
5
19
  Keep the persona and its system instructions for the lifetime of a session. A changed chat assignment starts a fresh session in the same conversation. Browser clients retry an unaccepted message in the new session.
@@ -10,6 +10,13 @@ export { TELEGRAM_MESSAGE_LIMIT };
10
10
  * attribution, as for a reply the agent sends after a member approved it, there is no footer.
11
11
  */
12
12
  export declare function renderTelegram(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string;
13
+ /**
14
+ * The message as one Telegram rich message, for Markdown with a table, which MarkdownV2 shows only
15
+ * as code: the member's Markdown, its links to the app as `renderTelegram` points them, then the
16
+ * attribution. Undefined without a table, beyond what one rich message takes, or when a block the
17
+ * Markdown leaves open, such as a code fence it never closes, would take the attribution in.
18
+ */
19
+ export declare function telegramRichMarkdown(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string | undefined;
13
20
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
14
21
  export declare function telegramKeyboard(rows: ChatButtonRows, links?: ReadonlyMap<string, string>): Readonly<Record<string, unknown>>;
15
22
  /** Where a text goes: the chat, its forum topic and the message it answers. */
@@ -46,6 +53,7 @@ export declare function telegramPart(input: Pick<TelegramSend, "finalText" | "pl
46
53
  export declare function sendTelegram(input: TelegramSend): Effect.Effect<ProviderOutcome>;
47
54
  /**
48
55
  * 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.
56
+ * entity parse refusal and, for Markdown with a table, the rich message that takes its place, and
57
+ * the agent's Telegram channel of the chat's name sends it.
50
58
  */
51
59
  export declare const telegramProvider: ChatProvider;
@@ -1,5 +1,6 @@
1
- import { isTelegramBotUsername, miniAppLink, telegramDeliverRoute, telegramMarkdownLinks, telegramMarkdownWithLinks, telegramTextLinks, telegramPreviewOptions, TELEGRAM_MESSAGE_LIMIT, } from "../../../telegram.js";
1
+ import { isTelegramBotUsername, miniAppLink, telegramDeliverRoute, telegramMarkdownLinks, telegramMarkdownWithLinks, telegramRichMarkdownLinks, telegramTextLinks, telegramPreviewOptions, TELEGRAM_MESSAGE_LIMIT, } from "../../../telegram.js";
2
2
  import { escapeMarkdownV2, TelegramFormatConverter } from "@chat-adapter/telegram";
3
+ import { stringifyMarkdown } from "chat";
3
4
  import { Cause, Effect } from "effect";
4
5
  import { refuseTelegramFiles, sendTelegramWithFiles, TELEGRAM_FILE_LIMITS } from "./files-send.js";
5
6
  import { agentFileLinks, deliveredFiles, postToAgent, record, transportFailure, } from "./provider.js";
@@ -17,6 +18,91 @@ export function renderTelegram(markdown, attribution, separator = "\n\n", links
17
18
  ? body
18
19
  : `${body}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
19
20
  }
21
+ /** What one Telegram rich message takes: its characters, its blocks and a table's columns. */
22
+ const RICH_MESSAGE_CHARACTERS = 32_768;
23
+ const RICH_MESSAGE_BLOCKS = 500;
24
+ const RICH_TABLE_COLUMNS = 20;
25
+ /** The Markdown nodes a rich message shows as blocks of its own; a list's items are in its list. */
26
+ const RICH_BLOCKS = new Set([
27
+ "paragraph",
28
+ "heading",
29
+ "code",
30
+ "math",
31
+ "thematicBreak",
32
+ "blockquote",
33
+ "list",
34
+ "table",
35
+ "html",
36
+ "footnoteDefinition",
37
+ ]);
38
+ /** Every ASCII punctuation character, each of which a backslash makes literal in Markdown. */
39
+ const MARKDOWN_PUNCTUATION = /[!-/:-@[-`{-~]/gu;
40
+ function markdownLiteral(text) {
41
+ return text.replace(MARKDOWN_PUNCTUATION, "\\$&");
42
+ }
43
+ /**
44
+ * The attribution `renderTelegram` writes after the body, as Markdown: the separator's text, then
45
+ * the attribution in italics, each character as written. It is a paragraph of its own, so no block
46
+ * of the body, such as a table, takes it in: the separator's leading line breaks are its break.
47
+ */
48
+ function markdownAttribution(attribution, separator) {
49
+ const lead = markdownLiteral(separator.trimStart()).replace(/^[ \t]+/gmu, "");
50
+ const name = attribution.trim();
51
+ if (name === "") {
52
+ return lead;
53
+ }
54
+ const start = attribution.indexOf(name);
55
+ const end = start + name.length;
56
+ return `${lead}${attribution.slice(0, start)}_${markdownLiteral(name)}_${attribution.slice(end)}`;
57
+ }
58
+ /** The blocks a tree shows, its tables and the most cells a row of them has. */
59
+ function richShape(tree) {
60
+ const shape = { blocks: 0, tables: 0, columns: 0 };
61
+ const pending = [tree];
62
+ for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
63
+ if (RICH_BLOCKS.has(node.type)) {
64
+ shape.blocks += 1;
65
+ }
66
+ if (node.type === "table") {
67
+ shape.tables += 1;
68
+ for (const row of node.children ?? []) {
69
+ shape.columns = Math.max(shape.columns, row.children?.length ?? 0);
70
+ }
71
+ }
72
+ else {
73
+ pending.push(...(node.children ?? []));
74
+ }
75
+ }
76
+ return shape;
77
+ }
78
+ /**
79
+ * The message as one Telegram rich message, for Markdown with a table, which MarkdownV2 shows only
80
+ * as code: the member's Markdown, its links to the app as `renderTelegram` points them, then the
81
+ * attribution. Undefined without a table, beyond what one rich message takes, or when a block the
82
+ * Markdown leaves open, such as a code fence it never closes, would take the attribution in.
83
+ */
84
+ export function telegramRichMarkdown(markdown, attribution, separator = "\n\n", links = new Map()) {
85
+ // A table has pipes: Markdown without one is not parsed again.
86
+ if (!markdown.includes("|")) {
87
+ return undefined;
88
+ }
89
+ const body = links.size === 0 ? markdown : stringifyMarkdown(telegramMarkdownWithLinks(markdown, links));
90
+ const signed = attribution === "" ? "" : markdownAttribution(attribution, separator);
91
+ const rich = signed === "" ? body : `${body}\n\n${signed}`;
92
+ const tree = converter.toAst(rich);
93
+ if (signed !== "" &&
94
+ tree.children.length !==
95
+ converter.toAst(body).children.length + converter.toAst(signed).children.length) {
96
+ return undefined;
97
+ }
98
+ const shape = richShape(tree);
99
+ return shape.tables > 0 &&
100
+ shape.columns <= RICH_TABLE_COLUMNS &&
101
+ shape.blocks <= RICH_MESSAGE_BLOCKS &&
102
+ [...rich].length <= RICH_MESSAGE_CHARACTERS
103
+ ? rich
104
+ : undefined;
105
+ }
20
106
  /**
21
107
  * The usernames of the bots this service looked up, by connection: a `t.me` link names its bot.
22
108
  * Each is kept an hour, as the agent keeps its bot's identity, so links follow a connection that
@@ -226,7 +312,8 @@ function attemptTelegram(input, text, markup) {
226
312
  }
227
313
  /**
228
314
  * 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.
315
+ * entity parse refusal and, for Markdown with a table, the rich message that takes its place, and
316
+ * the agent's Telegram channel of the chat's name sends it.
230
317
  */
231
318
  export const telegramProvider = {
232
319
  provider: "telegram",
@@ -261,8 +348,9 @@ function telegramMessage(input) {
261
348
  ...telegramTextLinks(input.attribution),
262
349
  ];
263
350
  const buttonUrls = (input.buttons ?? []).flatMap((row) => row.flatMap((button) => ("url" in button ? [button.url] : [])));
351
+ // A rich message shows its tables' links, which the formatted text shows as code.
264
352
  const links = yield* miniAppLinksOf(input, [
265
- ...telegramMarkdownLinks(input.text),
353
+ ...telegramRichMarkdownLinks(input.text),
266
354
  ...buttonUrls,
267
355
  ]);
268
356
  // Previews are chosen from the links as written. Telegram previews the first link it gets,
@@ -271,7 +359,12 @@ function telegramMessage(input) {
271
359
  const preview = input.previews?.settings?.linkPreviews === "all" && first !== undefined && links.has(first)
272
360
  ? { link_preview_options: { url: first } }
273
361
  : {};
362
+ // As the Chat SDK sends the agent's own replies: a message with files has no rich message.
363
+ const rich = (input.files ?? []).length > 0
364
+ ? undefined
365
+ : telegramRichMarkdown(input.text, input.attribution, input.separator, links);
274
366
  return {
367
+ ...(rich === undefined ? {} : { rich: { markdown: rich } }),
275
368
  part: telegramPart({
276
369
  finalText: links.size === 0
277
370
  ? input.finalText
@@ -319,11 +412,11 @@ const AGENT_DELIVER_TIMEOUT_MS = 90_000;
319
412
  const MESSAGE_ID = /^[1-9][0-9]*$/;
320
413
  /**
321
414
  * 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.
415
+ * retried: the channel sends the parts rendered here in order, or the rich message in their place,
416
+ * through its bot, then the files by their links. Undefined when the agent has no such route
417
+ * (`404`) or no Telegram channel of the chat's name on this connection (`channel_unknown`), so the
418
+ * ontology sends it itself. The agent's other `4xx` sent nothing; a `2xx` says what reached the
419
+ * person; a timeout, a `5xx` or an answer without its shape may have sent it, and is uncertain.
327
420
  */
328
421
  function deliverThroughAgent(input, message) {
329
422
  return Effect.gen(function* () {
@@ -371,6 +464,7 @@ function deliverThroughAgent(input, message) {
371
464
  reply_to: input.replyTo,
372
465
  // A message of files alone has no text to send, nor to caption them with.
373
466
  parts: input.plainText.trim() === "" ? [] : [message.part],
467
+ ...(message.rich === undefined ? {} : { rich: message.rich }),
374
468
  ...markup,
375
469
  ...(links.value.length === 0 ? {} : { files: links.value }),
376
470
  };
@@ -49,6 +49,8 @@ export declare function telegramPreviewEnvironment(environment: Readonly<Record<
49
49
  */
50
50
  export declare function telegramMarkdownWithLinks(markdown: string, links: ReadonlyMap<string, string>): ReturnType<typeof converter.toAst>;
51
51
  export declare function telegramMarkdownLinks(markdown: string): readonly string[];
52
+ /** The links of Markdown as a rich message shows them: its tables' too, outside code. */
53
+ export declare function telegramRichMarkdownLinks(markdown: string): readonly string[];
52
54
  /** Visible URLs and hidden destinations, excluding formatted code and linked-label lookalikes. */
53
55
  export declare function telegramTextLinks(text: string, entities?: readonly TelegramLinkEntity[]): readonly string[];
54
56
  /** Explicit modern > explicit legacy > channel mode > external default. Never merge caller options. */
@@ -73,8 +75,8 @@ export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
73
75
  * Where the agent's Telegram channel `name` delivers a message the ontology sends: a draft a member
74
76
  * approved, a reply its review let go, a member's or a service's post. The ontology decides and
75
77
  * 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
+ * through its bot, its parts in order, or the rich message that takes their place, in one
79
+ * operation. Only the deployment's own functions may call it.
78
80
  */
79
81
  export declare function telegramDeliverRoute(name: string): string;
80
82
  /** One text as `sendMessage` takes it: the text, its format, and its link preview. */
@@ -92,6 +94,10 @@ export interface TelegramDeliverPart {
92
94
  readonly formatted: TelegramDeliverText;
93
95
  readonly plain: TelegramDeliverText;
94
96
  }
97
+ /** One Telegram rich message as `sendRichMessage` takes it: its Markdown. */
98
+ export interface TelegramDeliverRich {
99
+ readonly markdown: string;
100
+ }
95
101
  /** The most text messages one delivery carries. */
96
102
  export declare const TELEGRAM_DELIVER_PARTS = 20;
97
103
  /** One message for the agent's Telegram channel to send (`POST` {@link telegramDeliverRoute}). */
@@ -115,6 +121,14 @@ export interface TelegramDeliver {
115
121
  * caption goes as the caption of files sent as one message.
116
122
  */
117
123
  readonly parts: ReadonlyArray<TelegramDeliverPart>;
124
+ /**
125
+ * The same message as one rich message, for Markdown with a table, which the parts show only as
126
+ * code: its text, links to the app and attribution, in Markdown, within what one rich message
127
+ * takes. The channel sends it in place of the parts, with the buttons under it, and the parts
128
+ * when Telegram refuses it. Only for a message without files; a channel from before it sends the
129
+ * parts.
130
+ */
131
+ readonly rich?: TelegramDeliverRich;
118
132
  /** The buttons under the last text message: Telegram's inline keyboard. */
119
133
  readonly reply_markup?: Readonly<Record<string, unknown>>;
120
134
  /** The files after the text, in order, each by its link. */
package/dist/telegram.js CHANGED
@@ -136,19 +136,22 @@ export function telegramMarkdownWithLinks(markdown, links) {
136
136
  visit(tree);
137
137
  return tree;
138
138
  }
139
- /** Parse source Markdown, never escaped Telegram MarkdownV2. AST offsets are UTF-16. */
140
- function markdownLinks(markdown, plain = false) {
139
+ /**
140
+ * Parse source Markdown, never escaped Telegram MarkdownV2. AST offsets are UTF-16. `shown` is how
141
+ * Telegram shows it: formatted in MarkdownV2, as plain text, or as a rich message.
142
+ */
143
+ function markdownLinks(markdown, shown = "formatted") {
141
144
  const links = [];
142
145
  const visit = (node, base = 0, depth = 0) => {
143
146
  const offset = base + (node.position?.start.offset ?? 0);
144
147
  if (node.type === "code" || node.type === "inlineCode") {
145
148
  // A formatting fallback sends literal code text, so its URLs become eligible again.
146
- if (plain && depth < 32) {
149
+ if (shown === "plain" && depth < 32) {
147
150
  visit(converter.toAst(node.value), offset, depth + 1);
148
151
  }
149
152
  return;
150
153
  }
151
- if (!plain && node.type === "table") {
154
+ if (shown === "formatted" && node.type === "table") {
152
155
  return; // The existing Telegram renderer renders tables as code.
153
156
  }
154
157
  if (node.type === "link" || node.type === "image") {
@@ -172,13 +175,17 @@ function markdownLinks(markdown, plain = false) {
172
175
  export function telegramMarkdownLinks(markdown) {
173
176
  return markdownLinks(markdown).map((link) => link.url);
174
177
  }
178
+ /** The links of Markdown as a rich message shows them: its tables' too, outside code. */
179
+ export function telegramRichMarkdownLinks(markdown) {
180
+ return markdownLinks(markdown, "rich").map((link) => link.url);
181
+ }
175
182
  /** Visible URLs and hidden destinations, excluding formatted code and linked-label lookalikes. */
176
183
  export function telegramTextLinks(text, entities = []) {
177
184
  const protectedEntities = entities.filter((entity) => ["code", "pre", "text_link", "url"].includes(entity.type));
178
185
  // Literal fallbacks can expose URLs in Markdown labels, definitions or HTML. The URL
179
186
  // tokenizer handles their punctuation without interpreting that text as Markdown.
180
187
  const bare = bareLinks(text);
181
- const parsed = markdownLinks(text, true).flatMap((link) => {
188
+ const parsed = markdownLinks(text, "plain").flatMap((link) => {
182
189
  const offset = text.indexOf(link.url, link.offset);
183
190
  // An embedded Markdown match belongs to the complete visible URL's query/fragment.
184
191
  return offset < 0 || bare.some((visible) => offset > visible.offset && offset < visible.end)
@@ -320,8 +327,8 @@ export const TELEGRAM_MESSAGE_LIMIT = 4096;
320
327
  * Where the agent's Telegram channel `name` delivers a message the ontology sends: a draft a member
321
328
  * approved, a reply its review let go, a member's or a service's post. The ontology decides and
322
329
  * 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.
330
+ * through its bot, its parts in order, or the rich message that takes their place, in one
331
+ * operation. Only the deployment's own functions may call it.
325
332
  */
326
333
  export function telegramDeliverRoute(name) {
327
334
  return `/eve/segmentstream/v1/telegram/${name}/deliver`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.194.0",
3
+ "version": "0.195.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",
@@ -117,6 +117,7 @@
117
117
  "@workflow/utils": "5.1.0",
118
118
  "@workflow/world": "5.2.0",
119
119
  "acorn": "8.15.0",
120
+ "chat": "4.41.0",
120
121
  "devalue": "6.0.3",
121
122
  "jose": "^6.2.12",
122
123
  "marked": "15.0.12",