@segmentstream/agent 0.103.1 → 0.105.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/README.md +13 -2
- package/dist/_chunks/{build-metadata-ByWwCQd1.mjs → build-metadata-DhAF_QGj.mjs} +1 -1
- package/dist/_chunks/{silent-CWcAjHwt.mjs → silent-DwObe1UV.mjs} +18 -3
- package/dist/extension/lib/adapter-view.d.ts +15 -0
- package/dist/extension/lib/adapter-view.mjs +32 -0
- package/dist/extension/lib/attachments-dispatch.d.ts +8 -0
- package/dist/extension/lib/attachments-dispatch.mjs +17 -10
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/chat-recorder.d.ts +2 -0
- package/dist/extension/lib/chat-recorder.mjs +65 -20
- package/dist/extension/lib/connection-proxy.d.ts +6 -0
- package/dist/extension/lib/connection-proxy.mjs +32 -1
- package/dist/extension/lib/deliver-route.d.ts +27 -0
- package/dist/extension/lib/deliver-route.mjs +35 -0
- package/dist/extension/lib/email/attachments-send.d.ts +2 -0
- package/dist/extension/lib/email/attachments-send.mjs +1 -1
- package/dist/extension/lib/email/channel.mjs +34 -47
- package/dist/extension/lib/reply-part.d.ts +11 -0
- package/dist/extension/lib/reply-part.mjs +17 -0
- package/dist/extension/lib/reply.d.ts +115 -0
- package/dist/extension/lib/reply.mjs +107 -0
- package/dist/extension/lib/review/files.d.ts +3 -2
- package/dist/extension/lib/review/files.mjs +1 -1
- package/dist/extension/lib/review/hold.d.ts +7 -0
- package/dist/extension/lib/review/hold.mjs +3 -3
- package/dist/extension/lib/review/reply.d.ts +24 -0
- package/dist/extension/lib/review/reply.mjs +18 -6
- package/dist/extension/lib/review/revision.mjs +3 -1
- package/dist/extension/lib/sent-files.d.ts +9 -0
- package/dist/extension/lib/sent-files.mjs +15 -1
- package/dist/extension/lib/slack/adapter.mjs +2 -1
- package/dist/extension/lib/telegram/adapter.d.ts +3 -1
- package/dist/extension/lib/telegram/adapter.mjs +64 -50
- package/dist/extension/lib/telegram/deliver.d.ts +77 -0
- package/dist/extension/lib/telegram/deliver.mjs +334 -0
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/lib/telegram/routing-context.mjs +1 -1
- package/dist/extension/lib/telegram/silent.d.ts +3 -1
- package/dist/extension/lib/telegram/silent.mjs +1 -1
- package/dist/extension/lib/whatsapp/adapter.mjs +2 -1
- package/dist/extension/lib/workspace-channel/channel.d.ts +4 -1
- package/dist/extension/lib/workspace-channel/channel.mjs +14 -5
- package/dist/extension/tools/attachments_send.mjs +1 -1
- package/dist/extension/tools/reply.d.ts +19 -0
- package/dist/extension/tools/reply.mjs +180 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.mjs +2 -1
- package/package.json +4 -3
|
@@ -8,6 +8,7 @@ import { redactDiagnostic } from "../diagnostics.mjs";
|
|
|
8
8
|
import { AgentIdentityError, refusal } from "../identities.mjs";
|
|
9
9
|
import { readChat } from "./judge.mjs";
|
|
10
10
|
import { postDraftRoute } from "./routes.mjs";
|
|
11
|
+
import { toolReplyCallOf } from "../reply-part.mjs";
|
|
11
12
|
import { ontologyDeploymentHeaders } from "../environment.mjs";
|
|
12
13
|
import { EMAIL_RECIPIENTS_LIMIT, isEmailAddress } from "@segmentstream/ontology/email";
|
|
13
14
|
const REVISION_AUTHENTICATOR = "segmentstream-review-revision";
|
|
@@ -259,12 +260,13 @@ function shown(value) {
|
|
|
259
260
|
}
|
|
260
261
|
async function turnLookups(stream, sessionId, partId) {
|
|
261
262
|
const turns = new Map();
|
|
263
|
+
const replyCall = toolReplyCallOf(partId);
|
|
262
264
|
let turnId;
|
|
263
265
|
for await (const event of stream(sessionId)) {
|
|
264
266
|
const turn = event.scope?.turnId;
|
|
265
267
|
if (turn === void 0) continue;
|
|
266
268
|
const data = event.data;
|
|
267
|
-
if (turn === partId || event.type === "content.completed" && data.partId === partId &&
|
|
269
|
+
if (turn === partId || turnId === void 0 && (event.type === "content.completed" && data.partId === partId || replyCall !== void 0 && event.type === "call.requested" && data.callId === replyCall)) turnId = turn;
|
|
268
270
|
const calls = turns.get(turn) ?? new Map();
|
|
269
271
|
turns.set(turn, calls);
|
|
270
272
|
const callId = typeof data.callId === "string" ? data.callId : void 0;
|
|
@@ -71,6 +71,15 @@ export declare function storedFileGrant(input: StoredFileRead): Promise<StoredFi
|
|
|
71
71
|
export declare function storedChannelFile(grant: StoredFileGrant, input: StoredFileRead): ChannelStoredFile & {
|
|
72
72
|
readonly link: () => Promise<StoredFileGrant>;
|
|
73
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* One file the ontology hands a channel's deliver route, read by its link to the workspace's file
|
|
76
|
+
* storage, which the ontology granted just before it handed the message over. Its bytes must be
|
|
77
|
+
* the size the delivery names: the revision the ontology checked.
|
|
78
|
+
*/
|
|
79
|
+
export declare function readDeliveredFile(file: {
|
|
80
|
+
readonly url: string;
|
|
81
|
+
readonly size: number;
|
|
82
|
+
}, fetchImpl: typeof fetch): Promise<Uint8Array>;
|
|
74
83
|
/** What a stored file's download needs once its grant is read. */
|
|
75
84
|
interface StoredFileDownload {
|
|
76
85
|
readonly fetch: typeof fetch;
|
|
@@ -145,6 +145,20 @@ function storedChannelFile(grant, input) {
|
|
|
145
145
|
}
|
|
146
146
|
};
|
|
147
147
|
}
|
|
148
|
+
const DELIVERED_FILE_TIMEOUT_MS = 3e4;
|
|
149
|
+
async function readDeliveredFile(file, fetchImpl) {
|
|
150
|
+
const response = await fetchImpl(file.url, {
|
|
151
|
+
redirect: "error",
|
|
152
|
+
signal: AbortSignal.timeout(DELIVERED_FILE_TIMEOUT_MS)
|
|
153
|
+
});
|
|
154
|
+
if (!response.ok) {
|
|
155
|
+
await response.body?.cancel();
|
|
156
|
+
throw new Error(`The file storage answered with status ${response.status}.`);
|
|
157
|
+
}
|
|
158
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
159
|
+
if (bytes.byteLength !== file.size) throw new Error(`The file read has ${bytes.byteLength} bytes, not the ${file.size} named.`);
|
|
160
|
+
return bytes;
|
|
161
|
+
}
|
|
148
162
|
async function fetchStoredFile(input) {
|
|
149
163
|
return downloadStoredFile(await storedFileGrant(input), input);
|
|
150
164
|
}
|
|
@@ -182,4 +196,4 @@ async function downloadStoredFile(grant, input) {
|
|
|
182
196
|
});
|
|
183
197
|
}
|
|
184
198
|
}
|
|
185
|
-
export { StoredFileError, boundedDownload, downloadStoredFile, fetchStoredFile, storedChannelFile, storedFileGrant };
|
|
199
|
+
export { StoredFileError, boundedDownload, downloadStoredFile, fetchStoredFile, readDeliveredFile, storedChannelFile, storedFileGrant };
|
|
@@ -26,6 +26,7 @@ import { handleWorkspaceCallback } from "./callbacks.mjs";
|
|
|
26
26
|
import { workspaceTriage } from "../triage.mjs";
|
|
27
27
|
import { pairingNotice } from "./pairing.mjs";
|
|
28
28
|
import { recordThreadHistory } from "./thread-history.mjs";
|
|
29
|
+
import { withToolReplies } from "../reply.mjs";
|
|
29
30
|
import { channelReview, withReviewedReplies } from "../review/reply.mjs";
|
|
30
31
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
31
32
|
import { r as chatArchive } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
|
|
@@ -459,7 +460,7 @@ function segmentstreamSlack(options) {
|
|
|
459
460
|
token,
|
|
460
461
|
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
461
462
|
});
|
|
462
|
-
const replying = reviewed === void 0 ? channel : withReviewedReplies(channel, () => reviewed.review, () => reviewed.archive);
|
|
463
|
+
const replying = withToolReplies(reviewed === void 0 ? channel : withReviewedReplies(channel, () => reviewed.review, () => reviewed.archive));
|
|
463
464
|
return {
|
|
464
465
|
...withSessionChannels("slack", replying),
|
|
465
466
|
routes: withNamedRoutes("slack", replying.routes.flatMap((route) => route.transport === "websocket" ? [] : [gatedRoute(route, settings, environment, observe, delivered)]), (name) => options.settings(name) !== null)
|
|
@@ -59,8 +59,10 @@ export interface TelegramAdapterOptions {
|
|
|
59
59
|
readonly describeImage?: ImageDescriber;
|
|
60
60
|
readonly describeAttachment?: AttachmentDescriber;
|
|
61
61
|
readonly modelCapabilities?: CapabilityLookup;
|
|
62
|
-
/** Verifies callers of the health
|
|
62
|
+
/** Verifies callers of the health and deliver routes; tests pass one on a local key set. */
|
|
63
63
|
readonly verify?: RuntimeTokenVerifier;
|
|
64
|
+
/** Waits out Telegram's flood control on the deliver route; tests pass one that does not wait. */
|
|
65
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
64
66
|
/** Reads session events for routing and interactions; tests pass a fake. */
|
|
65
67
|
readonly history?: HistoryReader;
|
|
66
68
|
/** The attachment store; tests pass a fake. */
|
|
@@ -12,7 +12,7 @@ import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
|
|
|
12
12
|
import { handleWorkspaceCallback } from "./callbacks.mjs";
|
|
13
13
|
import { workspaceTriage } from "../triage.mjs";
|
|
14
14
|
import { telegramText, withTelegramTexts } from "./texts.mjs";
|
|
15
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
15
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-DhAF_QGj.mjs";
|
|
16
16
|
import { attachmentLifecycle } from "./lifecycle.mjs";
|
|
17
17
|
import { manifestOf } from "../../config.mjs";
|
|
18
18
|
import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
|
|
@@ -26,8 +26,8 @@ import { a as captureTelegramFetch, h as telegramChatCapture, i as captureRouteD
|
|
|
26
26
|
import { runtimeTokenVerifier } from "../runtime-identity.mjs";
|
|
27
27
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
28
28
|
import { botIdentityCache, proxiedBotRequest, runtimeBotIdentity } from "./bot.mjs";
|
|
29
|
-
import { isWorkspaceCallback } from "../workspace-action.mjs";
|
|
30
29
|
import { handleConfirmationCallback, telegramConfirmationEvents } from "./confirmations.mjs";
|
|
30
|
+
import { isWorkspaceCallback } from "../workspace-action.mjs";
|
|
31
31
|
import { confirmationLocale } from "./confirmation-text.mjs";
|
|
32
32
|
import { telegramAppLinkContext } from "./app-links.mjs";
|
|
33
33
|
import { gatewayImageDescriber } from "../inbound-media/images.mjs";
|
|
@@ -39,9 +39,11 @@ import { handleInboundMessage } from "./inbound.mjs";
|
|
|
39
39
|
import { recoverableSessions } from "./session-recovery.mjs";
|
|
40
40
|
import { TELEGRAM_PLACEHOLDER_TOKEN, TELEGRAM_PROXY_ORIGIN, telegramProxyFetch } from "./proxy-fetch.mjs";
|
|
41
41
|
import { healthRoute } from "./health.mjs";
|
|
42
|
+
import { telegramDeliverRoute } from "./deliver.mjs";
|
|
42
43
|
import { decisionRouter } from "../group-routing/router.mjs";
|
|
43
44
|
import { scopedAddress, senderAddress } from "./sessions.mjs";
|
|
44
|
-
import { a as isNoReplyCall, i as interimTexts, s as replyDelivery } from "../../../_chunks/silent-
|
|
45
|
+
import { a as isNoReplyCall, i as interimTexts, s as replyDelivery } from "../../../_chunks/silent-DwObe1UV.mjs";
|
|
46
|
+
import { supersededByToolReply, toolReplyPart } from "../reply.mjs";
|
|
45
47
|
import { channelReview, holdFilesAfterTurn } from "../review/reply.mjs";
|
|
46
48
|
import { telegramSendScope } from "./send-queue.mjs";
|
|
47
49
|
import { telegramFailureEvents } from "./turn-errors.mjs";
|
|
@@ -439,59 +441,63 @@ function segmentstreamTelegram(options) {
|
|
|
439
441
|
await approvalEvents["interaction.settled"]?.(event, ctx);
|
|
440
442
|
},
|
|
441
443
|
async "turn.settled"(event, ctx) {
|
|
444
|
+
const part = event.data.outcome === "completed" ? toolReplyPart(ctx.view, event.data.turnId) : void 0;
|
|
445
|
+
if (part !== void 0) await completed(part, ctx);
|
|
442
446
|
await failureEvents["turn.settled"]?.(event, ctx);
|
|
443
447
|
await approvalEvents["turn.settled"]?.(event, ctx);
|
|
444
448
|
await holdFilesAfterTurn(review, event, ctx);
|
|
445
449
|
},
|
|
446
|
-
|
|
447
|
-
const channel = context.channel;
|
|
448
|
-
const message = typeof event.data.value === "string" ? event.data.value : "";
|
|
449
|
-
const principal = context.session.auth.current;
|
|
450
|
-
const taskId = principal?.attributes.taskId;
|
|
451
|
-
const configuration = settings().attachmentLifecycle;
|
|
452
|
-
if (event.data.kind === "text" && event.data.phase === "reply" && !event.data.interrupted && message && configuration && principal && typeof taskId === "string") try {
|
|
453
|
-
const memberId = principal.attributes.memberId;
|
|
454
|
-
if (typeof memberId !== "string") throw new Error("A current member is required for completion.");
|
|
455
|
-
const result = await attachmentLifecycle({
|
|
456
|
-
configuration,
|
|
457
|
-
principal,
|
|
458
|
-
memberId,
|
|
459
|
-
environment,
|
|
460
|
-
token,
|
|
461
|
-
...options.fetch ? { fetch: options.fetch } : {},
|
|
462
|
-
message: {
|
|
463
|
-
chat: { id: channel.telegram.chatId },
|
|
464
|
-
messageId: String(principal.attributes.triggeringMessageId ?? principal.attributes.replyToMessageId),
|
|
465
|
-
messageThreadId: channel.telegram.messageThreadId,
|
|
466
|
-
from: { id: principal.subject ?? "" }
|
|
467
|
-
}
|
|
468
|
-
})("completed", {
|
|
469
|
-
key: taskId,
|
|
470
|
-
...configuration.contextVersion === 2 ? { reply: message } : {},
|
|
471
|
-
...typeof principal.attributes.attachmentDispatchToken === "string" ? { dispatch_token: principal.attributes.attachmentDispatchToken } : {}
|
|
472
|
-
});
|
|
473
|
-
if (result.message !== void 0 || result.complete === false) event = {
|
|
474
|
-
...event,
|
|
475
|
-
data: {
|
|
476
|
-
...event.data,
|
|
477
|
-
value: result.message ?? ""
|
|
478
|
-
}
|
|
479
|
-
};
|
|
480
|
-
} catch (error) {
|
|
481
|
-
const reference = reportTelegramError("intake_completion_failed", error, {
|
|
482
|
-
sessionId: context.session.id,
|
|
483
|
-
taskId
|
|
484
|
-
});
|
|
485
|
-
await channel.telegram.post(failureText(reference));
|
|
486
|
-
return;
|
|
487
|
-
}
|
|
488
|
-
await replyDelivery(() => telegramSendScope(environment, settings().connection), {
|
|
489
|
-
enabled: () => settings().interimMessages === true,
|
|
490
|
-
delivered: interimDelivered
|
|
491
|
-
}, review, () => settings().identifiers ?? "block")(event, context);
|
|
492
|
-
}
|
|
450
|
+
"content.completed": (event, context) => completed(event, context)
|
|
493
451
|
}
|
|
494
452
|
});
|
|
453
|
+
async function completed(...[event, context]) {
|
|
454
|
+
const channel = context.channel;
|
|
455
|
+
const message = typeof event.data.value === "string" ? event.data.value : "";
|
|
456
|
+
const principal = context.session.auth.current;
|
|
457
|
+
const taskId = principal?.attributes.taskId;
|
|
458
|
+
const configuration = settings().attachmentLifecycle;
|
|
459
|
+
if (supersededByToolReply(event, context)) return;
|
|
460
|
+
if (event.data.kind === "text" && event.data.phase === "reply" && !event.data.interrupted && message && configuration && principal && typeof taskId === "string") try {
|
|
461
|
+
const memberId = principal.attributes.memberId;
|
|
462
|
+
if (typeof memberId !== "string") throw new Error("A current member is required for completion.");
|
|
463
|
+
const result = await attachmentLifecycle({
|
|
464
|
+
configuration,
|
|
465
|
+
principal,
|
|
466
|
+
memberId,
|
|
467
|
+
environment,
|
|
468
|
+
token,
|
|
469
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
470
|
+
message: {
|
|
471
|
+
chat: { id: channel.telegram.chatId },
|
|
472
|
+
messageId: String(principal.attributes.triggeringMessageId ?? principal.attributes.replyToMessageId),
|
|
473
|
+
messageThreadId: channel.telegram.messageThreadId,
|
|
474
|
+
from: { id: principal.subject ?? "" }
|
|
475
|
+
}
|
|
476
|
+
})("completed", {
|
|
477
|
+
key: taskId,
|
|
478
|
+
...configuration.contextVersion === 2 ? { reply: message } : {},
|
|
479
|
+
...typeof principal.attributes.attachmentDispatchToken === "string" ? { dispatch_token: principal.attributes.attachmentDispatchToken } : {}
|
|
480
|
+
});
|
|
481
|
+
if (result.message !== void 0 || result.complete === false) event = {
|
|
482
|
+
...event,
|
|
483
|
+
data: {
|
|
484
|
+
...event.data,
|
|
485
|
+
value: result.message ?? ""
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
} catch (error) {
|
|
489
|
+
const reference = reportTelegramError("intake_completion_failed", error, {
|
|
490
|
+
sessionId: context.session.id,
|
|
491
|
+
taskId
|
|
492
|
+
});
|
|
493
|
+
await channel.telegram.post(failureText(reference));
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
await replyDelivery(() => telegramSendScope(environment, settings().connection), {
|
|
497
|
+
enabled: () => settings().interimMessages === true,
|
|
498
|
+
delivered: interimDelivered
|
|
499
|
+
}, review, () => settings().identifiers ?? "block")(event, context);
|
|
500
|
+
}
|
|
495
501
|
const adapter = channel.adapter;
|
|
496
502
|
const fetchTelegramFile = adapter?.fetchFile;
|
|
497
503
|
async function fetchFile(url, context) {
|
|
@@ -557,6 +563,14 @@ function segmentstreamTelegram(options) {
|
|
|
557
563
|
confirmationMode: options.confirmationMode?.() ?? null,
|
|
558
564
|
attachmentLifecycle: channelSettings()?.attachmentLifecycle !== void 0
|
|
559
565
|
})
|
|
566
|
+
}),
|
|
567
|
+
telegramDeliverRoute({
|
|
568
|
+
settings: options.settings,
|
|
569
|
+
proxy,
|
|
570
|
+
environment,
|
|
571
|
+
verify: () => verify ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment)),
|
|
572
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch },
|
|
573
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep }
|
|
560
574
|
})
|
|
561
575
|
]
|
|
562
576
|
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type HttpRouteDefinition } from "eve/channels";
|
|
2
|
+
import type { TelegramChannelState } from "eve/channels/telegram";
|
|
3
|
+
import { type ChannelDeliveredFile, type ChannelFile, type ChannelRequest, type ChannelStoredFile, type TelegramDeliverPart } from "@segmentstream/ontology/telegram";
|
|
4
|
+
import type { TelegramSettings } from "../../config.js";
|
|
5
|
+
import { type ConnectionProxy } from "../connection-proxy.js";
|
|
6
|
+
import type { Environment } from "../environment.js";
|
|
7
|
+
import type { RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
8
|
+
/**
|
|
9
|
+
* Where the ontology hands the Telegram channel `:channel` a message to send (`telegramDeliverRoute`
|
|
10
|
+
* of the ontology SDK): a draft a member approved, a reply its review let go, a member's or a
|
|
11
|
+
* service's post. The ontology decided it and rendered it, its exact text with its attribution,
|
|
12
|
+
* links and previews; the channel sends what it was given through its bot, as the ontology's own
|
|
13
|
+
* sender did, and says what reached the person.
|
|
14
|
+
*
|
|
15
|
+
* - The text goes in MarkdownV2, and once more without formatting only when Telegram refuses the
|
|
16
|
+
* formatting: that refusal proves nothing was sent. Nothing else is sent twice, and no text is
|
|
17
|
+
* checked or rewritten here: the person gets the message as it was approved.
|
|
18
|
+
* - The parts go in order, in the chat's send queue, which the channel's own replies share, so
|
|
19
|
+
* none of theirs lands between them. Nothing follows a part that did not certainly reach the
|
|
20
|
+
* person. The files are read by their links before the queue is taken; no lock is held.
|
|
21
|
+
* - Telegram's flood control (`429`), which sent nothing, is waited out and the part tried again,
|
|
22
|
+
* up to {@link DELIVER_ATTEMPTS} times within the ontology's wait. No adapter retries.
|
|
23
|
+
* - A failure is classified where it happens: Telegram's refusal or SegmentStream's before the
|
|
24
|
+
* call sent nothing, anything else may have. The original errors, Telegram's answers included,
|
|
25
|
+
* go to the deployment's logs, credentials redacted, under the reference the answer names.
|
|
26
|
+
*/
|
|
27
|
+
export declare const TELEGRAM_DELIVER_ROUTE = "/eve/segmentstream/v1/telegram/:channel/deliver";
|
|
28
|
+
/** A message the deliver route sends, as its request names it and its files are read. */
|
|
29
|
+
export interface TelegramDelivery {
|
|
30
|
+
readonly chatId: string;
|
|
31
|
+
readonly threadId: string | null;
|
|
32
|
+
readonly replyTo: string | null;
|
|
33
|
+
readonly parts: ReadonlyArray<TelegramDeliverPart>;
|
|
34
|
+
readonly replyMarkup?: Readonly<Record<string, unknown>>;
|
|
35
|
+
readonly files: ReadonlyArray<ChannelFile | ChannelStoredFile>;
|
|
36
|
+
}
|
|
37
|
+
/** Why nothing of a delivery was sent. */
|
|
38
|
+
export type TelegramDeliveryError = "provider_refused" | "thread_unavailable" | "connection_refused" | "file_unavailable" | "file_too_large";
|
|
39
|
+
/** What became of a delivery, as Telegram's answers prove it. */
|
|
40
|
+
export interface TelegramDeliveryOutcome {
|
|
41
|
+
/** `sent` when every message was; `failed` when none reached the person; else `uncertain`. */
|
|
42
|
+
readonly status: "sent" | "uncertain" | "failed";
|
|
43
|
+
/** The first message that reached the person. */
|
|
44
|
+
readonly messageId: string | null;
|
|
45
|
+
/** Its link, for a text alone in a group Telegram links to. */
|
|
46
|
+
readonly url: string | null;
|
|
47
|
+
/** Why nothing was sent, for a `failed` delivery. */
|
|
48
|
+
readonly error?: TelegramDeliveryError;
|
|
49
|
+
readonly refusal?: "recipient_unreachable";
|
|
50
|
+
/** What became of each file, by its index, for a delivery with files. */
|
|
51
|
+
readonly files?: ReadonlyArray<ChannelDeliveredFile>;
|
|
52
|
+
/** Each original failure: Telegram's answer, or the connection's error. */
|
|
53
|
+
readonly causes: ReadonlyArray<unknown>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Sends a delivery in order: its text messages, each with the chat's topic and the message it
|
|
57
|
+
* answers, the buttons under the last; then its files. A single text that fits a caption goes as
|
|
58
|
+
* the caption of files sent as one message: one file, or an album of one type. Nothing follows a
|
|
59
|
+
* text that did not certainly reach the person.
|
|
60
|
+
*/
|
|
61
|
+
export declare function deliverTelegram(delivery: TelegramDelivery, options: {
|
|
62
|
+
readonly request: ChannelRequest;
|
|
63
|
+
readonly sleep: (ms: number) => Promise<void>;
|
|
64
|
+
}): Promise<TelegramDeliveryOutcome>;
|
|
65
|
+
/** The Telegram channel's deliver route; see {@link TELEGRAM_DELIVER_ROUTE}. */
|
|
66
|
+
export declare function telegramDeliverRoute(options: {
|
|
67
|
+
/** The Telegram channel `name` the mount declares, or `null`. */
|
|
68
|
+
readonly settings: (name: string) => TelegramSettings | null;
|
|
69
|
+
/** The connection proxy of the channel the current request runs for. */
|
|
70
|
+
readonly proxy: () => ConnectionProxy;
|
|
71
|
+
readonly environment: Environment;
|
|
72
|
+
readonly verify: () => RuntimeTokenVerifier;
|
|
73
|
+
/** Reads the files by their links; `fetch` by default. */
|
|
74
|
+
readonly fetch?: typeof fetch;
|
|
75
|
+
/** Waits out flood control; tests pass one that does not wait. */
|
|
76
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
77
|
+
}): HttpRouteDefinition<TelegramChannelState>;
|
|
@@ -0,0 +1,334 @@
|
|
|
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 { inChannel } from "../channel-scope.mjs";
|
|
8
|
+
import { definiteProxyFailure } from "../connection-proxy.mjs";
|
|
9
|
+
import { deliverError, deliverRequest } from "../deliver-route.mjs";
|
|
10
|
+
import { readDeliveredFile } from "../sent-files.mjs";
|
|
11
|
+
import { St as reportTelegramError } from "../../../_chunks/principal-DIQHp6AG.mjs";
|
|
12
|
+
import { inTelegramSendQueue, telegramSendScope } from "./send-queue.mjs";
|
|
13
|
+
import { ChannelAnswerError, TELEGRAM_CAPTION_LIMIT, TELEGRAM_DELIVER_PARTS, TELEGRAM_FILES_PER_MESSAGE, TELEGRAM_INLINE_FILE_BYTES, sendTelegramFiles, telegramFileRefusal, telegramFileType, telegramFormattingRefused } from "@segmentstream/ontology/telegram";
|
|
14
|
+
import { POST } from "eve/channels";
|
|
15
|
+
const TELEGRAM_DELIVER_ROUTE = "/eve/segmentstream/v1/telegram/:channel/deliver";
|
|
16
|
+
const DELIVER_ATTEMPTS = 3;
|
|
17
|
+
const RETRY_WAIT_MS = 1e4;
|
|
18
|
+
const CHAT_ID = /^-?[1-9][0-9]*$/u;
|
|
19
|
+
const MESSAGE_ID = /^[1-9][0-9]*$/u;
|
|
20
|
+
function isRecord(value) {
|
|
21
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22
|
+
}
|
|
23
|
+
function answerOf(reply) {
|
|
24
|
+
try {
|
|
25
|
+
const value = JSON.parse(new TextDecoder().decode(reply.body));
|
|
26
|
+
return isRecord(value) ? value : void 0;
|
|
27
|
+
} catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function floodWait(status, answer) {
|
|
32
|
+
if (status !== 429 && answer.error_code !== 429) return;
|
|
33
|
+
const seconds = isRecord(answer.parameters) ? answer.parameters.retry_after : void 0;
|
|
34
|
+
return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0 && seconds * 1e3 <= RETRY_WAIT_MS ? seconds * 1e3 : void 0;
|
|
35
|
+
}
|
|
36
|
+
function messageUrl(chatId, chat, id) {
|
|
37
|
+
if (!chatId.startsWith("-")) return null;
|
|
38
|
+
if (typeof chat.username === "string" && /^[A-Za-z][A-Za-z0-9_]{3,31}$/u.test(chat.username)) return `https://t.me/${chat.username}/${id}`;
|
|
39
|
+
return /^-100[1-9][0-9]*$/u.test(chatId) ? `https://t.me/c/${chatId.slice(4)}/${id}` : null;
|
|
40
|
+
}
|
|
41
|
+
async function sendMessage(request, sleep, delivery, text, markup) {
|
|
42
|
+
const call = {
|
|
43
|
+
api: "bot",
|
|
44
|
+
method: "POST",
|
|
45
|
+
path: "/sendMessage",
|
|
46
|
+
headers: [["content-type", "application/json"]],
|
|
47
|
+
body: new TextEncoder().encode(JSON.stringify({
|
|
48
|
+
chat_id: delivery.chatId,
|
|
49
|
+
...delivery.threadId === null ? {} : { message_thread_id: Number(delivery.threadId) },
|
|
50
|
+
...text,
|
|
51
|
+
...markup === void 0 ? {} : { reply_markup: markup },
|
|
52
|
+
...delivery.replyTo === null ? {} : { reply_parameters: {
|
|
53
|
+
message_id: Number(delivery.replyTo),
|
|
54
|
+
allow_sending_without_reply: false
|
|
55
|
+
} }
|
|
56
|
+
}))
|
|
57
|
+
};
|
|
58
|
+
const uncertain = (cause) => ({
|
|
59
|
+
status: "uncertain",
|
|
60
|
+
messageId: null,
|
|
61
|
+
url: null,
|
|
62
|
+
causes: [cause]
|
|
63
|
+
});
|
|
64
|
+
for (let attempt = 1;; attempt++) {
|
|
65
|
+
let reply;
|
|
66
|
+
try {
|
|
67
|
+
reply = await request(call);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return definiteProxyFailure(error) ? {
|
|
70
|
+
status: "failed",
|
|
71
|
+
messageId: null,
|
|
72
|
+
url: null,
|
|
73
|
+
error: "connection_refused",
|
|
74
|
+
causes: [error]
|
|
75
|
+
} : uncertain(error);
|
|
76
|
+
}
|
|
77
|
+
const answer = answerOf(reply);
|
|
78
|
+
const answered = new ChannelAnswerError(`Telegram answered sendMessage with status ${reply.status}.`, reply.status, reply);
|
|
79
|
+
if (answer === void 0) return uncertain(answered);
|
|
80
|
+
if (answer.ok === false) {
|
|
81
|
+
const wait = floodWait(reply.status, answer);
|
|
82
|
+
if (wait !== void 0 && attempt < DELIVER_ATTEMPTS) {
|
|
83
|
+
await sleep(wait);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
status: "failed",
|
|
88
|
+
messageId: null,
|
|
89
|
+
url: null,
|
|
90
|
+
formattingRefused: telegramFormattingRefused(reply.status, answer),
|
|
91
|
+
error: typeof answer.description === "string" && /message thread not found|topic_(?:closed|deleted)/iu.test(answer.description) ? "thread_unavailable" : "provider_refused",
|
|
92
|
+
...reply.status === 403 ? { refusal: "recipient_unreachable" } : {},
|
|
93
|
+
causes: [answered]
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const message = isRecord(answer.result) ? answer.result : {};
|
|
97
|
+
const chat = isRecord(message.chat) ? message.chat : {};
|
|
98
|
+
const quoted = isRecord(message.reply_to_message) ? message.reply_to_message : {};
|
|
99
|
+
if (reply.status < 200 || reply.status >= 300 || answer.ok !== true || !Number.isSafeInteger(message.message_id) || Number(message.message_id) < 1 || String(chat.id) !== delivery.chatId || delivery.replyTo !== null && String(quoted.message_id) !== delivery.replyTo) return uncertain(answered);
|
|
100
|
+
const id = String(message.message_id);
|
|
101
|
+
return {
|
|
102
|
+
status: "sent",
|
|
103
|
+
messageId: id,
|
|
104
|
+
url: messageUrl(delivery.chatId, chat, id),
|
|
105
|
+
causes: []
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async function sendText(request, sleep, delivery, part, markup) {
|
|
110
|
+
const formatted = await sendMessage(request, sleep, delivery, part.formatted, markup);
|
|
111
|
+
if (part.formatted.parse_mode === void 0 || formatted.formattingRefused !== true) return formatted;
|
|
112
|
+
const plain = await sendMessage(request, sleep, delivery, part.plain, markup);
|
|
113
|
+
return {
|
|
114
|
+
...plain,
|
|
115
|
+
causes: [...formatted.causes, ...plain.causes]
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function fileError(part) {
|
|
119
|
+
return part.code === "unavailable" ? "file_unavailable" : part.code === "too_large" ? "file_too_large" : part.cause instanceof ChannelAnswerError ? "provider_refused" : "connection_refused";
|
|
120
|
+
}
|
|
121
|
+
async function deliverTelegram(delivery, options) {
|
|
122
|
+
const { parts, files } = delivery;
|
|
123
|
+
const target = (replyTo) => ({
|
|
124
|
+
chatId: delivery.chatId,
|
|
125
|
+
...delivery.threadId === null ? {} : { messageThreadId: delivery.threadId },
|
|
126
|
+
...replyTo === null ? {} : { replyTo }
|
|
127
|
+
});
|
|
128
|
+
const types = new Set(files.map((file) => telegramFileType(file.contentType)));
|
|
129
|
+
const oneMessage = files.length === 1 || types.size === 1 && files.length <= TELEGRAM_FILES_PER_MESSAGE;
|
|
130
|
+
const first = parts[0];
|
|
131
|
+
const captioned = files.length > 0 && (parts.length === 0 || parts.length === 1 && oneMessage && first.formatted.text.length <= TELEGRAM_CAPTION_LIMIT);
|
|
132
|
+
const texts = [];
|
|
133
|
+
let sentFiles = [];
|
|
134
|
+
const indexed = files.map((file, index) => ({
|
|
135
|
+
...file,
|
|
136
|
+
index
|
|
137
|
+
}));
|
|
138
|
+
if (captioned) sentFiles = await sendTelegramFiles({
|
|
139
|
+
request: options.request,
|
|
140
|
+
target: target(delivery.replyTo),
|
|
141
|
+
files: indexed,
|
|
142
|
+
...first === void 0 ? {} : {
|
|
143
|
+
caption: {
|
|
144
|
+
text: first.formatted.text,
|
|
145
|
+
entities: [],
|
|
146
|
+
...first.formatted.parse_mode === void 0 ? {} : { parseMode: first.formatted.parse_mode }
|
|
147
|
+
},
|
|
148
|
+
plainCaption: {
|
|
149
|
+
text: first.plain.text,
|
|
150
|
+
entities: []
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
definite: definiteProxyFailure
|
|
154
|
+
});
|
|
155
|
+
else {
|
|
156
|
+
for (const [index, part] of parts.entries()) {
|
|
157
|
+
const result = await sendText(options.request, options.sleep, delivery, part, index === parts.length - 1 ? delivery.replyMarkup : void 0);
|
|
158
|
+
texts.push(result);
|
|
159
|
+
if (result.status !== "sent") break;
|
|
160
|
+
}
|
|
161
|
+
if (files.length > 0 && texts.every((text) => text.status === "sent")) sentFiles = await sendTelegramFiles({
|
|
162
|
+
request: options.request,
|
|
163
|
+
target: target(null),
|
|
164
|
+
files: indexed,
|
|
165
|
+
definite: definiteProxyFailure
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
const visible = [...texts.map((text) => ({
|
|
169
|
+
status: text.status,
|
|
170
|
+
messageIds: text.messageId === null ? [] : [text.messageId],
|
|
171
|
+
error: text.error,
|
|
172
|
+
refusal: text.refusal
|
|
173
|
+
})), ...sentFiles.map((part) => ({
|
|
174
|
+
status: part.status,
|
|
175
|
+
messageIds: part.messageIds,
|
|
176
|
+
error: part.status === "failed" ? fileError(part) : void 0,
|
|
177
|
+
refusal: void 0
|
|
178
|
+
}))];
|
|
179
|
+
const sent = visible.length > 0 && visible.every((part) => part.status === "sent");
|
|
180
|
+
const none = visible.every((part) => part.status === "failed");
|
|
181
|
+
const firstSent = visible.find((part) => part.status === "sent")?.messageIds[0] ?? null;
|
|
182
|
+
const firstFailed = visible.find((part) => part.status === "failed");
|
|
183
|
+
const status = sent ? "sent" : none ? "failed" : "uncertain";
|
|
184
|
+
const causes = [...texts.flatMap((text) => text.causes), ...sentFiles.flatMap((part) => part.status === "sent" || part.cause === void 0 ? [] : [part.cause])];
|
|
185
|
+
return {
|
|
186
|
+
status,
|
|
187
|
+
messageId: status === "failed" ? null : firstSent,
|
|
188
|
+
url: files.length === 0 && status !== "failed" ? texts.find((text) => text.status === "sent")?.url ?? null : null,
|
|
189
|
+
...status === "failed" ? { error: firstFailed?.error ?? "provider_refused" } : {},
|
|
190
|
+
...status === "failed" && firstFailed?.refusal !== void 0 ? { refusal: firstFailed.refusal } : {},
|
|
191
|
+
...files.length === 0 ? {} : { files: files.map((_file, index) => {
|
|
192
|
+
const part = sentFiles.find((candidate) => candidate.files.includes(index));
|
|
193
|
+
const position = part?.files.indexOf(index) ?? -1;
|
|
194
|
+
return {
|
|
195
|
+
index,
|
|
196
|
+
status: part?.status ?? "failed",
|
|
197
|
+
message_id: part?.status === "sent" ? part.messageIds[position] ?? part.messageIds[0] ?? null : null
|
|
198
|
+
};
|
|
199
|
+
}) },
|
|
200
|
+
causes
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function textOf(value) {
|
|
204
|
+
if (!isRecord(value) || typeof value.text !== "string" || value.text.trim() === "" || value.parse_mode !== void 0 && value.parse_mode !== "MarkdownV2" || value.link_preview_options !== void 0 && !isRecord(value.link_preview_options) || value.disable_web_page_preview !== void 0 && typeof value.disable_web_page_preview !== "boolean") return;
|
|
205
|
+
return {
|
|
206
|
+
text: value.text,
|
|
207
|
+
...value.parse_mode === void 0 ? {} : { parse_mode: "MarkdownV2" },
|
|
208
|
+
...value.link_preview_options === void 0 ? {} : { link_preview_options: value.link_preview_options },
|
|
209
|
+
...value.disable_web_page_preview === void 0 ? {} : { disable_web_page_preview: value.disable_web_page_preview }
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function keyboardOf(value) {
|
|
213
|
+
if (value === void 0) return;
|
|
214
|
+
const rows = isRecord(value) ? value.inline_keyboard : void 0;
|
|
215
|
+
if (!Array.isArray(rows) || rows.length === 0 || !rows.every(Array.isArray)) return null;
|
|
216
|
+
const buttons = rows.map((row) => row.map((button) => isRecord(button) && typeof button.text === "string" ? typeof button.url === "string" && button.callback_data === void 0 ? {
|
|
217
|
+
text: button.text,
|
|
218
|
+
url: button.url
|
|
219
|
+
} : typeof button.callback_data === "string" && button.url === void 0 ? {
|
|
220
|
+
text: button.text,
|
|
221
|
+
callback_data: button.callback_data
|
|
222
|
+
} : void 0 : void 0));
|
|
223
|
+
return buttons.every((row) => row.length > 0 && row.every((button) => button !== void 0)) ? { inline_keyboard: buttons } : null;
|
|
224
|
+
}
|
|
225
|
+
function deliveryOf(body) {
|
|
226
|
+
const parts = Array.isArray(body.parts) ? body.parts.map((part) => {
|
|
227
|
+
const formatted = isRecord(part) ? textOf(part.formatted) : void 0;
|
|
228
|
+
const plain = isRecord(part) ? textOf(part.plain) : void 0;
|
|
229
|
+
return formatted === void 0 || plain === void 0 ? void 0 : {
|
|
230
|
+
formatted,
|
|
231
|
+
plain
|
|
232
|
+
};
|
|
233
|
+
}) : void 0;
|
|
234
|
+
const files = body.files === void 0 ? [] : body.files;
|
|
235
|
+
const replyMarkup = keyboardOf(body.reply_markup);
|
|
236
|
+
if (typeof body.operation_id !== "string" || body.operation_id === "" || body.operation_id.length > 512 || typeof body.connection !== "string" || typeof body.chat_id !== "string" || !CHAT_ID.test(body.chat_id) || body.thread_id !== null && (typeof body.thread_id !== "string" || !MESSAGE_ID.test(body.thread_id)) || body.reply_to !== null && (typeof body.reply_to !== "string" || !MESSAGE_ID.test(body.reply_to) || !Number.isSafeInteger(Number(body.reply_to))) || parts === void 0 || parts.length > TELEGRAM_DELIVER_PARTS || !parts.every((part) => part !== void 0) || replyMarkup === null || !Array.isArray(files) || files.length > TELEGRAM_FILES_PER_MESSAGE || !files.every((file) => isRecord(file) && typeof file.filename === "string" && typeof file.content_type === "string" && Number.isSafeInteger(file.size) && file.size >= 0 && typeof file.url === "string" && file.url.startsWith("https://")) || parts.length + files.length === 0) return;
|
|
237
|
+
return {
|
|
238
|
+
operationId: body.operation_id,
|
|
239
|
+
connection: body.connection,
|
|
240
|
+
delivery: {
|
|
241
|
+
chatId: body.chat_id,
|
|
242
|
+
threadId: body.thread_id,
|
|
243
|
+
replyTo: body.reply_to,
|
|
244
|
+
parts,
|
|
245
|
+
...replyMarkup === void 0 ? {} : { replyMarkup }
|
|
246
|
+
},
|
|
247
|
+
files: files.map((file) => ({
|
|
248
|
+
filename: file.filename,
|
|
249
|
+
contentType: file.content_type,
|
|
250
|
+
size: file.size,
|
|
251
|
+
url: file.url
|
|
252
|
+
}))
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function linkSecrets(url) {
|
|
256
|
+
const parsed = URL.parse(url);
|
|
257
|
+
const values = [url];
|
|
258
|
+
parsed?.searchParams.forEach((value, name) => {
|
|
259
|
+
if (/signature|credential|token|key/iu.test(name)) values.push(value);
|
|
260
|
+
});
|
|
261
|
+
return values;
|
|
262
|
+
}
|
|
263
|
+
function telegramDeliverRoute(options) {
|
|
264
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
265
|
+
return POST(TELEGRAM_DELIVER_ROUTE, async (request, args) => {
|
|
266
|
+
const read = await deliverRequest(request, args.params, {
|
|
267
|
+
environment: options.environment,
|
|
268
|
+
verify: options.verify,
|
|
269
|
+
declared: (name) => options.settings(name) !== null
|
|
270
|
+
});
|
|
271
|
+
if ("failure" in read) return read.failure;
|
|
272
|
+
const { channel } = read;
|
|
273
|
+
const named = deliveryOf(read.body);
|
|
274
|
+
if (named === void 0) return deliverError("invalid_request", 400);
|
|
275
|
+
const connection = options.settings(channel)?.connection;
|
|
276
|
+
if (connection === void 0 || named.connection !== connection) return deliverError("channel_unknown", 422);
|
|
277
|
+
for (const file of named.files) {
|
|
278
|
+
const refusal = telegramFileRefusal(file, { stored: true });
|
|
279
|
+
if (refusal !== void 0) return deliverError(refusal.code === "empty" ? "files_unsupported" : "file_too_large", 422);
|
|
280
|
+
}
|
|
281
|
+
const metadata = {
|
|
282
|
+
operationId: named.operationId,
|
|
283
|
+
chatId: named.delivery.chatId
|
|
284
|
+
};
|
|
285
|
+
const secrets = new Set(named.files.flatMap((file) => linkSecrets(file.url)));
|
|
286
|
+
return inChannel("telegram", channel, async () => {
|
|
287
|
+
const files = [];
|
|
288
|
+
for (const file of named.files) try {
|
|
289
|
+
files.push(file.size <= TELEGRAM_INLINE_FILE_BYTES ? {
|
|
290
|
+
filename: file.filename,
|
|
291
|
+
contentType: file.contentType,
|
|
292
|
+
bytes: await readDeliveredFile(file, options.fetch ?? fetch)
|
|
293
|
+
} : {
|
|
294
|
+
filename: file.filename,
|
|
295
|
+
contentType: file.contentType,
|
|
296
|
+
size: file.size,
|
|
297
|
+
read: async () => ({
|
|
298
|
+
url: file.url,
|
|
299
|
+
headers: []
|
|
300
|
+
})
|
|
301
|
+
});
|
|
302
|
+
} catch (cause) {
|
|
303
|
+
reportTelegramError("telegram_deliver_file_unavailable", cause, metadata, secrets);
|
|
304
|
+
return deliverError("file_unavailable", 422);
|
|
305
|
+
}
|
|
306
|
+
const proxy = options.proxy();
|
|
307
|
+
try {
|
|
308
|
+
const outcome = await inTelegramSendQueue(telegramSendScope(options.environment, connection), named.delivery.chatId, () => deliverTelegram({
|
|
309
|
+
...named.delivery,
|
|
310
|
+
files
|
|
311
|
+
}, {
|
|
312
|
+
request: (call) => proxy.request(call),
|
|
313
|
+
sleep
|
|
314
|
+
}));
|
|
315
|
+
const reference = outcome.causes.length === 0 ? void 0 : reportTelegramError(`telegram_deliver_${outcome.status}`, outcome.causes.length === 1 ? outcome.causes[0] : new AggregateError(outcome.causes, "Parts of the message were not sent."), metadata, secrets);
|
|
316
|
+
if (outcome.status === "failed") return deliverError(outcome.error ?? "provider_refused", 422, {
|
|
317
|
+
...outcome.refusal === void 0 ? {} : { refusal: outcome.refusal },
|
|
318
|
+
...reference === void 0 ? {} : { reference }
|
|
319
|
+
});
|
|
320
|
+
return Response.json({
|
|
321
|
+
status: outcome.status,
|
|
322
|
+
message_id: outcome.messageId,
|
|
323
|
+
url: outcome.url,
|
|
324
|
+
...outcome.files === void 0 ? {} : { files: outcome.files },
|
|
325
|
+
...reference === void 0 ? {} : { reference }
|
|
326
|
+
});
|
|
327
|
+
} catch (cause) {
|
|
328
|
+
const reference = reportTelegramError("telegram_deliver_failed", cause, metadata, secrets);
|
|
329
|
+
return deliverError("send_failed", 502, { reference });
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
export { TELEGRAM_DELIVER_ROUTE, deliverTelegram, telegramDeliverRoute };
|