@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
@@ -0,0 +1,1836 @@
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, withTelegramTexts } from "../extension/lib/telegram/texts.mjs";
8
+ import { isTechnicalText } from "../extension/lib/customer-text-safety.mjs";
9
+ import { miniAppLinks, originalLinkPreview, withMiniAppLinks } from "../extension/lib/telegram/app-links.mjs";
10
+ import { appOrigin } from "../extension/lib/environment.mjs";
11
+ import { redactDiagnostic } from "../extension/lib/diagnostics.mjs";
12
+ import { redactTelegramDiagnostic } from "../extension/lib/telegram/diagnostic-redaction.mjs";
13
+ import { CONFIRMATION_FACTS, CONFIRMATION_PREVIEW_METHOD, ConfirmationRefused, UnsafeConfirmationTarget, confirmationCard, describeConfirmation, factsConfirmation, object } from "../extension/lib/confirmation-description.mjs";
14
+ import { confirmationCopy, confirmationCopyIssue, confirmationEntities, confirmationLocale, renderConfirmation } from "../extension/lib/telegram/confirmation-text.mjs";
15
+ import { chatPostCard, chatPostCardLinks, chatPostPrompt, isExactChatPostCard } from "../extension/lib/telegram/chat-post-card.mjs";
16
+ import { plainTelegramText, splitTelegramText, telegramMarkdown } from "../extension/lib/telegram/format.mjs";
17
+ import { inTelegramSendQueue } from "../extension/lib/telegram/send-queue.mjs";
18
+ import { runtimeToken, tokenExpiry } from "../extension/lib/runtime-token.mjs";
19
+ import { retainDeliveryDiagnostic } from "../extension/lib/telegram/delivery-diagnostics.mjs";
20
+ import { MAXIMUM_DOWNLOAD_BYTES } from "../extension/lib/connection-proxy.mjs";
21
+ import { AGENT_TASK_HEADER, agentTaskIdOf, taskSecret } from "../extension/lib/agent-task.mjs";
22
+ import { promptFits, withButtonDecision } from "../extension/lib/confirmation-buttons.mjs";
23
+ import { CHAT_POST_ENVELOPE, CHAT_POST_TOOL, chatPostDigest, chatPostOperationId, describeChatPost, isChatPost, supportsChatPost } from "../extension/lib/chat-post-confirmation.mjs";
24
+ import { describableImage, describeReceivedImage } from "../extension/lib/inbound-media/images.mjs";
25
+ import { NATIVE_AUDIO_NOTE, isSpeech, transcribeSpeech } from "../extension/lib/inbound-media/speech.mjs";
26
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
27
+ import { AsyncLocalStorage } from "node:async_hooks";
28
+ import { telegramPreviewOptions, telegramTextLinks } from "@segmentstream/ontology/telegram";
29
+ import { defineMcpClientConnection } from "eve/connections";
30
+ import { defineState } from "eve/context";
31
+ import { defineDynamic as defineDynamic$1 } from "eve/tools";
32
+ import { ForbiddenError, UnauthenticatedError } from "eve/channels/auth";
33
+ function telegramRuntimeSource(message, files, callbackQueryId) {
34
+ const attachments = [];
35
+ for (const file of message.attachments) {
36
+ const staged = files?.get(file.fileId);
37
+ if (staged?.status !== "stored" || attachments.length >= 10) continue;
38
+ let kind = file.kind;
39
+ for (const candidate of [
40
+ "voice",
41
+ "audio",
42
+ "video",
43
+ "video_note",
44
+ "sticker",
45
+ "animation"
46
+ ]) {
47
+ const raw = message.raw[candidate];
48
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && raw.file_id === file.fileId) kind = candidate;
49
+ }
50
+ attachments.push({
51
+ file_id: file.fileId,
52
+ kind,
53
+ staged_id: staged.attachment.id,
54
+ ...file.fileUniqueId === void 0 ? {} : { file_unique_id: file.fileUniqueId },
55
+ media_type: staged.attachment.contentType
56
+ });
57
+ }
58
+ return {
59
+ provider: "telegram",
60
+ chat_id: message.chat.id,
61
+ thread_id: String(message.messageThreadId ?? ""),
62
+ message_id: message.messageId,
63
+ ...message.replyToMessage === void 0 ? {} : { reply_to_message_id: message.replyToMessage.messageId },
64
+ ...message.from === void 0 ? {} : { sender: message.from.id },
65
+ ...callbackQueryId === void 0 ? {} : { callback_query_id: callbackQueryId },
66
+ ...attachments.length === 0 ? {} : { attachments }
67
+ };
68
+ }
69
+ function principalRuntimeSource(principal) {
70
+ if (principal?.authenticator !== "segmentstream-telegram") return;
71
+ const value = principal.attributes.segmentstreamRuntimeSource;
72
+ if (typeof value !== "string") return;
73
+ try {
74
+ return JSON.parse(value);
75
+ } catch {
76
+ return;
77
+ }
78
+ }
79
+ function runtimeEnvelope(input = {}) {
80
+ const source = input.source ?? principalRuntimeSource(input.principal);
81
+ return {
82
+ version: 1,
83
+ session_id: input.sessionId ?? randomUUID(),
84
+ call_id: input.callId ?? randomUUID(),
85
+ ...source === void 0 ? {} : { source }
86
+ };
87
+ }
88
+ function compatibleRuntimeEnvelope(envelope, extended) {
89
+ const source = envelope.source;
90
+ return extended || source === void 0 || source.provider !== "telegram" ? envelope : {
91
+ ...envelope,
92
+ source: {
93
+ provider: source.provider,
94
+ chat_id: source.chat_id,
95
+ thread_id: source.thread_id
96
+ }
97
+ };
98
+ }
99
+ const RUNTIME_SOURCE_PROTOCOL = "segmentstream/runtime-source";
100
+ const deliveryLocale = new AsyncLocalStorage();
101
+ function withDeliveryLocale(locale, run, threadId, replyTo, chatId) {
102
+ return deliveryLocale.run({
103
+ locale,
104
+ threadId,
105
+ replyTo,
106
+ chatId
107
+ }, run);
108
+ }
109
+ function currentLocale() {
110
+ return deliveryLocale.getStore()?.locale ?? currentInboundRequest()?.locale ?? "en";
111
+ }
112
+ function currentThreadId() {
113
+ return deliveryLocale.getStore()?.threadId ?? currentInboundRequest()?.threadId;
114
+ }
115
+ function customerCopy(locale = currentLocale()) {
116
+ return {
117
+ failed: telegramText("notice", "failed", locale),
118
+ modelBudgetExceeded: telegramText("notice", "modelBudgetExceeded", locale),
119
+ modelUnavailable: telegramText("notice", "modelUnavailable", locale),
120
+ recovery: telegramText("notice", "recovery", locale),
121
+ attachment: telegramText("notice", "attachment", locale),
122
+ authorization: telegramText("notice", "authorization", locale),
123
+ response: telegramText("notice", "response", locale),
124
+ connected: telegramText("notice", "connected", locale),
125
+ disconnected: telegramText("notice", "disconnected", locale),
126
+ cancelled: telegramText("notice", "cancelled", locale)
127
+ };
128
+ }
129
+ function reportTelegramError(operation, error, metadata = {}, secrets = new Set()) {
130
+ const errorId = randomBytes(4).toString("hex");
131
+ const redactedError = redactTelegramDiagnostic(error, secrets);
132
+ const redactedMetadata = redactTelegramDiagnostic(metadata, secrets);
133
+ console.error("[segmentstream] Telegram delivery diagnostic", {
134
+ ...redactedMetadata,
135
+ errorId,
136
+ operation,
137
+ error: redactedError
138
+ });
139
+ retainDeliveryDiagnostic({
140
+ errorId,
141
+ operation,
142
+ error: redactedError,
143
+ metadata: redactedMetadata
144
+ });
145
+ return errorId;
146
+ }
147
+ function failureText(_errorId, kind = "failed", _locale = currentLocale(), fallback = "failed") {
148
+ const copy = customerCopy(_locale);
149
+ return copy[kind] ?? (kind === "modelBudgetExceeded" || kind === "modelUnavailable" ? copy[fallback] : void 0) ?? (kind === "cancelled" ? "⏹" : "⚠️");
150
+ }
151
+ function customerText(text, locale = currentLocale()) {
152
+ if (!isTechnicalText(text)) return text;
153
+ return failureText(reportTelegramError("technical_text_blocked", { text }), "response", locale);
154
+ }
155
+ function customerMessage(text, locale = currentLocale()) {
156
+ return guardedCustomerMessage(text, locale);
157
+ }
158
+ function guardedCustomerMessage(text, locale, blocked) {
159
+ let message;
160
+ try {
161
+ message = telegramMarkdown(text);
162
+ } catch (error) {
163
+ reportTelegramError("markdown_render_failed", error);
164
+ message = {
165
+ text: plainTelegramText(text),
166
+ entities: []
167
+ };
168
+ }
169
+ const links = message.entities.flatMap((entity) => entity.url === void 0 ? [] : [entity.url]);
170
+ const visible = customerText(message.text, locale);
171
+ if (visible !== message.text) {
172
+ blocked?.();
173
+ return {
174
+ text: visible,
175
+ entities: []
176
+ };
177
+ }
178
+ if (links.some(isTechnicalText)) {
179
+ blocked?.();
180
+ return {
181
+ text: failureText(reportTelegramError("unsafe_markdown_link", new Error("Credential-bearing link refused.")), "response", locale),
182
+ entities: []
183
+ };
184
+ }
185
+ return message;
186
+ }
187
+ async function formattingRefused(response) {
188
+ if (response.status !== 400) return false;
189
+ const body = await response.clone().json().catch(() => null);
190
+ 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));
191
+ }
192
+ var TelegramDeliveryError = class extends Error {
193
+ reference;
194
+ delivery;
195
+ messageIds;
196
+ name = "TelegramDeliveryError";
197
+ constructor(reference, delivery, messageIds) {
198
+ super(`Telegram delivery ${delivery}; reference ${reference}. Do not automatically resend.`);
199
+ this.reference = reference;
200
+ this.delivery = delivery;
201
+ this.messageIds = messageIds;
202
+ }
203
+ };
204
+ function isFields(value) {
205
+ return typeof value === "object" && value !== null;
206
+ }
207
+ function records(value) {
208
+ return Array.isArray(value) ? value.filter(isFields) : [];
209
+ }
210
+ function linkDestinations(body) {
211
+ const markup = body.reply_markup;
212
+ return [
213
+ ...records(body.entities),
214
+ ...records(body.caption_entities),
215
+ ...records(body.media).flatMap((item) => records(item.caption_entities)),
216
+ ...Array.isArray(markup?.inline_keyboard) ? markup.inline_keyboard.flatMap(records) : []
217
+ ].flatMap((item) => typeof item.url === "string" ? [item.url] : []);
218
+ }
219
+ function safeTelegramFetch(fetchImpl, scope = "telegram", previews = {}, appLinks) {
220
+ const methods = new Set([
221
+ "sendMessage",
222
+ "editMessageText",
223
+ "editMessageCaption",
224
+ "editMessageReplyMarkup",
225
+ "answerCallbackQuery",
226
+ "sendPhoto",
227
+ "sendDocument",
228
+ "sendMediaGroup"
229
+ ]);
230
+ return async (input, init) => {
231
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
232
+ if (!methods.has(url.split("/").at(-1) ?? "") || typeof init?.body !== "string") return fetchImpl(input, init);
233
+ const body = JSON.parse(init.body);
234
+ let textBlocked = false;
235
+ const fixed = ["text", "caption"].some((field) => {
236
+ const value = body[field];
237
+ return typeof value === "string" && (isExactChatPostCard(value) || confirmationEntities(value) !== void 0);
238
+ });
239
+ for (const field of ["text", "caption"]) {
240
+ if (typeof body[field] === "string" && isExactChatPostCard(body[field])) body.parse_mode = "MarkdownV2";
241
+ if (typeof body[field] === "string" && !isExactChatPostCard(body[field])) {
242
+ const entityField = field === "text" ? "entities" : "caption_entities";
243
+ const existing = body[entityField];
244
+ const card = confirmationEntities(body[field]);
245
+ const message = card !== void 0 ? {
246
+ text: body[field],
247
+ entities: [...card]
248
+ } : Array.isArray(existing) ? {
249
+ text: body[field],
250
+ entities: existing
251
+ } : guardedCustomerMessage(body[field], currentLocale(), () => {
252
+ textBlocked = true;
253
+ });
254
+ const guarded = customerText(message.text);
255
+ const unsafeLink = message.entities.some((entity) => typeof entity.url === "string" && isTechnicalText(entity.url));
256
+ textBlocked ||= guarded !== message.text || unsafeLink;
257
+ body[field] = unsafeLink ? failureText(reportTelegramError("unsafe_entity_link", new Error("Credential-bearing link refused.")), "response") : guarded;
258
+ if (!url.endsWith("/answerCallbackQuery")) body[entityField] = body[field] === message.text ? message.entities : [];
259
+ delete body.parse_mode;
260
+ }
261
+ }
262
+ if (Array.isArray(body.media)) body.media = body.media.map((item) => ({
263
+ ...item,
264
+ ...typeof item.caption === "string" ? { caption: customerText(item.caption) } : {}
265
+ }));
266
+ const replyTo = deliveryLocale.getStore()?.replyTo ?? currentInboundRequest()?.replyTo;
267
+ const replyChat = deliveryLocale.getStore()?.chatId ?? currentInboundRequest()?.chatId;
268
+ 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 = {
269
+ message_id: Number(replyTo),
270
+ allow_sending_without_reply: true
271
+ };
272
+ const markup = body.reply_markup;
273
+ if (Array.isArray(markup?.inline_keyboard)) {
274
+ 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.");
275
+ const rows = markup.inline_keyboard.map((row) => row.filter((button) => {
276
+ if (typeof button.text !== "string" || !isTechnicalText(button.text)) return true;
277
+ reportTelegramError("technical_button_label_blocked", { text: button.text });
278
+ return false;
279
+ })).filter((row) => row.length > 0);
280
+ if (rows.length === 0 && markup.inline_keyboard.length > 0) delete body.reply_markup;
281
+ else markup.inline_keyboard = rows;
282
+ }
283
+ const links = appLinks === void 0 || fixed ? new Map() : await miniAppLinks(appLinks, linkDestinations(body));
284
+ if (links.size > 0) {
285
+ if (Array.isArray(markup?.inline_keyboard) && body.reply_markup !== void 0) markup.inline_keyboard = markup.inline_keyboard.map((row) => withMiniAppLinks(row, links));
286
+ if (Array.isArray(body.media)) body.media = body.media.map((item) => isFields(item) && item.caption_entities !== void 0 ? {
287
+ ...item,
288
+ caption_entities: withMiniAppLinks(item.caption_entities, links)
289
+ } : item);
290
+ }
291
+ const send = async () => {
292
+ const parts = url.endsWith("/sendMessage") && typeof body.text === "string" && !isExactChatPostCard(body.text) ? splitTelegramText({
293
+ text: body.text,
294
+ entities: body.entities ?? []
295
+ }) : [null];
296
+ let first;
297
+ const messageIds = [];
298
+ const attempt = async (outgoing) => {
299
+ try {
300
+ const written = (url.endsWith("/sendMessage") || url.endsWith("/editMessageText")) && typeof outgoing.text === "string" ? chatPostCardLinks(outgoing.text) ?? telegramTextLinks(outgoing.text, outgoing.entities ?? []) : void 0;
301
+ const previewOptions = written === void 0 ? {} : originalLinkPreview(telegramPreviewOptions(body, written, previews), written, links);
302
+ const payload = { ...outgoing };
303
+ if (url.endsWith("/sendMessage") || url.endsWith("/editMessageText")) {
304
+ delete payload.link_preview_options;
305
+ delete payload.disable_web_page_preview;
306
+ Object.assign(payload, previewOptions);
307
+ }
308
+ for (const field of ["entities", "caption_entities"]) if (payload[field] !== void 0) payload[field] = withMiniAppLinks(payload[field], links);
309
+ return await fetchImpl(input, {
310
+ ...init,
311
+ body: JSON.stringify(payload)
312
+ });
313
+ } catch (error) {
314
+ throw new TelegramDeliveryError(reportTelegramError("telegram_send_unknown", error, { messageIds }), "unknown", messageIds);
315
+ }
316
+ };
317
+ for (const [index, part] of parts.entries()) {
318
+ const outgoing = part === null ? { ...body } : {
319
+ ...body,
320
+ text: part.text,
321
+ entities: part.entities
322
+ };
323
+ if (index < parts.length - 1) delete outgoing.reply_markup;
324
+ let response = await attempt(outgoing);
325
+ const entityField = typeof outgoing.text === "string" ? "entities" : "caption_entities";
326
+ if (Array.isArray(outgoing[entityField]) && outgoing[entityField].length > 0 && await formattingRefused(response)) {
327
+ delete outgoing[entityField];
328
+ delete outgoing.parse_mode;
329
+ response = await attempt(outgoing);
330
+ }
331
+ const result = await response.clone().json().catch(() => null);
332
+ if (url.endsWith("/sendMessage")) {
333
+ const id = result?.result?.message_id;
334
+ if (!response.ok || result?.ok !== true || typeof id !== "number" || !Number.isSafeInteger(id) || id < 1) {
335
+ const delivery = result?.ok === false ? "failed" : "unknown";
336
+ throw new TelegramDeliveryError(reportTelegramError("telegram_send_unacknowledged", {
337
+ status: response.status,
338
+ result,
339
+ messageIds,
340
+ delivery
341
+ }), delivery, messageIds);
342
+ }
343
+ messageIds.push(id);
344
+ } else if (!response.ok || result?.ok !== true) return response;
345
+ first ??= response;
346
+ }
347
+ if (first === void 0) throw new Error("Telegram message has no visible text; nothing was sent.");
348
+ return first;
349
+ };
350
+ return typeof body.chat_id === "string" || typeof body.chat_id === "number" ? inTelegramSendQueue(scope, String(body.chat_id), send) : send();
351
+ };
352
+ }
353
+ const CHAT_ATTRIBUTE = "segmentstreamChat";
354
+ const EARLIER_CHAT_ATTRIBUTE = "segmentstreamConversation";
355
+ function withChatAddress(principal, chat) {
356
+ return {
357
+ ...principal,
358
+ attributes: {
359
+ ...principal.attributes,
360
+ [CHAT_ATTRIBUTE]: JSON.stringify(chat)
361
+ }
362
+ };
363
+ }
364
+ function chatAddressOf(principal) {
365
+ if (principal === void 0 || principal === null) return;
366
+ const attributes = principal.attributes;
367
+ if (principal.authenticator === "segmentstream-telegram") {
368
+ const chatId = attributes.chatId;
369
+ return typeof chatId !== "string" || chatId === "" ? void 0 : {
370
+ provider: "telegram",
371
+ chatId,
372
+ threadId: String(attributes.messageThreadId ?? ""),
373
+ kind: chatId.startsWith("-") ? "group" : "private"
374
+ };
375
+ }
376
+ const value = attributes["segmentstreamChat"] ?? attributes[EARLIER_CHAT_ATTRIBUTE];
377
+ if (typeof value !== "string") return;
378
+ try {
379
+ return parsedChatAddress(JSON.parse(value), attributes.identityProvider);
380
+ } catch {
381
+ return;
382
+ }
383
+ }
384
+ function parsedChatAddress(value, provider) {
385
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
386
+ const item = value;
387
+ const text = (field, empty = false) => typeof field === "string" && (empty || field !== "") && field.length <= 512;
388
+ if (item.provider !== "slack" && item.provider !== "whatsapp" && item.provider !== "web" || item.provider !== provider || !text(item.chatId) || !text(item.threadId, true) || item.kind !== "private" && item.kind !== "group" || item.peer !== void 0 && !text(item.peer)) return;
389
+ return {
390
+ provider: item.provider,
391
+ chatId: item.chatId,
392
+ threadId: item.threadId,
393
+ kind: item.kind,
394
+ ...item.peer === void 0 ? {} : { peer: item.peer }
395
+ };
396
+ }
397
+ function isSameChat(chat, destination) {
398
+ if (chat.provider !== destination.provider) return false;
399
+ return chat.chatId === destination.externalId || chat.provider !== "telegram" && chat.kind === "private" && chat.peer === destination.externalId;
400
+ }
401
+ const WEB_AUTHENTICATOR = "segmentstream-web";
402
+ const WEB_PROVIDER = "web";
403
+ const AGENT_GRANT_HEADER = "X-SegmentStream-Agent-Grant";
404
+ const WEB_GRANT_ATTRIBUTE = "webGrant";
405
+ const ACCESS_TOKEN_PREFIX = "sso_";
406
+ const INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
407
+ const INTROSPECTION_TIMEOUT_MS = 5e3;
408
+ const ANSWER_TTL_MS = 6e4;
409
+ const ANSWER_LIMIT = 1e3;
410
+ const TURN_LIMITED_CODE = "rate_limited";
411
+ var TurnLimitedError = class extends ForbiddenError {
412
+ retryAfterSeconds;
413
+ response;
414
+ constructor(retryAfterSeconds) {
415
+ super({
416
+ code: TURN_LIMITED_CODE,
417
+ message: TURN_LIMITED_CODE
418
+ });
419
+ this.retryAfterSeconds = retryAfterSeconds;
420
+ this.name = "TurnLimitedError";
421
+ this.response = Response.json({
422
+ code: TURN_LIMITED_CODE,
423
+ ok: false,
424
+ retry_after_seconds: retryAfterSeconds
425
+ }, {
426
+ status: 429,
427
+ headers: {
428
+ "cache-control": "no-store",
429
+ "retry-after": String(retryAfterSeconds)
430
+ }
431
+ });
432
+ }
433
+ };
434
+ function strings(value) {
435
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
436
+ }
437
+ function webMemberOf(body) {
438
+ if (typeof body !== "object" || body === null) return;
439
+ const answer = body;
440
+ const roles = strings(answer.roles);
441
+ if (answer.active !== true || typeof answer.member_id !== "string" || typeof answer.grant_id !== "string" || answer.chat !== `member:${answer.member_id}` || roles === void 0) return;
442
+ const limited = answer.limited;
443
+ return {
444
+ memberId: answer.member_id,
445
+ grant: answer.grant_id,
446
+ chat: answer.chat,
447
+ roles,
448
+ ...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {},
449
+ ...typeof limited === "object" && limited !== null && typeof limited.retry_after_seconds === "number" ? { limited: {
450
+ scope: typeof limited.scope === "string" ? limited.scope : "",
451
+ retryAfterSeconds: limited.retry_after_seconds
452
+ } } : {}
453
+ };
454
+ }
455
+ function ontologyIntrospection(options = {}) {
456
+ return async (token, origin, turn) => {
457
+ const ask = async (body) => (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}${INTROSPECTION_PATH}`, {
458
+ method: "POST",
459
+ headers: {
460
+ authorization: `Bearer ${await (options.token ?? runtimeToken)()}`,
461
+ "content-type": "application/json"
462
+ },
463
+ body: JSON.stringify(body),
464
+ signal: AbortSignal.timeout(INTROSPECTION_TIMEOUT_MS)
465
+ });
466
+ let response = await ask({
467
+ token,
468
+ origin,
469
+ ...turn === true ? { turn: true } : {}
470
+ });
471
+ if (turn === true && response.status === 400) response = await ask({
472
+ token,
473
+ origin
474
+ });
475
+ if (!response.ok) throw new Error(`The ontology could not say whom an agent token stands for (${response.status}).`);
476
+ return webMemberOf(await response.json());
477
+ };
478
+ }
479
+ function webPrincipal(member) {
480
+ const chat = {
481
+ provider: "web",
482
+ chatId: member.chat,
483
+ threadId: "",
484
+ kind: "private",
485
+ peer: member.memberId
486
+ };
487
+ const attributes = {
488
+ memberId: member.memberId,
489
+ identityProvider: "web",
490
+ roles: member.roles,
491
+ [WEB_GRANT_ATTRIBUTE]: member.grant
492
+ };
493
+ if (member.name !== void 0) attributes.memberName = member.name;
494
+ return withChatAddress({
495
+ authenticator: WEB_AUTHENTICATOR,
496
+ principalId: `web:${member.memberId}`,
497
+ principalType: "user",
498
+ subject: member.memberId,
499
+ attributes
500
+ }, chat);
501
+ }
502
+ function webGrantOf(principal) {
503
+ const grant = principal?.attributes[WEB_GRANT_ATTRIBUTE];
504
+ return principal?.authenticator === "segmentstream-web" && typeof grant === "string" && grant !== "" ? grant : void 0;
505
+ }
506
+ function bearerOf(request) {
507
+ const header = request.headers.get("authorization") ?? "";
508
+ return /^Bearer\s+(.+)$/iu.exec(header.trim())?.[1];
509
+ }
510
+ async function bodyOf(request) {
511
+ if (request.method !== "POST") return;
512
+ try {
513
+ const body = await request.clone().json();
514
+ return typeof body === "object" && body !== null ? body : void 0;
515
+ } catch {
516
+ return;
517
+ }
518
+ }
519
+ function answersOf(body) {
520
+ const answers = body?.answers;
521
+ return Array.isArray(answers) ? answers.filter((answer) => typeof answer === "object" && answer !== null && typeof answer.interactionId === "string") : [];
522
+ }
523
+ function startsTurn(body) {
524
+ return body?.message !== void 0 && body.message !== null;
525
+ }
526
+ function answerCache(introspect) {
527
+ const answers = new Map();
528
+ return async (token, origin, turn) => {
529
+ if (turn === true) return introspect(token, origin, true);
530
+ const key = createHash("sha256").update(`${origin} ${token}`).digest("hex");
531
+ const now = Date.now();
532
+ const kept = answers.get(key);
533
+ if (kept !== void 0 && kept.until > now) return kept.member;
534
+ answers.delete(key);
535
+ const member = await introspect(token, origin, false);
536
+ if (member !== void 0) {
537
+ if (answers.size >= ANSWER_LIMIT) answers.delete(answers.keys().next().value);
538
+ answers.set(key, {
539
+ member,
540
+ until: now + ANSWER_TTL_MS
541
+ });
542
+ }
543
+ return member;
544
+ };
545
+ }
546
+ function webAuth(options = {}) {
547
+ let introspect;
548
+ return async (request) => {
549
+ const token = bearerOf(request);
550
+ if (token === void 0 || !token.startsWith("sso_")) return null;
551
+ introspect ??= answerCache(options.introspect ?? ontologyIntrospection());
552
+ const body = await bodyOf(request);
553
+ const member = await introspect(token, new URL(request.url).origin, startsTurn(body));
554
+ if (member === void 0) throw new UnauthenticatedError({
555
+ code: "agent_token_invalid",
556
+ message: "The agent token is invalid or expired."
557
+ });
558
+ if (member.limited !== void 0) throw new TurnLimitedError(member.limited.retryAfterSeconds);
559
+ return withButtonDecision(webPrincipal(member), answersOf(body));
560
+ };
561
+ }
562
+ const ACT_AS_HEADER = "X-SegmentStream-Act-As";
563
+ function member(memberId) {
564
+ return {
565
+ kind: "member",
566
+ memberId
567
+ };
568
+ }
569
+ function actorOf(principal) {
570
+ const taskId = agentTaskIdOf(principal);
571
+ if (taskId !== void 0) return {
572
+ kind: "task",
573
+ taskId
574
+ };
575
+ const memberId = memberIdOf(principal);
576
+ return memberId === void 0 ? void 0 : member(memberId);
577
+ }
578
+ function actorKey(actor) {
579
+ return actor.kind === "member" ? `member:${actor.memberId}` : `task:${actor.taskId}`;
580
+ }
581
+ var ActorRequiredError = class extends Error {
582
+ name = "ActorRequiredError";
583
+ };
584
+ function actorHeaders(input) {
585
+ const { actor } = input;
586
+ if (actor.kind === "task") {
587
+ const secret = (input.secret ?? taskSecret)(actor.taskId);
588
+ if (secret === void 0) throw new ActorRequiredError("The task is no longer live in this session.");
589
+ return { [AGENT_TASK_HEADER]: secret };
590
+ }
591
+ const provider = memberIdOf(input.principal) === actor.memberId ? identityProviderOf(input.principal) : void 0;
592
+ const grant = provider === "web" ? webGrantOf(input.principal) : void 0;
593
+ if (provider === "web" && grant === void 0) throw new ActorRequiredError("The web session carries no agent token grant.");
594
+ return {
595
+ [ACT_AS_HEADER]: actor.memberId,
596
+ ...provider === void 0 ? {} : { "X-SegmentStream-Identity-Provider": provider },
597
+ ...grant === void 0 ? {} : { [AGENT_GRANT_HEADER]: grant }
598
+ };
599
+ }
600
+ function memberTool(tool) {
601
+ return defineDynamic$1((context) => actorOf(context.session.auth.current)?.kind === "task" ? null : tool);
602
+ }
603
+ const CONFIRMATION_TTL_MS = 6e5;
604
+ function needsConfirmation(labels) {
605
+ return labels.readOnlyHint !== true && (labels.destructiveHint === true || labels.irreversibleHint === true || labels.openWorldHint === true || labels.destructiveHint === void 0 && labels.irreversibleHint === void 0);
606
+ }
607
+ function canonical(value) {
608
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
609
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
610
+ const encoded = JSON.stringify(value);
611
+ if (encoded === void 0) throw new TypeError("Action input must be JSON.");
612
+ return encoded;
613
+ }
614
+ function inputHash(input) {
615
+ return createHash("sha256").update(canonical(input)).digest("hex");
616
+ }
617
+ function isSameSource(saved, current) {
618
+ return current !== void 0 && saved.provider === current.provider && saved.chatId === current.chatId && saved.threadId === current.threadId;
619
+ }
620
+ const confirmations = defineState("segmentstream.confirmations", () => ({}));
621
+ function connectionHints(ctx) {
622
+ const hints = ctx.toolAnnotations;
623
+ return typeof hints === "object" && hints !== null && !Array.isArray(hints) ? hints : void 0;
624
+ }
625
+ function actionApproval(options) {
626
+ const state = options.state ?? confirmations;
627
+ const now = options.now ?? Date.now;
628
+ const denied = (reason) => ({
629
+ type: "denied",
630
+ reason
631
+ });
632
+ return {
633
+ prompt({ callId }) {
634
+ try {
635
+ return state.get()[callId]?.prompt;
636
+ } catch {
637
+ return;
638
+ }
639
+ },
640
+ async request(ctx) {
641
+ const actor = actorOf(ctx.session.auth.current);
642
+ if (actor?.kind === "task") {
643
+ if (isChatPost(ctx.toolName)) return denied("Chat posting is unavailable in a task.");
644
+ if (connectionHints(ctx) !== void 0) return "approved";
645
+ try {
646
+ await options.labels(actor, ctx.toolName, ctx.toolInput ?? {});
647
+ } catch (error) {
648
+ console.warn("The ontology action permission check failed.", error);
649
+ return denied("The action is unavailable or the task's role does not permit it.");
650
+ }
651
+ return "approved";
652
+ }
653
+ const memberId = actor?.memberId;
654
+ if (memberId === void 0) return denied("A paired member is required.");
655
+ const present = (run) => options.texts === void 0 ? run() : withTelegramTexts(options.texts(), run, () => confirmationLocale(ctx.session.auth.current));
656
+ const hash = inputHash(ctx.toolInput ?? {});
657
+ const saved = state.get()[ctx.callId];
658
+ if (saved !== void 0) {
659
+ if (saved.memberId !== memberId || saved.action !== ctx.toolName || saved.inputHash !== hash) return denied("The confirmation belongs to another member, action or input.");
660
+ if (saved.expiresAt <= now()) return denied("The confirmation expired. Make a new call.");
661
+ if (saved.status === "consumed" || saved.status === "cancelled") return denied("The confirmation has already been used or cancelled.");
662
+ }
663
+ const hints = connectionHints(ctx);
664
+ if (saved === void 0 && !isChatPost(ctx.toolName) && hints !== void 0 && !needsConfirmation(hints)) return "approved";
665
+ let labels;
666
+ try {
667
+ labels = await options.labels(member(memberId), ctx.toolName, ctx.toolInput ?? {}, void 0, hints);
668
+ } catch (error) {
669
+ console.warn("The ontology action permission check failed.", error);
670
+ return denied("The action is unavailable or the member no longer has permission.");
671
+ }
672
+ const offered = options.copy === void 0 ? ctx.toolInput?._confirmation : options.copy(member(memberId), ctx.toolInput ?? {});
673
+ const copy = labels.confirmation === false ? void 0 : confirmationCopy(offered);
674
+ const businessInput = Object.fromEntries(Object.entries(ctx.toolInput ?? {}).filter(([key]) => key !== "_confirmation"));
675
+ const posting = isChatPost(ctx.toolName);
676
+ let description;
677
+ const missingCopy = () => denied((offered === void 0 ? "This action needs a confirmation card and the call has no _confirmation. " : `The call's _confirmation is invalid: ${confirmationCopyIssue(offered) ?? "it cannot be shown"}. `) + "Make the call again with _confirmation (for a file call, in its arguments file) in the chat's language: a plain single-line question naming the action and its key records and amounts (at most 300 characters), and short confirm, cancel, done, cancelled and failed labels without emoji.");
678
+ if (posting && saved === void 0 && labels.confirmation === true && copy === void 0) return missingCopy();
679
+ let prompt;
680
+ const chat = chatAddressOf(ctx.session.auth.current);
681
+ if (posting) try {
682
+ description = await options.describe?.(member(memberId), ctx.toolName, businessInput, hints);
683
+ const preview = description?.chatPost;
684
+ if (description === void 0 || preview === void 0 || chat === void 0 || isSameChat(chat, preview)) return denied("A complete preview for a different chat is required. Reply normally in this chat.");
685
+ const previewDescription = {
686
+ ...description,
687
+ warning: labels.destructiveHint === true || labels.irreversibleHint === true
688
+ };
689
+ if (chat.provider === "telegram") present(() => chatPostCard(previewDescription, copy));
690
+ else {
691
+ prompt = present(() => chatPostPrompt(previewDescription, copy));
692
+ if (!promptFits(chat.provider, prompt)) return denied("The full message does not fit this chat's confirmation card. Make a shorter draft.");
693
+ }
694
+ if (saved !== void 0 && (saved.description?.chatPost === void 0 || chatPostDigest(saved.description.chatPost) !== chatPostDigest(preview) || saved.source === void 0 || !isSameSource(saved.source, chat))) return denied("The destination or attribution changed. Make a new call and confirmation.");
695
+ } catch (error) {
696
+ console.warn("The exact chat confirmation could not be prepared.", error);
697
+ return denied("The full exact chat preview is unavailable or too long. Make a new call.");
698
+ }
699
+ if (saved?.status === "approved") {
700
+ state.update((all) => ({
701
+ ...all,
702
+ [ctx.callId]: {
703
+ ...saved,
704
+ status: "consumed"
705
+ }
706
+ }));
707
+ return "approved";
708
+ }
709
+ if (saved !== void 0) return denied("The original call is waiting for its Confirm / Cancel buttons.");
710
+ if (!posting && !needsConfirmation(labels)) return "approved";
711
+ if (labels.confirmation === true && labels.preview !== true && copy === void 0) return missingCopy();
712
+ try {
713
+ if (!posting) description = await options.describe?.(member(memberId), ctx.toolName, businessInput, hints, confirmationLocale(ctx.session.auth.current));
714
+ if (description === void 0) throw new Error("A trusted confirmation description is required.");
715
+ } catch (error) {
716
+ if (error instanceof ConfirmationRefused) return denied(`The action refuses this input, so no card was shown and nothing ran: ${error.reason} Tell the member why in their language, in a short message; do not ask them to confirm it and do not make the same call again.`);
717
+ console.warn("The confirmation description could not be read.", error);
718
+ if (error instanceof UnsafeConfirmationTarget) return denied(`No confirmation card can name the ${error.label}: its title is missing, unreadable, or looks like a file name, link or identifier. Another call will be refused the same way; tell the member, who can rename that record or make the change in the app.`);
719
+ return denied("Trusted confirmation facts are incomplete, unsafe or too long. Resolve every target title and narrow the input before making a new call.");
720
+ }
721
+ description = description === void 0 ? void 0 : {
722
+ ...description,
723
+ warning: labels.destructiveHint === true || labels.irreversibleHint === true
724
+ };
725
+ try {
726
+ if (!posting) prompt = present(() => renderConfirmation(description, copy)).text;
727
+ } catch {
728
+ return denied("The complete confirmation facts are unsafe or too long. Narrow the action input.");
729
+ }
730
+ if (prompt !== void 0 && !promptFits(ctx.session.auth.current?.attributes.identityProvider, prompt)) return denied("The complete confirmation facts are too long for this chat's confirmation card. Narrow the action input.");
731
+ state.update((all) => ({
732
+ ...all,
733
+ [ctx.callId]: {
734
+ memberId,
735
+ action: ctx.toolName,
736
+ inputHash: hash,
737
+ expiresAt: now() + CONFIRMATION_TTL_MS,
738
+ status: "pending",
739
+ ...copy === void 0 ? {} : { copy },
740
+ ...description === void 0 ? {} : { description },
741
+ ...prompt === void 0 ? {} : { prompt },
742
+ ...posting && chat !== void 0 ? { source: chat } : {}
743
+ }
744
+ }));
745
+ return "user-approval";
746
+ },
747
+ response(ctx) {
748
+ const saved = state.get()[ctx.request.callId];
749
+ const reject = (reason) => ({
750
+ status: "rejected",
751
+ reason
752
+ });
753
+ if (saved === void 0 || saved.status !== "pending") return reject("This confirmation is no longer pending.");
754
+ if (ctx.response.principal.attributes.confirmationRequestId !== ctx.request.interactionId || ctx.response.principal.attributes.confirmationDecision !== (ctx.response.decision === "deny" ? "cancel" : "approve")) return reject("Use the Confirm or Cancel button on the action's message.");
755
+ if (memberIdOf(ctx.response.principal) !== saved.memberId || memberIdOf(ctx.request.principal) !== saved.memberId) return reject("Only the requesting member can confirm or cancel this action.");
756
+ if (saved.action !== ctx.request.toolName || saved.inputHash !== inputHash(ctx.request.toolInput ?? {})) return reject("The action or input changed. Make a new call.");
757
+ if (ctx.response.decision === "approve" && saved.expiresAt <= now()) return reject("This confirmation expired.");
758
+ state.update((all) => ({
759
+ ...all,
760
+ [ctx.request.callId]: {
761
+ ...saved,
762
+ status: ctx.response.decision === "approve" ? "approved" : "cancelled",
763
+ ...ctx.response.decision === "deny" && ["edit", "expired"].includes(String(ctx.response.principal.attributes.confirmationReason)) ? { cancellationReason: ctx.response.principal.attributes.confirmationReason } : {}
764
+ }
765
+ }));
766
+ return { status: "allowed" };
767
+ }
768
+ };
769
+ }
770
+ function rejection(error) {
771
+ let cause = error.cause;
772
+ for (let depth = 0; depth < 4 && cause !== void 0; depth++) {
773
+ const code = object(object(cause).structuredContent).error;
774
+ if (typeof code === "string") return code;
775
+ cause = object(cause).cause;
776
+ }
777
+ return "";
778
+ }
779
+ const REFUSALS = new Set([
780
+ "action_rejected",
781
+ "not_found",
782
+ "conflict",
783
+ "forbidden"
784
+ ]);
785
+ var OntologyToolRejected = class extends Error {
786
+ code = "ontology_tool_rejected";
787
+ };
788
+ var OntologyActionNotPermitted = class extends Error {
789
+ code = "ontology_action_not_permitted";
790
+ };
791
+ var OntologyFileUnavailable = class extends Error {
792
+ code;
793
+ requestId;
794
+ retryable = true;
795
+ constructor(code, requestId, options) {
796
+ super(`${code}${requestId === void 0 ? "" : ` (${requestId})`}`, options);
797
+ this.code = code;
798
+ this.requestId = requestId;
799
+ }
800
+ };
801
+ function ontologyTools(options = {}) {
802
+ const runtimeSources = options.runtimeSources ?? new Map();
803
+ const initialized = new Map();
804
+ const definitions = new Map();
805
+ async function post(actor, method, params, credential, secrets, signal) {
806
+ const key = actorKey(actor);
807
+ const current = actorOf(options.principal);
808
+ const acting = actorHeaders({
809
+ actor,
810
+ principal: current !== void 0 && actorKey(current) === key ? options.principal : null,
811
+ secret: options.secret
812
+ });
813
+ secrets.add(acting["X-SegmentStream-Agent-Task"] ?? "");
814
+ const response = await (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}/mcp`, {
815
+ method: "POST",
816
+ headers: {
817
+ authorization: `Bearer ${credential}`,
818
+ ...acting,
819
+ "content-type": "application/json",
820
+ accept: "application/json, text/event-stream",
821
+ "mcp-protocol-version": "2025-11-25"
822
+ },
823
+ body: JSON.stringify({
824
+ jsonrpc: "2.0",
825
+ id: "approval-tools",
826
+ method,
827
+ params
828
+ }),
829
+ signal: signal ?? AbortSignal.timeout(15e3),
830
+ redirect: "error"
831
+ });
832
+ if (!response.ok) throw Object.assign(new Error(`Cannot check action permission (HTTP ${response.status}).`, { cause: await response.text() }), { status: response.status });
833
+ const body = object(await response.json());
834
+ if (body.error !== void 0) throw new Error("Ontology metadata unavailable.", { cause: body.error });
835
+ return object(body.result);
836
+ }
837
+ async function quiet(actor, method, params, signal) {
838
+ const secrets = new Set();
839
+ try {
840
+ const credential = await (options.token ?? runtimeToken)();
841
+ secrets.add(credential);
842
+ return await post(actor, method, params, credential, secrets, signal);
843
+ } catch (error) {
844
+ console.warn("[segmentstream] ontology_metadata_fallback", {
845
+ method,
846
+ error: redactDiagnostic(error, secrets)
847
+ });
848
+ return;
849
+ }
850
+ }
851
+ async function rpc(actor, method, params, signal) {
852
+ const key = actorKey(actor);
853
+ const current = actorOf(options.principal);
854
+ const own = current !== void 0 && actorKey(current) === key ? options.principal : null;
855
+ if (method === "tools/call") {
856
+ const envelope = options.envelope ?? runtimeEnvelope({ principal: own });
857
+ const extended = envelope.source !== void 0 && await runtimeSource(actor, signal);
858
+ params = {
859
+ ...params,
860
+ arguments: {
861
+ ...object(params.arguments),
862
+ _segmentstream: compatibleRuntimeEnvelope(envelope, extended)
863
+ }
864
+ };
865
+ }
866
+ const credential = await (options.token ?? runtimeToken)();
867
+ const secrets = new Set([credential]);
868
+ if (method === "tools/call") await options.beforeCall?.(String(params.name));
869
+ try {
870
+ const result = await post(actor, method, params, credential, secrets, signal);
871
+ if (method === "tools/list" && Array.isArray(result.tools)) runtimeSources.set(key, result.tools.map(object).some((tool) => object(tool._meta)[RUNTIME_SOURCE_PROTOCOL] === 1));
872
+ if (result.isError === true) {
873
+ const failure = object(result.structuredContent);
874
+ if (method === "tools/call" && params.name === "files_download" && failure.retryable === true && ["ontology_updating", "storage_unavailable"].includes(String(failure.error))) throw new OntologyFileUnavailable(String(failure.error), typeof failure.request_id === "string" ? failure.request_id : void 0, { cause: result });
875
+ const message = (Array.isArray(result.content) ? result.content : []).map(object).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
876
+ if ([
877
+ "action_rejected",
878
+ "invalid_input",
879
+ "invalid_request",
880
+ "invalid_json",
881
+ "unsupported_media_type",
882
+ "forbidden",
883
+ "unauthorized",
884
+ "not_invited",
885
+ "not_found",
886
+ "conflict",
887
+ "invalid_cursor",
888
+ "ontology_version_mismatch",
889
+ "discovery_too_large"
890
+ ].includes(String(object(result.structuredContent).error))) throw new OntologyToolRejected(message || "ontology_operation_rejected", { cause: result });
891
+ throw new Error("ontology_action_outcome_uncertain", { cause: result });
892
+ }
893
+ return result;
894
+ } catch (error) {
895
+ const diagnostic = redactDiagnostic(error, secrets);
896
+ const reference = randomUUID();
897
+ console.error("[segmentstream] ontology_request_failed", {
898
+ reference,
899
+ error: diagnostic
900
+ });
901
+ if (error instanceof OntologyFileUnavailable) throw new OntologyFileUnavailable(error.code, error.requestId, { cause: diagnostic });
902
+ if (error instanceof OntologyToolRejected) throw new OntologyToolRejected(String(object(diagnostic).message), { cause: diagnostic });
903
+ throw new Error(`The ontology request failed (${reference}).`, { cause: diagnostic });
904
+ }
905
+ }
906
+ function initialize(actor, signal) {
907
+ const key = actorKey(actor);
908
+ let pending = initialized.get(key);
909
+ if (pending === void 0) {
910
+ pending = quiet(actor, "initialize", {
911
+ protocolVersion: "2025-11-25",
912
+ capabilities: {},
913
+ clientInfo: {
914
+ name: "segmentstream-agent",
915
+ version: "1"
916
+ }
917
+ }, signal);
918
+ initialized.set(key, pending);
919
+ }
920
+ return pending;
921
+ }
922
+ async function advertises(actor, capability, signal) {
923
+ const result = await initialize(actor, signal);
924
+ return object(object(result?.capabilities).experimental)[capability] !== void 0;
925
+ }
926
+ async function runtimeSource(actor, signal) {
927
+ const key = actorKey(actor);
928
+ if (!runtimeSources.has(key)) {
929
+ if (await advertises(actor, "segmentstream/runtime-source", signal)) runtimeSources.set(key, true);
930
+ else await rpc(actor, "tools/list", {}, signal);
931
+ }
932
+ return runtimeSources.get(key) === true;
933
+ }
934
+ async function toolFor(actor, action, signal) {
935
+ const result = await rpc(actor, "tools/list", {}, signal);
936
+ const tools = Array.isArray(result.tools) ? result.tools.map(object) : [];
937
+ const bareName = action.split("__").at(-1);
938
+ let tool = tools.find((candidate) => candidate.name === bareName);
939
+ if (tool === void 0 && tools.some((item) => item.name === "ontology_describe_tool")) {
940
+ const inspected = await rpc(actor, "tools/call", {
941
+ name: "ontology_describe_tool",
942
+ arguments: { name: bareName }
943
+ }, signal);
944
+ const candidate = object(object(inspected.structuredContent).tool);
945
+ if (candidate.name === bareName) tool = candidate;
946
+ }
947
+ if (tool === void 0) throw new OntologyActionNotPermitted("Action not permitted.");
948
+ return {
949
+ tool,
950
+ tools
951
+ };
952
+ }
953
+ async function listed(actor, name, signal) {
954
+ const result = await quiet(actor, "resources/read", { uri: `ontology://tools/${encodeURIComponent(name)}` }, signal);
955
+ const text = object(Array.isArray(result?.contents) ? result.contents[0] : void 0).text;
956
+ try {
957
+ const tool = object(typeof text === "string" ? JSON.parse(text) : void 0);
958
+ return tool.name === name ? tool : void 0;
959
+ } catch {
960
+ return;
961
+ }
962
+ }
963
+ function definition(actor, action, signal) {
964
+ const bareName = action.split("__").at(-1) ?? action;
965
+ const key = `${actorKey(actor)} ${bareName}`;
966
+ let pending = definitions.get(key);
967
+ if (pending === void 0) {
968
+ pending = listed(actor, bareName, signal).then(async (tool) => tool === void 0 ? toolFor(actor, action, signal) : { tool });
969
+ definitions.set(key, pending);
970
+ pending.catch(() => definitions.delete(key));
971
+ }
972
+ return pending;
973
+ }
974
+ async function resolve(actor, action, input, signal, hints, depth = 0) {
975
+ if (depth > 3) throw new Error("Too many nested ontology tools.");
976
+ const bareName = action.split("__").at(-1);
977
+ if (bareName === "attachments_promote") {
978
+ const target = promotionTarget(input);
979
+ return resolve(actor, target.action, target.input, signal, void 0, depth + 1);
980
+ }
981
+ const found = depth === 0 && hints?.["segmentstream/confirmation"] !== void 0 ? { tool: {
982
+ name: bareName,
983
+ annotations: hints
984
+ } } : await definition(actor, action, signal);
985
+ if (depth > 0 && isChatPost(String(found.tool.name))) throw new Error("Exact chat posting must use the direct chat_post_message tool.");
986
+ if (found.tool.name === "ontology_call_tool") {
987
+ if (typeof input.name !== "string") throw new Error("A target tool is required.");
988
+ return resolve(actor, input.name, object(input.arguments), signal, void 0, depth + 1);
989
+ }
990
+ return {
991
+ ...found,
992
+ input
993
+ };
994
+ }
995
+ async function preview(actor, name, input, locale, signal) {
996
+ let result;
997
+ try {
998
+ result = await rpc(actor, CONFIRMATION_PREVIEW_METHOD, {
999
+ name,
1000
+ arguments: input,
1001
+ locale
1002
+ }, signal);
1003
+ } catch (error) {
1004
+ if (error instanceof OntologyToolRejected && REFUSALS.has(rejection(error))) throw new ConfirmationRefused(error.message);
1005
+ console.warn("The action's confirmation could not be read; showing its fields.", error);
1006
+ return;
1007
+ }
1008
+ const structured = object(result.structuredContent);
1009
+ if (structured.confirmation === null || structured.confirmation === void 0) return;
1010
+ try {
1011
+ return confirmationCard(structured.confirmation);
1012
+ } catch (error) {
1013
+ console.warn("The action's confirmation cannot be shown; showing its fields.", error);
1014
+ return;
1015
+ }
1016
+ }
1017
+ async function catalogEntities(actor, signal) {
1018
+ try {
1019
+ const catalog = await rpc(actor, "resources/read", { uri: "ontology://catalog" }, signal);
1020
+ const text = object(Array.isArray(catalog.contents) ? catalog.contents[0] : void 0).text;
1021
+ const manifest = object(typeof text === "string" ? JSON.parse(text) : void 0);
1022
+ return Array.isArray(manifest.entities) ? manifest.entities.map(object) : [];
1023
+ } catch (error) {
1024
+ console.warn("The confirmation catalog could not be read.", error);
1025
+ return [];
1026
+ }
1027
+ }
1028
+ return {
1029
+ rpc,
1030
+ async supportsRuntimeSource(actor, signal) {
1031
+ return runtimeSource(actor, signal);
1032
+ },
1033
+ async labels(actor, action, input = {}, signal, hints) {
1034
+ const { tool } = await resolve(actor, action, input, signal, hints);
1035
+ const annotations = object(tool.annotations);
1036
+ return {
1037
+ ...Object.fromEntries(Object.entries(annotations).filter(([key]) => key !== CONFIRMATION_FACTS)),
1038
+ confirmation: annotations["segmentstream/confirmation"] !== void 0 || object(object(tool.inputSchema).properties)._confirmation !== void 0,
1039
+ ...object(annotations["segmentstream/confirmation"]).preview === true ? { preview: true } : {}
1040
+ };
1041
+ },
1042
+ async describe(actor, action, input, hints, locale = "en") {
1043
+ const signal = AbortSignal.timeout(15e3);
1044
+ const resolved = await resolve(actor, action, input, signal, hints);
1045
+ const { tool } = resolved;
1046
+ input = resolved.input;
1047
+ action = String(tool.name);
1048
+ if (isChatPost(action)) {
1049
+ if (!supportsChatPost(tool)) throw new Error("The ontology does not support exact chat confirmations.");
1050
+ const read = async (name, args) => {
1051
+ if (resolved.tools !== void 0 && !resolved.tools.some((candidate) => candidate.name === name && object(candidate.annotations).readOnlyHint === true)) throw new Error("The chat preview reads are unavailable.");
1052
+ const result = await rpc(actor, "tools/call", {
1053
+ name,
1054
+ arguments: args
1055
+ }, signal);
1056
+ if (result.isError === true) throw new Error("The chat preview could not be resolved.");
1057
+ return object(result.structuredContent);
1058
+ };
1059
+ const [caller, destinations] = await Promise.all([read("me", {}), read("chat_list", { chat: input.chat })]);
1060
+ return {
1061
+ ...describeChatPost({
1062
+ values: input,
1063
+ caller,
1064
+ destinations
1065
+ }),
1066
+ action: typeof tool.title === "string" ? tool.title : typeof tool.description === "string" ? tool.description.split("\n\n")[0] : ""
1067
+ };
1068
+ }
1069
+ async function read(entityName, id) {
1070
+ const name = actionToolName(entityName, "get");
1071
+ try {
1072
+ const result = await rpc(actor, "tools/call", {
1073
+ name,
1074
+ arguments: { id }
1075
+ }, signal);
1076
+ return result.isError === true ? void 0 : object(result.structuredContent);
1077
+ } catch (error) {
1078
+ console.warn("A confirmation record title could not be read.", error);
1079
+ return;
1080
+ }
1081
+ }
1082
+ const facts = object(tool.annotations)[CONFIRMATION_FACTS];
1083
+ const card = object(facts).preview === true ? await preview(actor, String(tool.name), input, locale, signal) : void 0;
1084
+ if (card !== void 0) return {
1085
+ card,
1086
+ action: card.title,
1087
+ fields: []
1088
+ };
1089
+ if (facts !== void 0) return describeConfirmation({
1090
+ ...factsConfirmation(object(facts)),
1091
+ values: input,
1092
+ read
1093
+ });
1094
+ const entities = await catalogEntities(actor, signal);
1095
+ const entity = entities.find((candidate) => {
1096
+ return [
1097
+ "create",
1098
+ "update",
1099
+ "delete",
1100
+ "link",
1101
+ "unlink",
1102
+ ...Array.isArray(candidate.actions) ? candidate.actions.map((item) => object(item).name) : []
1103
+ ].some((name) => typeof name === "string" && actionToolName(String(candidate.name), name) === tool.name);
1104
+ });
1105
+ return describeConfirmation({
1106
+ title: typeof tool.title === "string" ? tool.title : void 0,
1107
+ description: typeof tool.description === "string" ? tool.description : void 0,
1108
+ schema: object(tool.inputSchema),
1109
+ entity,
1110
+ entities,
1111
+ values: input,
1112
+ read
1113
+ });
1114
+ }
1115
+ };
1116
+ }
1117
+ function ontologyToolLabels(options = {}) {
1118
+ return ontologyTools(options).labels;
1119
+ }
1120
+ function actionToolName(entity, action) {
1121
+ const snake = (name) => name.replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
1122
+ return `${snake(entity)}_${snake(action)}`;
1123
+ }
1124
+ function promotionTarget(input) {
1125
+ const entity = input.entity;
1126
+ const action = input.action;
1127
+ if (typeof entity !== "string" || typeof action !== "string" || !/^(?:[a-z][a-zA-Z0-9]*|[a-z][a-z0-9]*(?:_[a-z0-9]+)*)$/.test(entity) || !/^(?:[a-z][a-zA-Z0-9]*|[a-z][a-z0-9]*(?:_[a-z0-9]+)*)$/.test(action)) throw new Error("A valid attachment target entity and action are required.");
1128
+ return {
1129
+ action: actionToolName(entity, action),
1130
+ input: {
1131
+ ...object(input.input),
1132
+ ...typeof input.record_id === "string" ? { id: input.record_id } : {}
1133
+ }
1134
+ };
1135
+ }
1136
+ const DESCRIPTION = "The company's ontology: its records, their history, and the actions that change them, narrowed to what the user you act for may read and do. Each <entity>_find says what its fields mean, its related records and its metrics; list_metrics lists every metric, and query_metrics counts and sums them. An ontology that ranks entities by meaning lists segmentstream__ontology__discover: call it with the member's request and what you understand they want, then the tools it names. Call me for that user.";
1137
+ function actAsHeaders(input) {
1138
+ const actor = actorOf(input.principal);
1139
+ if (actor === void 0) throw new ActorRequiredError("The ontology is reachable only for a member paired with this agent or a live task.");
1140
+ if (actorKey(actor) !== actorKey(input.expected)) throw new ActorRequiredError("The ontology connection was opened for another member or task.");
1141
+ return actorHeaders({
1142
+ actor,
1143
+ principal: input.principal,
1144
+ secret: input.secret
1145
+ });
1146
+ }
1147
+ function ontologyConnection(input) {
1148
+ const actor = actorOf(input.principal);
1149
+ if (actor === void 0) return null;
1150
+ const origin = appOrigin(input.environment ?? process.env);
1151
+ const token = input.token ?? runtimeToken;
1152
+ const headers = (context) => actAsHeaders({
1153
+ principal: context.session.auth.current,
1154
+ expected: actor,
1155
+ secret: input.secret
1156
+ });
1157
+ const common = {
1158
+ url: `${origin}/mcp`,
1159
+ protocolVersionDiscovery: false,
1160
+ description: DESCRIPTION,
1161
+ approval: actionApproval({
1162
+ ...ontologyTools(input),
1163
+ texts: input.texts
1164
+ }),
1165
+ auth: {
1166
+ principalType: "app",
1167
+ getToken: async () => {
1168
+ const value = await token();
1169
+ const expiresAt = tokenExpiry(value);
1170
+ return expiresAt === void 0 ? { token: value } : {
1171
+ token: value,
1172
+ expiresAt
1173
+ };
1174
+ }
1175
+ },
1176
+ headers
1177
+ };
1178
+ if (actor.kind === "task") return defineMcpClientConnection({
1179
+ ...common,
1180
+ instanceKey: `${origin}/mcp#task:${actor.taskId}`,
1181
+ tools: { block: [CHAT_POST_TOOL] }
1182
+ });
1183
+ const memberId = actor.memberId;
1184
+ const web = input.principal?.authenticator === WEB_AUTHENTICATOR;
1185
+ const chatPosting = input.chatPosting === true && !web;
1186
+ const chatProtocol = chatPosting ? ":chat-post-v1" : "";
1187
+ const sourceProtocol = input.runtimeSource ? ":runtime-source-v1" : "";
1188
+ return defineMcpClientConnection({
1189
+ ...common,
1190
+ instanceKey: `${origin}/mcp#member:${memberId}${web ? ":web" : ""}${chatProtocol}${sourceProtocol}`,
1191
+ ...web ? { tools: { block: [CHAT_POST_TOOL] } } : {},
1192
+ ...chatPosting || input.runtimeSource ? { toolCall: { providedArguments: { [CHAT_POST_ENVELOPE]: (ctx) => {
1193
+ headers(ctx);
1194
+ const base = compatibleRuntimeEnvelope(runtimeEnvelope({
1195
+ principal: ctx.session.auth.current,
1196
+ sessionId: ctx.session.id,
1197
+ callId: ctx.callId
1198
+ }), input.runtimeSource === true);
1199
+ if (!isChatPost(ctx.toolName)) return base;
1200
+ const saved = confirmations.get()[ctx.callId];
1201
+ const preview = saved?.description?.chatPost;
1202
+ if (saved?.status !== "consumed" || saved.memberId !== memberId || saved.action.split("__").at(-1) !== ctx.toolName || saved.expiresAt <= Date.now() || preview === void 0 || saved.source === void 0) throw new Error("Exact chat posting requires the original unexpired confirmed call.");
1203
+ const source = saved.source;
1204
+ return {
1205
+ ...base,
1206
+ operation_id: chatPostOperationId(ctx.session.id, ctx.callId),
1207
+ source: source.provider === "telegram" ? {
1208
+ provider: "telegram",
1209
+ chat_id: source.chatId,
1210
+ thread_id: source.threadId,
1211
+ ...base.source
1212
+ } : {
1213
+ provider: source.provider,
1214
+ chat_id: source.chatId,
1215
+ thread_id: source.threadId,
1216
+ kind: source.kind,
1217
+ ...source.peer === void 0 ? {} : { peer: source.peer }
1218
+ },
1219
+ expected: {
1220
+ chat_id: preview.chatId,
1221
+ digest: chatPostDigest(preview)
1222
+ }
1223
+ };
1224
+ } } } } : {}
1225
+ });
1226
+ }
1227
+ const MAXIMUM_ATTACHMENT_BYTES = MAXIMUM_DOWNLOAD_BYTES;
1228
+ const ATTACHMENT_TTL_HOURS = 24;
1229
+ const CHAT_HEADER = "X-SegmentStream-Agent-Chat";
1230
+ const EARLIER_CHAT_HEADER = "X-SegmentStream-Agent-Conversation";
1231
+ const SESSION_HEADER = "X-SegmentStream-Agent-Session";
1232
+ const ATTACHMENT_URL_PROTOCOL = "segmentstream-attachment:";
1233
+ const CALL_TIMEOUT_MS = 3e4;
1234
+ const TRANSFER_TIMEOUT_MS = 12e4;
1235
+ var AttachmentError = class extends Error {
1236
+ name = "AttachmentError";
1237
+ code;
1238
+ status;
1239
+ constructor(input) {
1240
+ super(input.message, input.cause === void 0 ? void 0 : { cause: input.cause });
1241
+ this.code = input.code;
1242
+ this.status = input.status;
1243
+ }
1244
+ };
1245
+ function isRecord(value) {
1246
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1247
+ }
1248
+ function invalid(call) {
1249
+ return new AttachmentError({
1250
+ code: "invalid_response",
1251
+ message: `The ontology service answered the ${call} with an invalid body.`
1252
+ });
1253
+ }
1254
+ function attachmentOf(value, call) {
1255
+ if (!isRecord(value) || typeof value.id !== "string" || typeof value.filename !== "string" || typeof value.content_type !== "string" || typeof value.size !== "number" || typeof value.sha256 !== "string" || typeof value.state !== "string" || typeof value.created_at !== "string" || typeof value.expires_at !== "string") throw invalid(call);
1256
+ return {
1257
+ id: value.id,
1258
+ filename: value.filename,
1259
+ contentType: value.content_type,
1260
+ size: value.size,
1261
+ sha256: value.sha256,
1262
+ state: value.state,
1263
+ createdAt: value.created_at,
1264
+ expiresAt: value.expires_at,
1265
+ promotion: value.promotion ?? null
1266
+ };
1267
+ }
1268
+ function grantOf(value, call) {
1269
+ if (!isRecord(value) || typeof value.url !== "string" || value.method !== "GET" && value.method !== "PUT" || !isRecord(value.headers)) throw invalid(call);
1270
+ return {
1271
+ url: value.url,
1272
+ method: value.method,
1273
+ headers: Object.fromEntries(Object.entries(value.headers).filter((entry) => typeof entry[1] === "string"))
1274
+ };
1275
+ }
1276
+ async function refusal(response, call) {
1277
+ const status = response.status;
1278
+ let value;
1279
+ try {
1280
+ value = await response.json();
1281
+ } catch (error) {
1282
+ return new AttachmentError({
1283
+ code: `http_${status}`,
1284
+ status,
1285
+ message: `The ontology service refused the ${call} with HTTP ${status}.`,
1286
+ cause: error
1287
+ });
1288
+ }
1289
+ const body = isRecord(value) ? value : {};
1290
+ return new AttachmentError({
1291
+ code: typeof body.error === "string" ? body.error : `http_${status}`,
1292
+ status,
1293
+ message: `${typeof body.detail === "string" ? body.detail : `HTTP ${status}`}${typeof body.request_id === "string" ? ` (request ${body.request_id})` : ""}`
1294
+ });
1295
+ }
1296
+ async function boundedBytes(response, maxBytes) {
1297
+ const declared = Number(response.headers.get("content-length") ?? "");
1298
+ if (Number.isFinite(declared) && declared > maxBytes) throw new AttachmentError({
1299
+ code: "too_large",
1300
+ message: "The stored file is too large."
1301
+ });
1302
+ if (response.body === null) return new Uint8Array();
1303
+ const reader = response.body.getReader();
1304
+ const chunks = [];
1305
+ let size = 0;
1306
+ for (;;) {
1307
+ const next = await reader.read();
1308
+ if (next.done) break;
1309
+ size += next.value.byteLength;
1310
+ if (size > maxBytes) {
1311
+ await reader.cancel();
1312
+ throw new AttachmentError({
1313
+ code: "too_large",
1314
+ message: "The stored file is too large."
1315
+ });
1316
+ }
1317
+ chunks.push(next.value);
1318
+ }
1319
+ return new Uint8Array(Buffer.concat(chunks));
1320
+ }
1321
+ function agentAttachments(input) {
1322
+ const fetchImpl = input.fetch ?? fetch;
1323
+ const base = `${input.origin}/api/ontology/agent/attachments`;
1324
+ async function call(owner, path, name, body) {
1325
+ const token = await input.token();
1326
+ let response;
1327
+ try {
1328
+ response = await fetchImpl(`${base}${path}`, {
1329
+ method: body === void 0 ? "GET" : "POST",
1330
+ headers: {
1331
+ authorization: `Bearer ${token}`,
1332
+ accept: "application/json",
1333
+ [ACT_AS_HEADER]: owner.memberId,
1334
+ [CHAT_HEADER]: owner.chat,
1335
+ [EARLIER_CHAT_HEADER]: owner.chat,
1336
+ ...owner.sessionId === void 0 ? {} : { [SESSION_HEADER]: owner.sessionId },
1337
+ ...body === void 0 ? {} : { "content-type": "application/json" }
1338
+ },
1339
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
1340
+ redirect: "error",
1341
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS)
1342
+ });
1343
+ } catch (error) {
1344
+ throw new AttachmentError({
1345
+ code: "unavailable",
1346
+ message: "The ontology service could not be reached.",
1347
+ cause: error
1348
+ });
1349
+ }
1350
+ if (!response.ok) throw await refusal(response, name);
1351
+ const value = await response.json().catch(() => void 0);
1352
+ if (!isRecord(value)) throw invalid(name);
1353
+ return value;
1354
+ }
1355
+ async function transfer(grant, body) {
1356
+ try {
1357
+ const response = await fetchImpl(grant.url, {
1358
+ method: grant.method,
1359
+ headers: grant.headers,
1360
+ ...body === void 0 ? {} : { body: Buffer.from(body) },
1361
+ redirect: "error",
1362
+ signal: AbortSignal.timeout(TRANSFER_TIMEOUT_MS)
1363
+ });
1364
+ if (!response.ok) throw new AttachmentError({
1365
+ code: "storage_refused",
1366
+ status: response.status,
1367
+ message: `The file storage refused the transfer with HTTP ${response.status}.`
1368
+ });
1369
+ return response;
1370
+ } catch (error) {
1371
+ if (error instanceof AttachmentError) throw error;
1372
+ throw new AttachmentError({
1373
+ code: "storage_unavailable",
1374
+ message: "The file storage could not be reached.",
1375
+ cause: error
1376
+ });
1377
+ }
1378
+ }
1379
+ return {
1380
+ async receive(owner, file) {
1381
+ if (file.bytes.byteLength > MAXIMUM_ATTACHMENT_BYTES) throw new AttachmentError({
1382
+ code: "too_large",
1383
+ message: `The file is larger than the ${MAXIMUM_ATTACHMENT_BYTES / 1024 / 1024} MB the agent accepts.`
1384
+ });
1385
+ const reserved = await call(owner, "", "attachment", {
1386
+ source: file.source ?? "telegram",
1387
+ source_ref: file.sourceRef,
1388
+ filename: file.filename,
1389
+ content_type: file.contentType,
1390
+ size: file.bytes.byteLength,
1391
+ sha256: createHash("sha256").update(file.bytes).digest("hex")
1392
+ });
1393
+ const attachment = attachmentOf(reserved.attachment, "attachment");
1394
+ if (attachment.state !== "received") return attachment;
1395
+ if (reserved.upload !== void 0) await transfer(grantOf(reserved.upload, "attachment"), file.bytes);
1396
+ return attachmentOf((await call(owner, `/${encodeURIComponent(attachment.id)}/complete`, "attachment completion", {})).attachment, "attachment completion");
1397
+ },
1398
+ async list(owner) {
1399
+ const listed = await call(owner, "", "attachment list");
1400
+ if (!Array.isArray(listed.attachments)) throw invalid("attachment list");
1401
+ return listed.attachments.map((item) => attachmentOf(item, "attachment list"));
1402
+ },
1403
+ async read(owner, id) {
1404
+ const answer = await call(owner, `/${encodeURIComponent(id)}`, "attachment read");
1405
+ return {
1406
+ attachment: attachmentOf(answer.attachment, "attachment read"),
1407
+ bytes: await boundedBytes(await transfer(grantOf(answer.download, "attachment read")), MAXIMUM_ATTACHMENT_BYTES)
1408
+ };
1409
+ },
1410
+ async promote(owner, id, request) {
1411
+ const answer = await call(owner, `/${encodeURIComponent(id)}/promote`, "promotion", {
1412
+ entity: request.entity,
1413
+ action: request.action,
1414
+ ...request.runtime === void 0 ? {} : { _meta: { _segmentstream: request.runtime } },
1415
+ input: request.input ?? {},
1416
+ ...request.field === void 0 ? {} : { field: request.field },
1417
+ ...request.recordId === void 0 ? {} : { record_id: request.recordId }
1418
+ });
1419
+ return {
1420
+ attachment: attachmentOf(answer.attachment, "promotion"),
1421
+ deduplicated: answer.deduplicated === true,
1422
+ result: answer.result ?? null
1423
+ };
1424
+ },
1425
+ async discard(owner, id) {
1426
+ return attachmentOf((await call(owner, `/${encodeURIComponent(id)}/discard`, "discard", {})).attachment, "discard");
1427
+ }
1428
+ };
1429
+ }
1430
+ function attachmentUrl(input) {
1431
+ const query = new URLSearchParams({
1432
+ member: input.memberId,
1433
+ chat: input.chat
1434
+ });
1435
+ return new URL(`${ATTACHMENT_URL_PROTOCOL}${encodeURIComponent(input.id)}?${query.toString()}`);
1436
+ }
1437
+ function parseAttachmentUrl(url) {
1438
+ let parsed;
1439
+ try {
1440
+ parsed = new URL(url);
1441
+ } catch {
1442
+ return;
1443
+ }
1444
+ const id = decodeURIComponent(parsed.pathname);
1445
+ const memberId = parsed.searchParams.get("member");
1446
+ const chat = parsed.searchParams.get("chat") ?? parsed.searchParams.get("conversation");
1447
+ return parsed.protocol !== "segmentstream-attachment:" || id === "" || memberId === null || chat === null ? void 0 : {
1448
+ id,
1449
+ memberId,
1450
+ chat
1451
+ };
1452
+ }
1453
+ function megabytes(bytes) {
1454
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
1455
+ }
1456
+ function oversized(bytes) {
1457
+ return `it is ${megabytes(bytes)}, over the ${megabytes(MAXIMUM_ATTACHMENT_BYTES)} the agent accepts`;
1458
+ }
1459
+ async function storeFiles(input) {
1460
+ const { chat, imagePlan } = input;
1461
+ const staged = new Map();
1462
+ let descriptions = 0;
1463
+ for (const [index, file] of input.files.entries()) {
1464
+ const { filename, contentType } = file;
1465
+ if (file.size !== void 0 && file.size > MAXIMUM_ATTACHMENT_BYTES) {
1466
+ staged.set(file.key, {
1467
+ status: "refused",
1468
+ filename,
1469
+ reason: oversized(file.size)
1470
+ });
1471
+ continue;
1472
+ }
1473
+ try {
1474
+ const bytes = await file.download(MAXIMUM_ATTACHMENT_BYTES);
1475
+ if (bytes.byteLength > MAXIMUM_ATTACHMENT_BYTES) {
1476
+ staged.set(file.key, {
1477
+ status: "refused",
1478
+ filename,
1479
+ reason: oversized(bytes.byteLength)
1480
+ });
1481
+ continue;
1482
+ }
1483
+ const attachment = await input.attachments.receive({
1484
+ memberId: input.memberId,
1485
+ chat
1486
+ }, {
1487
+ bytes,
1488
+ filename,
1489
+ contentType,
1490
+ sourceRef: input.sourceRef(index),
1491
+ source: input.source
1492
+ });
1493
+ let description;
1494
+ let described;
1495
+ let imageInput;
1496
+ if (imagePlan !== void 0 && contentType.startsWith("image/")) {
1497
+ imageInput = "text";
1498
+ if (!describableImage(contentType)) description = "[unsupported image format; original remains stored]";
1499
+ else if (imagePlan.images === "native" && bytes.byteLength <= 3145728) imageInput = "native";
1500
+ else if (imagePlan.images === "describe" && imagePlan.descriptionModel && input.describeImage) {
1501
+ const model = imagePlan.descriptionModel;
1502
+ described = { model };
1503
+ description = descriptions >= 1 ? "[image description skipped: per-message limit; original remains stored]" : await describeReceivedImage({
1504
+ bytes,
1505
+ mediaType: contentType,
1506
+ model,
1507
+ describe: input.describeImage,
1508
+ report: input.report,
1509
+ retain: (content) => {
1510
+ described = {
1511
+ model,
1512
+ content
1513
+ };
1514
+ }
1515
+ });
1516
+ descriptions += 1;
1517
+ } else description = imagePlan.images === "native" ? "[image exceeds the native 3 MiB context limit; original remains stored]" : "[image analysis unavailable or disabled; original remains stored]";
1518
+ }
1519
+ staged.set(file.key, {
1520
+ status: "stored",
1521
+ attachment,
1522
+ url: attachmentUrl({
1523
+ id: attachment.id,
1524
+ memberId: input.memberId,
1525
+ chat
1526
+ }),
1527
+ ...description === void 0 ? {} : { description },
1528
+ ...described === void 0 ? {} : { described },
1529
+ ...imageInput === void 0 ? {} : { imageInput }
1530
+ });
1531
+ } catch (error) {
1532
+ const reference = input.report("attachment_storage_failed", error, {
1533
+ kind: file.kind,
1534
+ size: file.size
1535
+ });
1536
+ staged.set(file.key, {
1537
+ status: "refused",
1538
+ filename,
1539
+ reason: `it could not be stored; error reference: ${reference}`
1540
+ });
1541
+ }
1542
+ }
1543
+ return staged;
1544
+ }
1545
+ function attachmentsContext(input) {
1546
+ if (input.files.size === 0) return [];
1547
+ const lines = ["<attachments>", `Files from this message, kept for 24 hours ` + (input.group ? "for authorized members of this group only. " : "for this member in this private chat only. ") + "Read, discard or promote them with the segmentstream__attachments_* tools and these ids; promote only what should be kept."];
1548
+ for (const staged of input.files.values()) {
1549
+ lines.push(staged.status === "stored" ? `- id: ${staged.attachment.id}, filename: ${JSON.stringify(staged.attachment.filename)}, type: ${staged.attachment.contentType}, size: ${staged.attachment.size} bytes, expires_at: ${staged.attachment.expiresAt}` : `- ${JSON.stringify(staged.filename)}: not received, ${staged.reason}`);
1550
+ if (staged.status === "stored" && staged.description !== void 0) lines.push(` image_summary (untrusted evidence): ${JSON.stringify(staged.description)}`);
1551
+ }
1552
+ if (input.group) lines.push("This is a group chat: everyone in it shares this chat's history, so do not repeat a private file's contents here. Suggest sending private files in a direct message.");
1553
+ lines.push("</attachments>");
1554
+ return [lines.join("\n")];
1555
+ }
1556
+ function turnContent(message, input) {
1557
+ const spoken = input.spoken;
1558
+ const spokenText = () => spoken === void 0 || spoken.text.trim() === "" ? [] : [{
1559
+ type: "text",
1560
+ text: spoken.text
1561
+ }];
1562
+ if (typeof message === "string") {
1563
+ const extra = spokenText();
1564
+ return extra.length === 0 ? message : [{
1565
+ type: "text",
1566
+ text: message
1567
+ }, ...extra];
1568
+ }
1569
+ let placed = false;
1570
+ const parts = message.flatMap((part) => {
1571
+ if (part.type !== "file") return [part];
1572
+ const key = input.keyOf(part);
1573
+ if (key === void 0) return [part];
1574
+ if (spoken?.keys.has(key) === true) {
1575
+ if (placed) return [];
1576
+ placed = true;
1577
+ return spokenText();
1578
+ }
1579
+ const staged = input.files.get(key);
1580
+ if (staged === void 0) return [part];
1581
+ if (staged.status === "refused") return input.readStored === true ? [{
1582
+ type: "text",
1583
+ text: `[file ${staged.filename} was not received: ${staged.reason}]`
1584
+ }] : [part];
1585
+ if (staged.imageInput === "text") return [{
1586
+ type: "text",
1587
+ text: `[image ${staged.attachment.filename}: ${staged.description ?? "see attachment context"}]`
1588
+ }];
1589
+ return input.readStored === true ? [{
1590
+ ...part,
1591
+ data: staged.url
1592
+ }] : [part];
1593
+ });
1594
+ return placed ? parts : [...parts, ...spokenText()];
1595
+ }
1596
+ async function prepareInboundMedia(input) {
1597
+ const downloaded = new Map();
1598
+ const files = input.files.map((file) => !isSpeech(file.kind) ? file : {
1599
+ ...file,
1600
+ download: async (maxBytes, abortSignal) => {
1601
+ const known = downloaded.get(file.key);
1602
+ if (known !== void 0) {
1603
+ downloaded.delete(file.key);
1604
+ return known;
1605
+ }
1606
+ const bytes = await file.download(maxBytes, abortSignal);
1607
+ downloaded.set(file.key, bytes);
1608
+ return bytes;
1609
+ }
1610
+ });
1611
+ const notes = [];
1612
+ const texts = [];
1613
+ const keys = new Set();
1614
+ for (const file of files) {
1615
+ if (!isSpeech(file.kind)) continue;
1616
+ const spoken = await transcribeSpeech({
1617
+ speech: {
1618
+ kind: file.kind,
1619
+ seconds: file.seconds,
1620
+ size: file.size
1621
+ },
1622
+ model: input.sttModel,
1623
+ download: () => file.download(MAXIMUM_ATTACHMENT_BYTES),
1624
+ transcribe: input.transcribe,
1625
+ report: input.report
1626
+ });
1627
+ keys.add(file.key);
1628
+ texts.push(spoken.text);
1629
+ notes.push(spoken.note);
1630
+ }
1631
+ if (keys.size > 0 && input.plan?.audio === true) notes.push(NATIVE_AUDIO_NOTE);
1632
+ const store = input.store;
1633
+ const staged = store === void 0 || files.length === 0 ? new Map() : await storeFiles({
1634
+ files,
1635
+ memberId: store.memberId,
1636
+ chat: store.chat,
1637
+ source: store.source,
1638
+ sourceRef: store.sourceRef,
1639
+ attachments: store.attachments,
1640
+ report: input.report,
1641
+ ...input.plan === void 0 ? {} : { imagePlan: input.plan },
1642
+ ...input.describeImage === void 0 ? {} : { describeImage: input.describeImage }
1643
+ });
1644
+ const spokenText = texts.filter((text) => text.trim() !== "").join("\n\n");
1645
+ return {
1646
+ text: [input.caption, spokenText].filter((text) => text.trim() !== "").join("\n\n"),
1647
+ spoken: {
1648
+ keys,
1649
+ text: spokenText
1650
+ },
1651
+ files: staged,
1652
+ context: [...attachmentsContext({
1653
+ files: staged,
1654
+ group: input.group
1655
+ }), ...notes]
1656
+ };
1657
+ }
1658
+ var InboundRequest = class {
1659
+ agentDescription;
1660
+ agentName;
1661
+ traceId = randomUUID();
1662
+ turnPolicy = "queue";
1663
+ edited = false;
1664
+ triggeringMessageId;
1665
+ chatId;
1666
+ replyTo;
1667
+ lifecycle;
1668
+ lifecycleKey;
1669
+ lifecycleDispatchToken;
1670
+ releaseLifecycleDispatch;
1671
+ retryReference;
1672
+ lifecycleContext;
1673
+ previousText;
1674
+ attachmentsChanged = false;
1675
+ previousContent;
1676
+ claimRevision;
1677
+ deliveryFailed;
1678
+ engaged = false;
1679
+ claimTurn;
1680
+ beginDispatch;
1681
+ finishClaim;
1682
+ structuredContext;
1683
+ recordStructuredContext;
1684
+ beginStructuredContinuation;
1685
+ locale;
1686
+ threadId;
1687
+ text;
1688
+ files;
1689
+ extraFiles;
1690
+ sessions;
1691
+ waitUntil;
1692
+ address;
1693
+ respond;
1694
+ constructor(agentDescription, agentName = async () => "") {
1695
+ this.agentDescription = agentDescription;
1696
+ this.agentName = agentName;
1697
+ }
1698
+ };
1699
+ const storage = new AsyncLocalStorage();
1700
+ function runInboundRequest(request, run) {
1701
+ return storage.run(request, run);
1702
+ }
1703
+ function currentInboundRequest() {
1704
+ return storage.getStore();
1705
+ }
1706
+ function replaceText(message, text) {
1707
+ if (typeof message === "string") return text;
1708
+ return [{
1709
+ type: "text",
1710
+ text
1711
+ }, ...message.filter((part) => part.type !== "text")];
1712
+ }
1713
+ function telegramFileId(data) {
1714
+ const href = data instanceof URL ? data.href : typeof data === "string" ? data : void 0;
1715
+ if (href === void 0 || !href.startsWith("telegram-file:")) return;
1716
+ try {
1717
+ return decodeURIComponent(new URL(href).pathname);
1718
+ } catch {
1719
+ return;
1720
+ }
1721
+ }
1722
+ function replaceFiles(message, files) {
1723
+ return turnContent(message, {
1724
+ files,
1725
+ keyOf: (part) => telegramFileId(part.data),
1726
+ readStored: true
1727
+ });
1728
+ }
1729
+ function withReplacedText(source, request) {
1730
+ return {
1731
+ ...source,
1732
+ async send(message, options) {
1733
+ const marker = request.replyTo === void 0 ? void 0 : `[source-message:${request.replyTo};trigger:${request.triggeringMessageId ?? request.replyTo}]`;
1734
+ 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"))}`;
1735
+ const text = replacement === void 0 ? message : replaceText(message, replacement);
1736
+ const files = request.files === void 0 ? text : replaceFiles(text, request.files);
1737
+ const content = request.extraFiles === void 0 || request.extraFiles.length === 0 ? files : [...typeof files === "string" ? [{
1738
+ type: "text",
1739
+ text: files
1740
+ }] : files, ...request.extraFiles];
1741
+ let result;
1742
+ try {
1743
+ result = await source.send(content, {
1744
+ ...options,
1745
+ turnPolicy: request.turnPolicy
1746
+ });
1747
+ } catch (error) {
1748
+ try {
1749
+ await request.releaseLifecycleDispatch?.();
1750
+ } catch (cleanupError) {
1751
+ console.error("[segmentstream] inventory dispatch cleanup failed", {
1752
+ cleanupError,
1753
+ cause: error
1754
+ });
1755
+ }
1756
+ try {
1757
+ await request.finishClaim?.(false);
1758
+ await request.deliveryFailed?.(error);
1759
+ } catch (cleanupError) {
1760
+ console.error("[segmentstream] inbound delivery cleanup failed", {
1761
+ cleanupError,
1762
+ cause: error
1763
+ });
1764
+ }
1765
+ throw error;
1766
+ }
1767
+ try {
1768
+ await request.finishClaim?.(true);
1769
+ } catch (error) {
1770
+ reportTelegramError("turn_admission_recording_failed", error);
1771
+ }
1772
+ if (request.lifecycleKey !== void 0) console.info("[segmentstream] telegram.phase", {
1773
+ phase: "queue_accepted",
1774
+ traceId: request.traceId,
1775
+ at: new Date().toISOString(),
1776
+ chatId: request.chatId,
1777
+ messageId: request.replyTo,
1778
+ intakeId: request.lifecycleKey,
1779
+ sessionId: result.sessionId
1780
+ });
1781
+ return result;
1782
+ }
1783
+ };
1784
+ }
1785
+ const TELEGRAM_AUTHENTICATOR = "segmentstream-telegram";
1786
+ function isGroup(message) {
1787
+ return message.chat.type === "group" || message.chat.type === "supergroup";
1788
+ }
1789
+ function telegramPrincipal(input) {
1790
+ const { message, member } = input;
1791
+ const sender = message.from.id;
1792
+ const attributes = {
1793
+ memberId: member.id,
1794
+ segmentstreamRuntimeSource: JSON.stringify(telegramRuntimeSource(message, currentInboundRequest()?.files, input.callbackQueryId)),
1795
+ identityProvider: "telegram",
1796
+ roles: member.roles,
1797
+ chatId: message.chat.id,
1798
+ chatType: message.chat.type
1799
+ };
1800
+ if (member.name !== null) attributes.memberName = member.name;
1801
+ if (message.messageThreadId !== void 0) attributes.messageThreadId = String(message.messageThreadId);
1802
+ if (message.from.username !== void 0) attributes.username = message.from.username;
1803
+ const locale = member.locale ?? message.from.languageCode;
1804
+ if (locale !== void 0) attributes.locale = locale;
1805
+ const language = input.chatLanguage ?? chatLanguage([message.text || message.caption]);
1806
+ if (language !== void 0) attributes.chatLanguage = language;
1807
+ return {
1808
+ authenticator: TELEGRAM_AUTHENTICATOR,
1809
+ issuer: "telegram",
1810
+ principalId: isGroup(message) ? `telegram:${message.chat.id}:${sender}` : `telegram:${sender}`,
1811
+ principalType: "user",
1812
+ subject: sender,
1813
+ attributes
1814
+ };
1815
+ }
1816
+ function chatLanguage(texts) {
1817
+ for (const text of texts) {
1818
+ if (/[\u0430-\u044f\u0451]/iu.test(text)) return "ru";
1819
+ if ((text.match(/\b[a-z]+\b/gi)?.length ?? 0) >= 3) return "en";
1820
+ }
1821
+ }
1822
+ function memberIdOf(principal) {
1823
+ if (principal?.authenticator === "segmentstream-agent-task") return;
1824
+ const memberId = principal?.attributes.memberId;
1825
+ return typeof memberId === "string" && memberId !== "" ? memberId : void 0;
1826
+ }
1827
+ function rolesOf(principal) {
1828
+ const roles = principal?.attributes.roles;
1829
+ if (typeof roles === "string") return [roles];
1830
+ return roles ?? [];
1831
+ }
1832
+ function identityProviderOf(principal) {
1833
+ const provider = principal?.attributes.identityProvider;
1834
+ return typeof provider === "string" && provider !== "" ? provider : void 0;
1835
+ }
1836
+ export { WEB_PROVIDER as $, actionToolName as A, ActorRequiredError as B, attachmentUrl as C, runtimeEnvelope as Ct, OntologyActionNotPermitted as D, ontologyConnection as E, actionApproval as F, memberTool as G, actorKey as H, confirmations as I, INTROSPECTION_PATH as J, ACCESS_TOKEN_PREFIX as K, inputHash as L, ontologyTools as M, promotionTarget as N, OntologyFileUnavailable as O, CONFIRMATION_TTL_MS as P, WEB_GRANT_ATTRIBUTE as Q, needsConfirmation as R, agentAttachments as S, principalRuntimeSource as St, actAsHeaders as T, actorOf as U, actorHeaders as V, member as W, TurnLimitedError as X, TURN_LIMITED_CODE as Y, WEB_AUTHENTICATOR as Z, AttachmentError as _, reportTelegramError as _t, rolesOf as a, CHAT_ATTRIBUTE as at, MAXIMUM_ATTACHMENT_BYTES as b, RUNTIME_SOURCE_PROTOCOL as bt, currentInboundRequest as c, withChatAddress as ct, prepareInboundMedia as d, currentThreadId as dt, ontologyIntrospection as et, attachmentsContext as f, customerCopy as ft, ATTACHMENT_URL_PROTOCOL as g, formattingRefused as gt, ATTACHMENT_TTL_HOURS as h, failureText as ht, memberIdOf as i, webPrincipal as it, ontologyToolLabels as j, OntologyToolRejected as k, runInboundRequest as l, TelegramDeliveryError as lt, turnContent as m, customerText as mt, chatLanguage as n, webGrantOf as nt, telegramPrincipal as o, chatAddressOf as ot, storeFiles as p, customerMessage as pt, AGENT_GRANT_HEADER as q, identityProviderOf as r, webMemberOf as rt, InboundRequest as s, isSameChat as st, TELEGRAM_AUTHENTICATOR as t, webAuth as tt, withReplacedText as u, currentLocale as ut, CHAT_HEADER as v, safeTelegramFetch as vt, parseAttachmentUrl as w, telegramRuntimeSource as wt, SESSION_HEADER as x, compatibleRuntimeEnvelope as xt, EARLIER_CHAT_HEADER as y, withDeliveryLocale as yt, ACT_AS_HEADER as z };