@segmentstream/agent 0.47.0 → 0.50.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 (93) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +14 -15
  3. package/dist/_chunks/{build-metadata-5S6uTvyu.mjs → build-metadata-DrQtDIMX.mjs} +1 -1
  4. package/dist/_chunks/principal-D5Tualrk.mjs +1836 -0
  5. package/dist/extension/channels/slack.mjs +2 -1
  6. package/dist/extension/channels/whatsapp.mjs +1 -0
  7. package/dist/extension/connections/ontology.mjs +1 -1
  8. package/dist/extension/hooks/authorization.mjs +1 -1
  9. package/dist/extension/instructions/persona.mjs +1 -1
  10. package/dist/extension/lib/actor.mjs +1 -46
  11. package/dist/extension/lib/attachment-tools.mjs +1 -3
  12. package/dist/extension/lib/attachments.d.ts +1 -1
  13. package/dist/extension/lib/attachments.mjs +1 -230
  14. package/dist/extension/lib/build-metadata.mjs +1 -1
  15. package/dist/extension/lib/chat-address.mjs +1 -50
  16. package/dist/extension/lib/chat-context.mjs +1 -1
  17. package/dist/extension/lib/chat-recorder.mjs +1 -2
  18. package/dist/extension/lib/confirmations.mjs +1 -179
  19. package/dist/extension/lib/inbound-media/files.d.ts +91 -0
  20. package/dist/extension/lib/inbound-media/files.mjs +7 -0
  21. package/dist/extension/lib/{telegram → inbound-media}/images.d.ts +2 -0
  22. package/dist/extension/lib/{telegram → inbound-media}/images.mjs +1 -2
  23. package/dist/extension/lib/inbound-media/index.d.ts +55 -0
  24. package/dist/extension/lib/inbound-media/index.mjs +7 -0
  25. package/dist/extension/lib/inbound-media/plan.d.ts +59 -0
  26. package/dist/extension/lib/{telegram/media-policy.mjs → inbound-media/plan.mjs} +56 -4
  27. package/dist/extension/lib/inbound-media/report.d.ts +5 -0
  28. package/dist/extension/lib/inbound-media/report.mjs +7 -0
  29. package/dist/extension/lib/inbound-media/speech.d.ts +52 -0
  30. package/dist/extension/lib/inbound-media/speech.mjs +73 -0
  31. package/dist/extension/lib/ontology-connection.mjs +1 -101
  32. package/dist/extension/lib/ontology-file-call.mjs +1 -4
  33. package/dist/extension/lib/ontology-tools.mjs +1 -377
  34. package/dist/extension/lib/review/hold.mjs +1 -2
  35. package/dist/extension/lib/review/reply.mjs +1 -2
  36. package/dist/extension/lib/role-skill.mjs +1 -1
  37. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  38. package/dist/extension/lib/sent-files.mjs +1 -2
  39. package/dist/extension/lib/slack/adapter.d.ts +49 -7
  40. package/dist/extension/lib/slack/adapter.mjs +79 -21
  41. package/dist/extension/lib/slack/attachments-send.mjs +1 -3
  42. package/dist/extension/lib/slack/files.d.ts +12 -19
  43. package/dist/extension/lib/slack/files.mjs +26 -58
  44. package/dist/extension/lib/stored-files.mjs +1 -3
  45. package/dist/extension/lib/telegram/adapter.d.ts +3 -3
  46. package/dist/extension/lib/telegram/adapter.mjs +13 -17
  47. package/dist/extension/lib/telegram/attachment-description.d.ts +1 -1
  48. package/dist/extension/lib/telegram/attachment-description.mjs +2 -2
  49. package/dist/extension/lib/telegram/attachments-send.mjs +1 -3
  50. package/dist/extension/lib/telegram/callbacks.mjs +1 -2
  51. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  52. package/dist/extension/lib/telegram/confirmations.mjs +1 -3
  53. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  54. package/dist/extension/lib/telegram/files.d.ts +8 -15
  55. package/dist/extension/lib/telegram/files.mjs +32 -107
  56. package/dist/extension/lib/telegram/health.mjs +1 -1
  57. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  58. package/dist/extension/lib/telegram/inbound-request.d.ts +6 -12
  59. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  60. package/dist/extension/lib/telegram/inbound.d.ts +3 -3
  61. package/dist/extension/lib/telegram/inbound.mjs +11 -11
  62. package/dist/extension/lib/telegram/lifecycle.mjs +2 -6
  63. package/dist/extension/lib/telegram/principal.mjs +1 -1
  64. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  65. package/dist/extension/lib/telegram/silent.mjs +1 -1
  66. package/dist/extension/lib/telegram/structured.mjs +1 -1
  67. package/dist/extension/lib/telegram/turn-errors.mjs +1 -2
  68. package/dist/extension/lib/telegram/voice.d.ts +7 -38
  69. package/dist/extension/lib/telegram/voice.mjs +1 -64
  70. package/dist/extension/lib/telegram/workspace-action.mjs +1 -3
  71. package/dist/extension/lib/web/auth.d.ts +27 -4
  72. package/dist/extension/lib/web/auth.mjs +1 -124
  73. package/dist/extension/lib/web/channel.d.ts +13 -4
  74. package/dist/extension/lib/web/channel.mjs +15 -8
  75. package/dist/extension/lib/whatsapp/adapter.d.ts +37 -1
  76. package/dist/extension/lib/whatsapp/adapter.mjs +118 -21
  77. package/dist/extension/lib/whatsapp/files.d.ts +40 -0
  78. package/dist/extension/lib/whatsapp/files.mjs +70 -0
  79. package/dist/extension/lib/workspace-source.mjs +1 -3
  80. package/dist/extension/model.mjs +1 -1
  81. package/dist/extension/tools/attachments_discard.mjs +1 -1
  82. package/dist/extension/tools/attachments_list.mjs +1 -1
  83. package/dist/extension/tools/attachments_promote.mjs +1 -5
  84. package/dist/extension/tools/attachments_read.mjs +1 -1
  85. package/dist/extension/tools/attachments_send.mjs +1 -2
  86. package/dist/extension/tools/attachments_stage.mjs +1 -1
  87. package/dist/extension/tools/attachments_table.mjs +1 -1
  88. package/dist/extension/tools/questions_ask.mjs +1 -2
  89. package/dist/extension/tools/workspace_source.mjs +1 -1
  90. package/package.json +2 -2
  91. package/dist/_chunks/inbound-request-B3RhCuOw.mjs +0 -413
  92. package/dist/_chunks/principal-Dzs8hUDB.mjs +0 -128
  93. package/dist/extension/lib/telegram/media-policy.d.ts +0 -15
@@ -6,10 +6,9 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
- import { chatAddressOf } from "../lib/chat-address.mjs";
9
+ import { G as memberTool, ot as chatAddressOf } from "../../_chunks/principal-D5Tualrk.mjs";
10
10
  import { sendSlackAttachments } from "../lib/slack/attachments-send.mjs";
11
11
  import { sendAttachments, sendAttachmentsInput } from "../lib/telegram/attachments-send.mjs";
12
- import { memberTool } from "../lib/actor.mjs";
13
12
  import { defineTool } from "eve/tools";
14
13
  const tool = defineTool({
15
14
  availableInSubagents: false,
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { actorOf } from "../lib/actor.mjs";
8
+ import { U as actorOf } from "../../_chunks/principal-D5Tualrk.mjs";
9
9
  import { attachmentOwner, optionalString, stringArgument, toolAttachments } from "../lib/attachment-tools.mjs";
10
10
  import { sessionSandbox } from "../lib/sandbox-session.mjs";
11
11
  import { storedFileGrant } from "../lib/stored-files.mjs";
@@ -8,7 +8,7 @@ import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7
8
8
  import { ID_INPUT, attachmentForModel, attachmentOwner, boundedResultPage, headerArgument, optionalString, pageInteger, stringArgument, toolAttachments } from "../lib/attachment-tools.mjs";
9
9
  import { readSheets, typedTable } from "../lib/attachment-tables.mjs";
10
10
  import { queryTable } from "../lib/attachment-query.mjs";
11
- import { memberTool } from "../lib/actor.mjs";
11
+ import { G as memberTool } from "../../_chunks/principal-D5Tualrk.mjs";
12
12
  import { defineTool } from "eve/tools";
13
13
  const FILTER_OPERATIONS = [
14
14
  "eq",
@@ -7,9 +7,8 @@ __eveCreateRequire(import.meta.url);
7
7
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
8
8
  import { agentTaskIdOf, agentTaskSessions } from "../lib/agent-task.mjs";
9
9
  import { stringArgument } from "../lib/attachment-tools.mjs";
10
- import { chatAddressOf } from "../lib/chat-address.mjs";
10
+ import { i as memberIdOf, ot as chatAddressOf } from "../../_chunks/principal-D5Tualrk.mjs";
11
11
  import { pendingQuestions, questionKey } from "../lib/questions.mjs";
12
- import { i as memberIdOf } from "../../_chunks/principal-Dzs8hUDB.mjs";
13
12
  import { defineTool } from "eve/tools";
14
13
  var questions_ask_default = defineTool({
15
14
  availableInSubagents: false,
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { actorOf } from "../lib/actor.mjs";
8
+ import { U as actorOf } from "../../_chunks/principal-D5Tualrk.mjs";
9
9
  import { appOrigin } from "../lib/environment.mjs";
10
10
  import { runtimeToken } from "../lib/runtime-token.mjs";
11
11
  import { sessionSandbox } from "../lib/sandbox-session.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.47.0",
3
+ "version": "0.50.0",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -80,7 +80,7 @@
80
80
  "@chat-adapter/state-memory": "4.42.0",
81
81
  "@chat-adapter/telegram": "4.41.0",
82
82
  "@chat-adapter/whatsapp": "4.42.0",
83
- "@segmentstream/ontology": "0.101.0",
83
+ "@segmentstream/ontology": "0.104.0",
84
84
  "@vercel/oidc": "^3.8.4",
85
85
  "ai": "^7.0.172",
86
86
  "chat": "4.42.0",
@@ -1,413 +0,0 @@
1
- import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
- import { dirname as __eveDirname } from "node:path";
3
- import { createRequire as __eveCreateRequire } from "node:module";
4
- const __filename = __eveFileURLToPath(import.meta.url);
5
- __eveDirname(__filename);
6
- __eveCreateRequire(import.meta.url);
7
- import { telegramText } from "../extension/lib/telegram/texts.mjs";
8
- import { isTechnicalText } from "../extension/lib/customer-text-safety.mjs";
9
- import { redactTelegramDiagnostic } from "../extension/lib/telegram/diagnostic-redaction.mjs";
10
- import { chatPostCardLinks, isExactChatPostCard } from "../extension/lib/telegram/chat-post-card.mjs";
11
- import { confirmationEntities } from "../extension/lib/telegram/confirmation-text.mjs";
12
- import { plainTelegramText, splitTelegramText, telegramMarkdown } from "../extension/lib/telegram/format.mjs";
13
- import { inTelegramSendQueue } from "../extension/lib/telegram/send-queue.mjs";
14
- import { retainDeliveryDiagnostic } from "../extension/lib/telegram/delivery-diagnostics.mjs";
15
- import { miniAppLinks, originalLinkPreview, withMiniAppLinks } from "../extension/lib/telegram/app-links.mjs";
16
- import { randomBytes, randomUUID } from "node:crypto";
17
- import { AsyncLocalStorage } from "node:async_hooks";
18
- import { telegramPreviewOptions, telegramTextLinks } from "@segmentstream/ontology/telegram";
19
- const deliveryLocale = new AsyncLocalStorage();
20
- function withDeliveryLocale(locale, run, threadId, replyTo, chatId) {
21
- return deliveryLocale.run({
22
- locale,
23
- threadId,
24
- replyTo,
25
- chatId
26
- }, run);
27
- }
28
- function currentLocale() {
29
- return deliveryLocale.getStore()?.locale ?? currentInboundRequest()?.locale ?? "en";
30
- }
31
- function currentThreadId() {
32
- return deliveryLocale.getStore()?.threadId ?? currentInboundRequest()?.threadId;
33
- }
34
- function customerCopy(locale = currentLocale()) {
35
- return {
36
- failed: telegramText("notice", "failed", locale),
37
- modelBudgetExceeded: telegramText("notice", "modelBudgetExceeded", locale),
38
- modelUnavailable: telegramText("notice", "modelUnavailable", locale),
39
- recovery: telegramText("notice", "recovery", locale),
40
- attachment: telegramText("notice", "attachment", locale),
41
- authorization: telegramText("notice", "authorization", locale),
42
- response: telegramText("notice", "response", locale),
43
- connected: telegramText("notice", "connected", locale),
44
- disconnected: telegramText("notice", "disconnected", locale),
45
- cancelled: telegramText("notice", "cancelled", locale)
46
- };
47
- }
48
- function reportTelegramError(operation, error, metadata = {}, secrets = new Set()) {
49
- const errorId = randomBytes(4).toString("hex");
50
- const redactedError = redactTelegramDiagnostic(error, secrets);
51
- const redactedMetadata = redactTelegramDiagnostic(metadata, secrets);
52
- console.error("[segmentstream] Telegram delivery diagnostic", {
53
- ...redactedMetadata,
54
- errorId,
55
- operation,
56
- error: redactedError
57
- });
58
- retainDeliveryDiagnostic({
59
- errorId,
60
- operation,
61
- error: redactedError,
62
- metadata: redactedMetadata
63
- });
64
- return errorId;
65
- }
66
- function failureText(_errorId, kind = "failed", _locale = currentLocale(), fallback = "failed") {
67
- const copy = customerCopy(_locale);
68
- return copy[kind] ?? (kind === "modelBudgetExceeded" || kind === "modelUnavailable" ? copy[fallback] : void 0) ?? (kind === "cancelled" ? "⏹" : "⚠️");
69
- }
70
- function customerText(text, locale = currentLocale()) {
71
- if (!isTechnicalText(text)) return text;
72
- return failureText(reportTelegramError("technical_text_blocked", { text }), "response", locale);
73
- }
74
- function customerMessage(text, locale = currentLocale()) {
75
- return guardedCustomerMessage(text, locale);
76
- }
77
- function guardedCustomerMessage(text, locale, blocked) {
78
- let message;
79
- try {
80
- message = telegramMarkdown(text);
81
- } catch (error) {
82
- reportTelegramError("markdown_render_failed", error);
83
- message = {
84
- text: plainTelegramText(text),
85
- entities: []
86
- };
87
- }
88
- const links = message.entities.flatMap((entity) => entity.url === void 0 ? [] : [entity.url]);
89
- const visible = customerText(message.text, locale);
90
- if (visible !== message.text) {
91
- blocked?.();
92
- return {
93
- text: visible,
94
- entities: []
95
- };
96
- }
97
- if (links.some(isTechnicalText)) {
98
- blocked?.();
99
- return {
100
- text: failureText(reportTelegramError("unsafe_markdown_link", new Error("Credential-bearing link refused.")), "response", locale),
101
- entities: []
102
- };
103
- }
104
- return message;
105
- }
106
- async function formattingRefused(response) {
107
- if (response.status !== 400) return false;
108
- const body = await response.clone().json().catch(() => null);
109
- return body?.ok === false && typeof body.description === "string" && (/can't parse entities|cannot parse entities|entity (?:bounds|offset|length)|entities (?:are|too)/iu.test(body.description) || /unsupported (?:start tag|parse mode)/iu.test(body.description));
110
- }
111
- var TelegramDeliveryError = class extends Error {
112
- reference;
113
- delivery;
114
- messageIds;
115
- name = "TelegramDeliveryError";
116
- constructor(reference, delivery, messageIds) {
117
- super(`Telegram delivery ${delivery}; reference ${reference}. Do not automatically resend.`);
118
- this.reference = reference;
119
- this.delivery = delivery;
120
- this.messageIds = messageIds;
121
- }
122
- };
123
- function isFields(value) {
124
- return typeof value === "object" && value !== null;
125
- }
126
- function records(value) {
127
- return Array.isArray(value) ? value.filter(isFields) : [];
128
- }
129
- function linkDestinations(body) {
130
- const markup = body.reply_markup;
131
- return [
132
- ...records(body.entities),
133
- ...records(body.caption_entities),
134
- ...records(body.media).flatMap((item) => records(item.caption_entities)),
135
- ...Array.isArray(markup?.inline_keyboard) ? markup.inline_keyboard.flatMap(records) : []
136
- ].flatMap((item) => typeof item.url === "string" ? [item.url] : []);
137
- }
138
- function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}, appLinks) {
139
- const methods = new Set([
140
- "sendMessage",
141
- "editMessageText",
142
- "editMessageCaption",
143
- "editMessageReplyMarkup",
144
- "answerCallbackQuery",
145
- "sendPhoto",
146
- "sendDocument",
147
- "sendMediaGroup"
148
- ]);
149
- return async (input, init) => {
150
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
151
- if (!methods.has(url.split("/").at(-1) ?? "") || typeof init?.body !== "string") return fetchImpl(input, init);
152
- const body = JSON.parse(init.body);
153
- let textBlocked = false;
154
- const fixed = ["text", "caption"].some((field) => {
155
- const value = body[field];
156
- return typeof value === "string" && (isExactChatPostCard(value) || confirmationEntities(value) !== void 0);
157
- });
158
- for (const field of ["text", "caption"]) {
159
- if (typeof body[field] === "string" && isExactChatPostCard(body[field])) body.parse_mode = "MarkdownV2";
160
- if (typeof body[field] === "string" && !isExactChatPostCard(body[field])) {
161
- const entityField = field === "text" ? "entities" : "caption_entities";
162
- const existing = body[entityField];
163
- const card = confirmationEntities(body[field]);
164
- const message = card !== void 0 ? {
165
- text: body[field],
166
- entities: [...card]
167
- } : Array.isArray(existing) ? {
168
- text: body[field],
169
- entities: existing
170
- } : guardedCustomerMessage(body[field], currentLocale(), () => {
171
- textBlocked = true;
172
- });
173
- const guarded = customerText(message.text);
174
- const unsafeLink = message.entities.some((entity) => typeof entity.url === "string" && isTechnicalText(entity.url));
175
- textBlocked ||= guarded !== message.text || unsafeLink;
176
- body[field] = unsafeLink ? failureText(reportTelegramError("unsafe_entity_link", new Error("Credential-bearing link refused.")), "response") : guarded;
177
- if (!url.endsWith("/answerCallbackQuery")) body[entityField] = body[field] === message.text ? message.entities : [];
178
- delete body.parse_mode;
179
- }
180
- }
181
- if (Array.isArray(body.media)) body.media = body.media.map((item) => ({
182
- ...item,
183
- ...typeof item.caption === "string" ? { caption: customerText(item.caption) } : {}
184
- }));
185
- const replyTo = deliveryLocale.getStore()?.replyTo ?? currentInboundRequest()?.replyTo;
186
- const replyChat = deliveryLocale.getStore()?.chatId ?? currentInboundRequest()?.chatId;
187
- if (replyTo !== void 0 && replyChat === String(body.chat_id) && /\/send(?:Message|Photo|Document|Video|Audio|Voice|MediaGroup)$/.test(url) && body.reply_parameters === void 0 && body.reply_to_message_id === void 0) body.reply_parameters = {
188
- message_id: Number(replyTo),
189
- allow_sending_without_reply: true
190
- };
191
- const markup = body.reply_markup;
192
- if (Array.isArray(markup?.inline_keyboard)) {
193
- if ((textBlocked || typeof body.text === "string" && body.text.length > 4096) && markup.inline_keyboard.some((row) => row.some((button) => typeof button.callback_data === "string" && button.callback_data.startsWith("ss-confirm:")))) throw new Error("Approval buttons require the complete, safe confirmation text.");
194
- const rows = markup.inline_keyboard.map((row) => row.filter((button) => {
195
- if (typeof button.text !== "string" || !isTechnicalText(button.text)) return true;
196
- reportTelegramError("technical_button_label_blocked", { text: button.text });
197
- return false;
198
- })).filter((row) => row.length > 0);
199
- if (rows.length === 0 && markup.inline_keyboard.length > 0) delete body.reply_markup;
200
- else markup.inline_keyboard = rows;
201
- }
202
- const links = appLinks === void 0 || fixed ? new Map() : await miniAppLinks(appLinks, linkDestinations(body));
203
- if (links.size > 0) {
204
- if (Array.isArray(markup?.inline_keyboard) && body.reply_markup !== void 0) markup.inline_keyboard = markup.inline_keyboard.map((row) => withMiniAppLinks(row, links));
205
- if (Array.isArray(body.media)) body.media = body.media.map((item) => isFields(item) && item.caption_entities !== void 0 ? {
206
- ...item,
207
- caption_entities: withMiniAppLinks(item.caption_entities, links)
208
- } : item);
209
- }
210
- const send = async () => {
211
- const parts = url.endsWith("/sendMessage") && typeof body.text === "string" && !isExactChatPostCard(body.text) ? splitTelegramText({
212
- text: body.text,
213
- entities: body.entities ?? []
214
- }) : [null];
215
- let first;
216
- const messageIds = [];
217
- const attempt = async (outgoing) => {
218
- try {
219
- const written = (url.endsWith("/sendMessage") || url.endsWith("/editMessageText")) && typeof outgoing.text === "string" ? chatPostCardLinks(outgoing.text) ?? telegramTextLinks(outgoing.text, outgoing.entities ?? []) : void 0;
220
- const previewOptions = written === void 0 ? {} : originalLinkPreview(telegramPreviewOptions(body, written, previews), written, links);
221
- const payload = { ...outgoing };
222
- if (url.endsWith("/sendMessage") || url.endsWith("/editMessageText")) {
223
- delete payload.link_preview_options;
224
- delete payload.disable_web_page_preview;
225
- Object.assign(payload, previewOptions);
226
- }
227
- for (const field of ["entities", "caption_entities"]) if (payload[field] !== void 0) payload[field] = withMiniAppLinks(payload[field], links);
228
- return await fetchImpl(input, {
229
- ...init,
230
- body: JSON.stringify(payload)
231
- });
232
- } catch (error) {
233
- throw new TelegramDeliveryError(reportTelegramError("telegram_send_unknown", error, { messageIds }), "unknown", messageIds);
234
- }
235
- };
236
- for (const [index, part] of parts.entries()) {
237
- const outgoing = part === null ? { ...body } : {
238
- ...body,
239
- text: part.text,
240
- entities: part.entities
241
- };
242
- if (index < parts.length - 1) delete outgoing.reply_markup;
243
- let response = await attempt(outgoing);
244
- const entityField = typeof outgoing.text === "string" ? "entities" : "caption_entities";
245
- if (Array.isArray(outgoing[entityField]) && outgoing[entityField].length > 0 && await formattingRefused(response)) {
246
- delete outgoing[entityField];
247
- delete outgoing.parse_mode;
248
- response = await attempt(outgoing);
249
- }
250
- const result = await response.clone().json().catch(() => null);
251
- if (url.endsWith("/sendMessage")) {
252
- const id = result?.result?.message_id;
253
- if (!response.ok || result?.ok !== true || typeof id !== "number" || !Number.isSafeInteger(id) || id < 1) {
254
- const delivery = result?.ok === false ? "failed" : "unknown";
255
- throw new TelegramDeliveryError(reportTelegramError("telegram_send_unacknowledged", {
256
- status: response.status,
257
- result,
258
- messageIds,
259
- delivery
260
- }), delivery, messageIds);
261
- }
262
- messageIds.push(id);
263
- } else if (!response.ok || result?.ok !== true) return response;
264
- first ??= response;
265
- }
266
- if (first === void 0) throw new Error("Telegram message has no visible text; nothing was sent.");
267
- return first;
268
- };
269
- return typeof body.chat_id === "string" || typeof body.chat_id === "number" ? inTelegramSendQueue(scope, String(body.chat_id), send) : send();
270
- };
271
- }
272
- var InboundRequest = class {
273
- agentDescription;
274
- agentName;
275
- traceId = randomUUID();
276
- turnPolicy = "queue";
277
- edited = false;
278
- triggeringMessageId;
279
- chatId;
280
- replyTo;
281
- lifecycle;
282
- lifecycleKey;
283
- lifecycleDispatchToken;
284
- releaseLifecycleDispatch;
285
- retryReference;
286
- lifecycleContext;
287
- previousText;
288
- attachmentsChanged = false;
289
- previousContent;
290
- claimRevision;
291
- deliveryFailed;
292
- engaged = false;
293
- claimTurn;
294
- beginDispatch;
295
- finishClaim;
296
- structuredContext;
297
- recordStructuredContext;
298
- beginStructuredContinuation;
299
- locale;
300
- threadId;
301
- text;
302
- files;
303
- extraFiles;
304
- sessions;
305
- waitUntil;
306
- address;
307
- respond;
308
- constructor(agentDescription, agentName = async () => "") {
309
- this.agentDescription = agentDescription;
310
- this.agentName = agentName;
311
- }
312
- };
313
- const storage = new AsyncLocalStorage();
314
- function runInboundRequest(request, run) {
315
- return storage.run(request, run);
316
- }
317
- function currentInboundRequest() {
318
- return storage.getStore();
319
- }
320
- function replaceText(message, text) {
321
- if (typeof message === "string") return text;
322
- return [{
323
- type: "text",
324
- text
325
- }, ...message.filter((part) => part.type !== "text")];
326
- }
327
- function telegramFileId(data) {
328
- const href = data instanceof URL ? data.href : typeof data === "string" ? data : void 0;
329
- if (href === void 0 || !href.startsWith("telegram-file:")) return;
330
- try {
331
- return decodeURIComponent(new URL(href).pathname);
332
- } catch {
333
- return;
334
- }
335
- }
336
- function replaceFiles(message, files) {
337
- if (typeof message === "string") return message;
338
- return message.map((part) => {
339
- if (part.type !== "file") return part;
340
- const fileId = telegramFileId(part.data);
341
- const staged = fileId === void 0 ? void 0 : files.get(fileId);
342
- if (staged === void 0) return part;
343
- if (staged.status === "refused") return {
344
- type: "text",
345
- text: `[file ${staged.filename} was not received: ${staged.reason}]`
346
- };
347
- if (staged.imageInput === "text") return {
348
- type: "text",
349
- text: `[image ${staged.attachment.filename}: ${staged.description ?? "see attachment context"}]`
350
- };
351
- return {
352
- ...part,
353
- data: staged.url
354
- };
355
- });
356
- }
357
- function withReplacedText(source, request) {
358
- return {
359
- ...source,
360
- async send(message, options) {
361
- const marker = request.replyTo === void 0 ? void 0 : `[source-message:${request.replyTo};trigger:${request.triggeringMessageId ?? request.replyTo}]`;
362
- const replacement = marker === void 0 ? request.text : `${marker}\n${request.text ?? (typeof message === "string" ? message : message.filter((part) => part.type === "text").map((part) => part.text).join("\n"))}`;
363
- const text = replacement === void 0 ? message : replaceText(message, replacement);
364
- const files = request.files === void 0 ? text : replaceFiles(text, request.files);
365
- const content = request.extraFiles === void 0 || request.extraFiles.length === 0 ? files : [...typeof files === "string" ? [{
366
- type: "text",
367
- text: files
368
- }] : files, ...request.extraFiles];
369
- let result;
370
- try {
371
- result = await source.send(content, {
372
- ...options,
373
- turnPolicy: request.turnPolicy
374
- });
375
- } catch (error) {
376
- try {
377
- await request.releaseLifecycleDispatch?.();
378
- } catch (cleanupError) {
379
- console.error("[segmentstream] inventory dispatch cleanup failed", {
380
- cleanupError,
381
- cause: error
382
- });
383
- }
384
- try {
385
- await request.finishClaim?.(false);
386
- await request.deliveryFailed?.(error);
387
- } catch (cleanupError) {
388
- console.error("[segmentstream] inbound delivery cleanup failed", {
389
- cleanupError,
390
- cause: error
391
- });
392
- }
393
- throw error;
394
- }
395
- try {
396
- await request.finishClaim?.(true);
397
- } catch (error) {
398
- reportTelegramError("turn_admission_recording_failed", error);
399
- }
400
- if (request.lifecycleKey !== void 0) console.info("[segmentstream] telegram.phase", {
401
- phase: "queue_accepted",
402
- traceId: request.traceId,
403
- at: new Date().toISOString(),
404
- chatId: request.chatId,
405
- messageId: request.replyTo,
406
- intakeId: request.lifecycleKey,
407
- sessionId: result.sessionId
408
- });
409
- return result;
410
- }
411
- };
412
- }
413
- export { TelegramDeliveryError as a, customerCopy as c, failureText as d, formattingRefused as f, withDeliveryLocale as h, withReplacedText as i, customerMessage as l, safeTelegramFetch as m, currentInboundRequest as n, currentLocale as o, reportTelegramError as p, runInboundRequest as r, currentThreadId as s, InboundRequest as t, customerText as u };
@@ -1,128 +0,0 @@
1
- import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
- import { dirname as __eveDirname } from "node:path";
3
- import { createRequire as __eveCreateRequire } from "node:module";
4
- const __filename = __eveFileURLToPath(import.meta.url);
5
- __eveDirname(__filename);
6
- __eveCreateRequire(import.meta.url);
7
- import { n as currentInboundRequest } from "./inbound-request-B3RhCuOw.mjs";
8
- import "../extension/lib/agent-task.mjs";
9
- import { randomUUID } from "node:crypto";
10
- function telegramRuntimeSource(message, files, callbackQueryId) {
11
- const attachments = [];
12
- for (const file of message.attachments) {
13
- const staged = files?.get(file.fileId);
14
- if (staged?.status !== "stored" || attachments.length >= 10) continue;
15
- let kind = file.kind;
16
- for (const candidate of [
17
- "voice",
18
- "audio",
19
- "video",
20
- "video_note",
21
- "sticker",
22
- "animation"
23
- ]) {
24
- const raw = message.raw[candidate];
25
- if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && raw.file_id === file.fileId) kind = candidate;
26
- }
27
- attachments.push({
28
- file_id: file.fileId,
29
- kind,
30
- staged_id: staged.attachment.id,
31
- ...file.fileUniqueId === void 0 ? {} : { file_unique_id: file.fileUniqueId },
32
- media_type: staged.attachment.contentType
33
- });
34
- }
35
- return {
36
- provider: "telegram",
37
- chat_id: message.chat.id,
38
- thread_id: String(message.messageThreadId ?? ""),
39
- message_id: message.messageId,
40
- ...message.replyToMessage === void 0 ? {} : { reply_to_message_id: message.replyToMessage.messageId },
41
- ...message.from === void 0 ? {} : { sender: message.from.id },
42
- ...callbackQueryId === void 0 ? {} : { callback_query_id: callbackQueryId },
43
- ...attachments.length === 0 ? {} : { attachments }
44
- };
45
- }
46
- function principalRuntimeSource(principal) {
47
- if (principal?.authenticator !== "segmentstream-telegram") return;
48
- const value = principal.attributes.segmentstreamRuntimeSource;
49
- if (typeof value !== "string") return;
50
- try {
51
- return JSON.parse(value);
52
- } catch {
53
- return;
54
- }
55
- }
56
- function runtimeEnvelope(input = {}) {
57
- const source = input.source ?? principalRuntimeSource(input.principal);
58
- return {
59
- version: 1,
60
- session_id: input.sessionId ?? randomUUID(),
61
- call_id: input.callId ?? randomUUID(),
62
- ...source === void 0 ? {} : { source }
63
- };
64
- }
65
- function compatibleRuntimeEnvelope(envelope, extended) {
66
- const source = envelope.source;
67
- return extended || source === void 0 || source.provider !== "telegram" ? envelope : {
68
- ...envelope,
69
- source: {
70
- provider: source.provider,
71
- chat_id: source.chat_id,
72
- thread_id: source.thread_id
73
- }
74
- };
75
- }
76
- const RUNTIME_SOURCE_PROTOCOL = "segmentstream/runtime-source";
77
- const TELEGRAM_AUTHENTICATOR = "segmentstream-telegram";
78
- function isGroup(message) {
79
- return message.chat.type === "group" || message.chat.type === "supergroup";
80
- }
81
- function telegramPrincipal(input) {
82
- const { message, member } = input;
83
- const sender = message.from.id;
84
- const attributes = {
85
- memberId: member.id,
86
- segmentstreamRuntimeSource: JSON.stringify(telegramRuntimeSource(message, currentInboundRequest()?.files, input.callbackQueryId)),
87
- identityProvider: "telegram",
88
- roles: member.roles,
89
- chatId: message.chat.id,
90
- chatType: message.chat.type
91
- };
92
- if (member.name !== null) attributes.memberName = member.name;
93
- if (message.messageThreadId !== void 0) attributes.messageThreadId = String(message.messageThreadId);
94
- if (message.from.username !== void 0) attributes.username = message.from.username;
95
- const locale = member.locale ?? message.from.languageCode;
96
- if (locale !== void 0) attributes.locale = locale;
97
- const language = input.chatLanguage ?? chatLanguage([message.text || message.caption]);
98
- if (language !== void 0) attributes.chatLanguage = language;
99
- return {
100
- authenticator: TELEGRAM_AUTHENTICATOR,
101
- issuer: "telegram",
102
- principalId: isGroup(message) ? `telegram:${message.chat.id}:${sender}` : `telegram:${sender}`,
103
- principalType: "user",
104
- subject: sender,
105
- attributes
106
- };
107
- }
108
- function chatLanguage(texts) {
109
- for (const text of texts) {
110
- if (/[\u0430-\u044f\u0451]/iu.test(text)) return "ru";
111
- if ((text.match(/\b[a-z]+\b/gi)?.length ?? 0) >= 3) return "en";
112
- }
113
- }
114
- function memberIdOf(principal) {
115
- if (principal?.authenticator === "segmentstream-agent-task") return;
116
- const memberId = principal?.attributes.memberId;
117
- return typeof memberId === "string" && memberId !== "" ? memberId : void 0;
118
- }
119
- function rolesOf(principal) {
120
- const roles = principal?.attributes.roles;
121
- if (typeof roles === "string") return [roles];
122
- return roles ?? [];
123
- }
124
- function identityProviderOf(principal) {
125
- const provider = principal?.attributes.identityProvider;
126
- return typeof provider === "string" && provider !== "" ? provider : void 0;
127
- }
128
- export { rolesOf as a, compatibleRuntimeEnvelope as c, telegramRuntimeSource as d, memberIdOf as i, principalRuntimeSource as l, chatLanguage as n, telegramPrincipal as o, identityProviderOf as r, RUNTIME_SOURCE_PROTOCOL as s, TELEGRAM_AUTHENTICATOR as t, runtimeEnvelope as u };
@@ -1,15 +0,0 @@
1
- export interface ModelMediaCapabilities {
2
- readonly known: boolean;
3
- readonly images: boolean;
4
- readonly audio: boolean;
5
- }
6
- export type CapabilityLookup = (model: string) => Promise<ModelMediaCapabilities>;
7
- export interface MediaPlan {
8
- readonly images: "native" | "describe" | "unavailable";
9
- readonly descriptionModel?: string;
10
- readonly audio: boolean;
11
- }
12
- /** Unknown capabilities never become a claim that the model can see or hear the upload. */
13
- export declare function planMedia(capabilities: ModelMediaCapabilities, descriptionModel?: string | false | null): MediaPlan;
14
- /** Public Gateway metadata, never a model-name heuristic or a credential-bearing request. */
15
- export declare function gatewayMediaCapabilities(fetchImpl?: typeof fetch): CapabilityLookup;