@segmentstream/ontology 0.179.0 → 0.181.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/channel-files.d.ts +40 -0
  3. package/dist/channel-files.js +10 -0
  4. package/dist/review.d.ts +46 -0
  5. package/dist/review.js +47 -0
  6. package/dist/runtime/agents.js +28 -4
  7. package/dist/service/agent/protocol.d.ts +51 -0
  8. package/dist/service/agent/protocol.js +66 -1
  9. package/dist/service/agent/server.d.ts +8 -0
  10. package/dist/service/agent/server.js +166 -1
  11. package/dist/service/chat/archive.d.ts +8 -1
  12. package/dist/service/chat/delivery.js +3 -1
  13. package/dist/service/chat/providers/custom.js +2 -0
  14. package/dist/service/chat/providers/email.js +2 -2
  15. package/dist/service/chat/providers/provider.d.ts +15 -2
  16. package/dist/service/chat/providers/provider.js +18 -1
  17. package/dist/service/chat/reply-proposal.d.ts +122 -0
  18. package/dist/service/chat/reply-proposal.js +385 -0
  19. package/dist/service/chat/review-delivery.d.ts +131 -24
  20. package/dist/service/chat/review-delivery.js +393 -296
  21. package/dist/service/chat/store-delivery.d.ts +27 -5
  22. package/dist/service/chat/store-delivery.js +45 -33
  23. package/dist/service/runtime-contract.d.ts +30 -0
  24. package/dist/service/service.js +12 -4
  25. package/dist/slack-files.d.ts +23 -5
  26. package/dist/slack-files.js +108 -16
  27. package/dist/slack.d.ts +3 -3
  28. package/dist/slack.js +2 -2
  29. package/dist/telegram-files.d.ts +27 -7
  30. package/dist/telegram-files.js +111 -31
  31. package/dist/telegram.d.ts +3 -3
  32. package/dist/telegram.js +2 -2
  33. package/dist/workspace-channel.d.ts +6 -0
  34. package/dist/workspace-channel.js +27 -0
  35. package/package.json +5 -1
@@ -1,4 +1,4 @@
1
- import { ChannelAnswerError, isRecord, replyJson, unrelayed, } from "./channel-files.js";
1
+ import { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError, isRecord, isStoredFile, replyJson, unrelayed, } from "./channel-files.js";
2
2
  import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
3
3
  /**
4
4
  * Telegram's message with files, which the agent's `attachments_send` and the ontology's delivery
@@ -6,6 +6,12 @@ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
6
6
  * the caption on the first. Photos go as photos and other files as documents; consecutive files of
7
7
  * one type go together as an album of at most ten, as long as one request carries them. Each
8
8
  * request is one multipart call on the connection's `bot` API.
9
+ *
10
+ * A file sent by its signed read (`ChannelStoredFile`) goes alone in its message: the connection
11
+ * reads its bytes from the workspace's file storage and sends them inside the form the sender
12
+ * builds around them, so it is held to Telegram's own bounds, not to the connection's request
13
+ * body. Telegram also fetches files by URL, but only up to 5 MB for a photo and 20 MB for another
14
+ * file, and a document only as PDF or ZIP, so every file goes as an upload.
9
15
  */
10
16
  /** The most bytes Telegram takes of a photo. */
11
17
  export const TELEGRAM_PHOTO_BYTES = 10 * 1024 * 1024;
@@ -21,18 +27,24 @@ const PHOTOS = new Set(["image/jpeg", "image/png", "image/webp"]);
21
27
  export function telegramFileType(contentType) {
22
28
  return PHOTOS.has(contentType.toLowerCase().split(";")[0].trim()) ? "photo" : "document";
23
29
  }
30
+ /**
31
+ * The most bytes of a file sent in a request's own body, which leaves room in the connection's
32
+ * request bound for the form around it. Files this small can go together as an album; a larger
33
+ * one goes by its signed read, alone in its message.
34
+ */
35
+ export const TELEGRAM_INLINE_FILE_BYTES = MAXIMUM_CONNECTION_BODY_BYTES - CHANNEL_FILE_FRAME_BYTES;
24
36
  /**
25
37
  * Why Telegram cannot take this file through one connection request, or undefined when it can:
26
- * `too_large` past Telegram's bound for its type or the connection's request bound, `empty` for no
27
- * bytes.
38
+ * `too_large` past Telegram's bound for its type or, unless the file may go by its signed read
39
+ * (`stored`), the connection's request bound; `empty` for no bytes.
28
40
  */
29
- export function telegramFileRefusal(file) {
41
+ export function telegramFileRefusal(file, options = {}) {
30
42
  const type = telegramFileType(file.contentType);
31
43
  const maximum = type === "photo" ? TELEGRAM_PHOTO_BYTES : TELEGRAM_DOCUMENT_BYTES;
32
44
  if (file.size > maximum) {
33
45
  return { code: "too_large", message: `Telegram's ${type} limit is ${maximum} bytes.` };
34
46
  }
35
- if (file.size > MAXIMUM_CONNECTION_BODY_BYTES) {
47
+ if (options.stored !== true && file.size > MAXIMUM_CONNECTION_BODY_BYTES) {
36
48
  return { code: "too_large", message: TELEGRAM_REQUEST_LIMIT };
37
49
  }
38
50
  if (file.size === 0) {
@@ -40,7 +52,7 @@ export function telegramFileRefusal(file) {
40
52
  }
41
53
  return undefined;
42
54
  }
43
- /** The most bytes of one file a single connection request can carry to Telegram. */
55
+ /** The most bytes of one file a single connection request can carry to Telegram in its body. */
44
56
  export function telegramFileBytes(contentType) {
45
57
  return Math.min(telegramFileType(contentType) === "photo" ? TELEGRAM_PHOTO_BYTES : TELEGRAM_DOCUMENT_BYTES, MAXIMUM_CONNECTION_BODY_BYTES);
46
58
  }
@@ -96,10 +108,15 @@ export function telegramFormattingRefused(status, body) {
96
108
  (/can't parse entities|cannot parse entities|entity (?:bounds|offset|length)|entities (?:are|too)/iu.test(body.description) ||
97
109
  /unsupported (?:start tag|parse mode)/iu.test(body.description)));
98
110
  }
99
- /** One multipart request of files: one file by its type's method, several as an album. */
111
+ /**
112
+ * One multipart request of files: one file by its type's method, several as an album. Each file's
113
+ * part comes after every field, and a stored file's part is empty: its bytes are not here.
114
+ */
100
115
  async function multipart(target, files, caption) {
101
116
  const form = new FormData();
102
- const blob = (upload) => new Blob([Buffer.from(upload.file.bytes)], { type: upload.file.contentType });
117
+ const blob = (upload) => new Blob(isStoredFile(upload.file) ? [] : [Buffer.from(upload.file.bytes)], {
118
+ type: upload.file.contentType,
119
+ });
103
120
  form.set("chat_id", target.chatId);
104
121
  if (target.messageThreadId !== undefined && /^\d+$/u.test(target.messageThreadId)) {
105
122
  form.set("message_thread_id", target.messageThreadId);
@@ -109,7 +126,6 @@ async function multipart(target, files, caption) {
109
126
  }
110
127
  if (files.length === 1) {
111
128
  const upload = files[0];
112
- form.set(upload.type, blob(upload), upload.file.filename);
113
129
  if (caption !== undefined) {
114
130
  // The form sends its line breaks as CRLF anyway; the entities must count them so.
115
131
  const sent = withCrlfLineBreaks(caption);
@@ -121,6 +137,8 @@ async function multipart(target, files, caption) {
121
137
  form.set("parse_mode", caption.parseMode);
122
138
  }
123
139
  }
140
+ // Last, so that a stored file's bytes go right before the form's closing boundary.
141
+ form.set(upload.type, blob(upload), upload.file.filename);
124
142
  }
125
143
  else {
126
144
  form.set("media", JSON.stringify(files.map((upload, index) => ({
@@ -148,6 +166,59 @@ async function multipart(target, files, caption) {
148
166
  body: new Uint8Array(await request.arrayBuffer()),
149
167
  };
150
168
  }
169
+ const TELEGRAM_FRAME_LIMIT = `The form around a stored file exceeds the connection's ` +
170
+ `${CHANNEL_FILE_FRAME_BYTES}-byte bound before and after it.`;
171
+ /** A stored file's request that could not be built, so nothing of it was sent. */
172
+ class FramingError extends Error {
173
+ code;
174
+ name = "FramingError";
175
+ constructor(code, message, cause) {
176
+ super(message, cause === undefined ? undefined : { cause });
177
+ this.code = code;
178
+ }
179
+ }
180
+ /**
181
+ * The form of one stored file, split where its bytes go: everything before them, and the closing
182
+ * boundary after them. The form's last part is the file's, which is empty here, so what follows
183
+ * it is exactly the boundary's close.
184
+ */
185
+ function framing(built) {
186
+ const boundary = /;\s*boundary="?([^";]+)"?/u.exec(built.contentType)?.[1];
187
+ const suffix = new TextEncoder().encode(`\r\n--${boundary ?? ""}--\r\n`);
188
+ const tail = built.body.subarray(built.body.byteLength - suffix.byteLength);
189
+ if (boundary === undefined ||
190
+ built.body.byteLength < suffix.byteLength ||
191
+ !Buffer.from(tail).equals(Buffer.from(suffix))) {
192
+ throw new FramingError("send_failed", "The form does not end with the file's part.");
193
+ }
194
+ return { prefix: built.body.slice(0, built.body.byteLength - suffix.byteLength), suffix };
195
+ }
196
+ /**
197
+ * The call of one stored file's form: the form around the file's part as the call's prefix and
198
+ * suffix, and a fresh signed read of the file, which the connection reads and sends between them.
199
+ */
200
+ async function storedCall(message, file) {
201
+ const { prefix, suffix } = framing(message);
202
+ if (prefix.byteLength > CHANNEL_FILE_FRAME_BYTES ||
203
+ suffix.byteLength > CHANNEL_FILE_FRAME_BYTES) {
204
+ throw new FramingError("too_large", TELEGRAM_FRAME_LIMIT);
205
+ }
206
+ let read;
207
+ try {
208
+ read = await file.read();
209
+ }
210
+ catch (error) {
211
+ throw new FramingError("unavailable", "The file's signed read could not be had.", error);
212
+ }
213
+ return {
214
+ api: "bot",
215
+ method: "POST",
216
+ path: `/${message.method}`,
217
+ headers: [["content-type", message.contentType]],
218
+ body: new Uint8Array(),
219
+ file: { ...read, start: 0, end: file.size - 1, prefix, suffix },
220
+ };
221
+ }
151
222
  /** The message ids Telegram's answer to a batch names, one per file, or undefined. */
152
223
  function messageIds(answer, count) {
153
224
  if (!isRecord(answer) || answer.ok !== true) {
@@ -160,12 +231,18 @@ function messageIds(answer, count) {
160
231
  ? messages.map((message) => String(message.message_id))
161
232
  : undefined;
162
233
  }
234
+ /** A part whose request was never sent: nothing of it reached the person. */
235
+ function unsent(part, code, cause) {
236
+ return { ...part, status: "failed", messageIds: [], code, cause };
237
+ }
163
238
  /**
164
239
  * Sends `files` to `target` in their order, `caption` on the first message Telegram takes. Each
165
240
  * album is one request and one part: `sent` when Telegram names its messages, `failed` when it
166
241
  * refused them (`too_large` for 413, `forbidden` for 403, `send_failed` otherwise) or a request
167
- * could not be built, `uncertain` when its answer proves neither. A refusal of the caption's
168
- * formatting alone sends the album again without it. Nothing is retried otherwise.
242
+ * could not be built (`unavailable` for a stored file whose read could not be had), `uncertain`
243
+ * when its answer proves neither. A stored file goes alone, through a `request` that reads stored
244
+ * files. A refusal of the caption's formatting alone sends the album again without it. Nothing is
245
+ * retried otherwise.
169
246
  */
170
247
  export async function sendTelegramFiles(options) {
171
248
  const uploads = options.files.map((file, position) => ({
@@ -178,10 +255,13 @@ export async function sendTelegramFiles(options) {
178
255
  let cursor = 0;
179
256
  while (cursor < uploads.length) {
180
257
  const batch = [uploads[cursor++]];
258
+ const first = batch[0].file;
181
259
  let built = await multipart(options.target, batch, caption);
182
- // An album holds files of one type only; the request's order is kept.
183
- while (cursor < uploads.length &&
260
+ // An album holds files of one type only, each sent inline; the request's order is kept.
261
+ while (!isStoredFile(first) &&
262
+ cursor < uploads.length &&
184
263
  batch.length < TELEGRAM_FILES_PER_MESSAGE &&
264
+ !isStoredFile(uploads[cursor].file) &&
185
265
  uploads[cursor].type === batch[0].type) {
186
266
  const candidate = await multipart(options.target, [...batch, uploads[cursor]], caption);
187
267
  if (candidate.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
@@ -191,35 +271,35 @@ export async function sendTelegramFiles(options) {
191
271
  built = candidate;
192
272
  }
193
273
  const part = { files: batch.map((upload) => upload.index), text: caption !== undefined };
194
- if (built.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
195
- parts.push({
196
- ...part,
197
- status: "failed",
198
- messageIds: [],
199
- code: "too_large",
200
- cause: new Error(TELEGRAM_REQUEST_LIMIT),
201
- });
274
+ if (!isStoredFile(first) && built.body.byteLength > MAXIMUM_CONNECTION_BODY_BYTES) {
275
+ parts.push(unsent(part, "too_large", new Error(TELEGRAM_REQUEST_LIMIT)));
202
276
  continue;
203
277
  }
204
- const send = (message) => options.request({
205
- api: "bot",
206
- method: "POST",
207
- path: `/${message.method}`,
208
- headers: [["content-type", message.contentType]],
209
- body: message.body,
210
- });
278
+ // A stored file's request reads the file afresh each time it is sent.
279
+ const call = (message) => isStoredFile(first)
280
+ ? storedCall(message, first)
281
+ : Promise.resolve({
282
+ api: "bot",
283
+ method: "POST",
284
+ path: `/${message.method}`,
285
+ headers: [["content-type", message.contentType]],
286
+ body: message.body,
287
+ });
211
288
  let reply;
212
289
  try {
213
- reply = await send(built);
290
+ reply = await options.request(await call(built));
214
291
  if (caption !== undefined &&
215
292
  (caption.entities.length > 0 || caption.parseMode !== undefined) &&
216
293
  telegramFormattingRefused(reply.status, replyJson(reply))) {
217
294
  caption = options.plainCaption ?? { text: caption.text, entities: [] };
218
- reply = await send(await multipart(options.target, batch, caption));
295
+ built = await multipart(options.target, batch, caption);
296
+ reply = await options.request(await call(built));
219
297
  }
220
298
  }
221
299
  catch (error) {
222
- parts.push(unrelayed(part, error, options.definite));
300
+ parts.push(error instanceof FramingError
301
+ ? unsent(part, error.code, error)
302
+ : unrelayed(part, error, options.definite));
223
303
  continue;
224
304
  }
225
305
  const answer = replyJson(reply);
@@ -66,6 +66,6 @@ export declare function telegramStartParam(page: string): string | undefined;
66
66
  export declare function miniAppLink(url: string, origins: ReadonlySet<string>, botUsername: string): string | undefined;
67
67
  /** A username Telegram accepts in a `t.me` link; any other leaves every link as it is. */
68
68
  export declare function isTelegramBotUsername(username: string): boolean;
69
- export type { ChannelCall, ChannelFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
70
- export { ChannelAnswerError } from "./channel-files.js";
71
- export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_PHOTO_BYTES, type TelegramEntity, type TelegramFilesTarget, type TelegramFormattedText, } from "./telegram-files.js";
69
+ export type { ChannelCall, ChannelCallFile, ChannelFile, ChannelFileRead, ChannelPart, ChannelReply, ChannelRequest, ChannelStoredFile, DefiniteFailure, } from "./channel-files.js";
70
+ export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
71
+ 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,5 @@ 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
- export { ChannelAnswerError } from "./channel-files.js";
318
- export { sendTelegramFiles, telegramFileBytes, telegramFileRefusal, telegramFileType, telegramFormattingRefused, withCrlfLineBreaks, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DOCUMENT_BYTES, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_PHOTO_BYTES, } from "./telegram-files.js";
317
+ export { CHANNEL_FILE_FRAME_BYTES, ChannelAnswerError } from "./channel-files.js";
318
+ 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";
@@ -28,6 +28,12 @@ export declare const WORKSPACE_CHANNEL_ID: RegExp;
28
28
  export declare const WORKSPACE_CHANNEL_TEXT_LIMIT = 20000;
29
29
  /** The text a workspace channel sends: the text as written, then the separator and attribution. */
30
30
  export declare function renderWorkspaceChannelText(text: string, attribution: string, separator: string): string;
31
+ /**
32
+ * A reply in parts of at most `maxLength` characters, as a workspace channel whose code sets
33
+ * `limits.maxLength` sends a longer one: at a paragraph, else a line, else a space, else where the
34
+ * length ends. The agent splits its own replies so, and the ontology the turn replies it sends.
35
+ */
36
+ export declare function splitReply(text: string, maxLength: number | undefined): ReadonlyArray<string>;
31
37
  /** `POST` {@link workspaceChannelSendRoute}: one message to one person's chat. */
32
38
  export interface WorkspaceChannelSend {
33
39
  /** Names the message, so a send the ontology tries again is the same message. */
@@ -34,6 +34,33 @@ export const WORKSPACE_CHANNEL_TEXT_LIMIT = 20_000;
34
34
  export function renderWorkspaceChannelText(text, attribution, separator) {
35
35
  return attribution === "" ? text : `${text}${separator}${attribution}`;
36
36
  }
37
+ /**
38
+ * A reply in parts of at most `maxLength` characters, as a workspace channel whose code sets
39
+ * `limits.maxLength` sends a longer one: at a paragraph, else a line, else a space, else where the
40
+ * length ends. The agent splits its own replies so, and the ontology the turn replies it sends.
41
+ */
42
+ export function splitReply(text, maxLength) {
43
+ if (maxLength === undefined || text.length <= maxLength) {
44
+ return [text];
45
+ }
46
+ const parts = [];
47
+ let rest = text;
48
+ while (rest.length > maxLength) {
49
+ const window = rest.slice(0, maxLength);
50
+ const cut = [
51
+ window.lastIndexOf("\n\n"),
52
+ window.lastIndexOf("\n"),
53
+ window.lastIndexOf(" "),
54
+ ].find((index) => index > 0);
55
+ const end = cut ?? maxLength;
56
+ parts.push(rest.slice(0, end).trimEnd());
57
+ rest = rest.slice(end).trimStart();
58
+ }
59
+ if (rest !== "") {
60
+ parts.push(rest);
61
+ }
62
+ return parts;
63
+ }
37
64
  /**
38
65
  * The most bytes of files one message through a workspace channel carries unless the channel's
39
66
  * code takes more (`limits.fileBytes`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.179.0",
3
+ "version": "0.181.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",
@@ -45,6 +45,10 @@
45
45
  "types": "./dist/workspace-channel.d.ts",
46
46
  "import": "./dist/workspace-channel.js"
47
47
  },
48
+ "./review": {
49
+ "types": "./dist/review.d.ts",
50
+ "import": "./dist/review.js"
51
+ },
48
52
  "./chat-personas": {
49
53
  "types": "./dist/chat-personas.d.ts",
50
54
  "import": "./dist/chat-personas.js"