@segmentstream/agent 0.104.0 → 0.106.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 +64 -0
- package/README.md +10 -2
- package/dist/_chunks/{build-metadata-DkPNOrqc.mjs → build-metadata-CxTQ2jH4.mjs} +1 -1
- package/dist/extension/channels/whatsapp.d.ts +2 -0
- package/dist/extension/lib/build-metadata.mjs +1 -1
- 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 +33 -0
- package/dist/extension/lib/deliver-route.mjs +43 -0
- package/dist/extension/lib/email/channel.mjs +10 -31
- package/dist/extension/lib/sent-files.d.ts +9 -0
- package/dist/extension/lib/sent-files.mjs +15 -1
- package/dist/extension/lib/telegram/adapter.d.ts +3 -1
- package/dist/extension/lib/telegram/adapter.mjs +10 -1
- package/dist/extension/lib/telegram/deliver.d.ts +77 -0
- package/dist/extension/lib/telegram/deliver.mjs +326 -0
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/lib/whatsapp/adapter.d.ts +7 -0
- package/dist/extension/lib/whatsapp/adapter.mjs +10 -2
- package/dist/extension/lib/whatsapp/deliver.d.ts +72 -0
- package/dist/extension/lib/whatsapp/deliver.mjs +225 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,69 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.106.0
|
|
4
|
+
|
|
5
|
+
The WhatsApp channel delivers the messages the ontology sends, a post in either voice, a draft a
|
|
6
|
+
member approves and a reply its review lets go, at
|
|
7
|
+
`POST /eve/segmentstream/v1/whatsapp/<name>/deliver`, for the deployment's own functions only. It
|
|
8
|
+
sends what the ontology rendered from its number, through the connection its replies use, as the
|
|
9
|
+
ontology's own sender did, and never rewrites it:
|
|
10
|
+
|
|
11
|
+
- a message without files as one message: the text with link previews off, the text with up to
|
|
12
|
+
three workspace buttons or one link under it, or an approved template with its values;
|
|
13
|
+
- a message with files as one message per file, which WhatsApp fetches by its short-lived link,
|
|
14
|
+
the text as the first's caption, or first on its own when it is longer than a caption or the
|
|
15
|
+
first file is audio; a refused file does not stop the next, and each file's result is answered.
|
|
16
|
+
A file whose turn comes more than 30 seconds after the message arrived is not sent, as its link
|
|
17
|
+
may expire before WhatsApp fetches it.
|
|
18
|
+
|
|
19
|
+
Each message is one `POST /phone/messages`, never retried, and never through the adapter's own
|
|
20
|
+
posts, which would render and split the text. Meta's refusal with an error code, or the
|
|
21
|
+
connection's before the call reached Meta, answers that nothing was sent; for a message without
|
|
22
|
+
files it names Meta's reason where its code names one (`outside_reply_window`,
|
|
23
|
+
`recipient_unreachable`, `recipient_opted_out`). Anything else is uncertain, with each file's
|
|
24
|
+
result. The original errors, Meta's explanation included, go to the deployment's logs with the
|
|
25
|
+
files' and the template's links redacted, under the reference the answer names. A channel on
|
|
26
|
+
another connection than the one the ontology's `chat` names for it answers `channel_unknown`, and
|
|
27
|
+
the ontology sends the message itself.
|
|
28
|
+
|
|
29
|
+
An ontology SDK from before the route never calls it and sends its WhatsApp messages itself, so
|
|
30
|
+
this release works with the ontology SDK's previous release, and the ontology SDK's next release
|
|
31
|
+
works with this agent SDK's previous one, which answers it 404.
|
|
32
|
+
|
|
33
|
+
Pins @segmentstream/ontology 0.185.0.
|
|
34
|
+
|
|
35
|
+
## 0.105.0
|
|
36
|
+
|
|
37
|
+
The Telegram channel delivers the messages the ontology sends, a post in either voice, a draft a
|
|
38
|
+
member approves and a reply its review lets go, at
|
|
39
|
+
`POST /eve/segmentstream/v1/telegram/<name>/deliver`, for the deployment's own functions only. It
|
|
40
|
+
sends what the ontology rendered through its bot, as the ontology's own sender did, and never
|
|
41
|
+
rewrites it:
|
|
42
|
+
|
|
43
|
+
- each text message in order, in the chat's send queue, which its own replies share, in the chat's
|
|
44
|
+
forum topic and as a reply to the message it answers, the buttons under the last; a text Telegram
|
|
45
|
+
refuses the formatting of goes once more as plain text;
|
|
46
|
+
- the files after the text, or under it as their caption when the text fits one and the files go
|
|
47
|
+
as one message; nothing follows a text that did not certainly reach the person;
|
|
48
|
+
- each file read by its short-lived link before the queue is taken, and refused, sending nothing,
|
|
49
|
+
when its size is not the one the ontology checked; a file too large for an album goes by its link,
|
|
50
|
+
which the connection proxy reads from storage.
|
|
51
|
+
|
|
52
|
+
Telegram's flood control, which sent nothing, is waited out, up to three attempts; nothing else is
|
|
53
|
+
sent twice, and no adapter retries a send. Telegram's refusal, or the connection's before the call
|
|
54
|
+
reached Telegram, answers that nothing was sent (`recipient_unreachable` for a person who blocked
|
|
55
|
+
the bot, `thread_unavailable` for a topic Telegram no longer has); anything else is uncertain, with
|
|
56
|
+
each file's result. The original errors, Telegram's explanation included, go to the deployment's
|
|
57
|
+
logs with credentials redacted, under the reference the answer names. A channel on another
|
|
58
|
+
connection than the one the ontology's `chat` names for it answers `channel_unknown`, and the
|
|
59
|
+
ontology sends the message itself.
|
|
60
|
+
|
|
61
|
+
An ontology SDK from before the route never calls it and sends its Telegram messages itself, so
|
|
62
|
+
this release works with the ontology SDK's previous release, and the ontology SDK's next release
|
|
63
|
+
works with this agent SDK's previous one, which answers it 404.
|
|
64
|
+
|
|
65
|
+
Pins @segmentstream/ontology 0.184.0.
|
|
66
|
+
|
|
3
67
|
## 0.104.0
|
|
4
68
|
|
|
5
69
|
The starter's `agent/agent/instructions.md` tells the agent, in the workspace's words, to answer in
|
package/README.md
CHANGED
|
@@ -600,8 +600,16 @@ The SDK adds no text to the prompt.
|
|
|
600
600
|
the preview and show a Telegram link when available; archive failure is distinct from send failure.
|
|
601
601
|
Agent SDK 0.6.0 prepares this flow; delivery becomes available when the ontology advertises the
|
|
602
602
|
protocol below. The old instruction receiver `/eve/v1/telegram/messages` is removed. Telegram
|
|
603
|
-
routes now serve only the inbound webhook
|
|
604
|
-
fail instead of starting an agent turn.
|
|
603
|
+
routes now serve only the inbound webhook, authenticated health and the deliver route; old
|
|
604
|
+
instruction relay calls fail instead of starting an agent turn.
|
|
605
|
+
- **Messages the ontology sends.** The ontology renders each Telegram message it sends, a post, an
|
|
606
|
+
approved draft or a reply its review lets go, and hands it to the channel of the chat's name at
|
|
607
|
+
`POST /eve/segmentstream/v1/telegram/<name>/deliver`, for the deployment's own functions only.
|
|
608
|
+
The channel sends it through its bot in the chat's send queue, as the ontology's own sender did,
|
|
609
|
+
and answers what reached the person. See `docs/agent.md`, "Telegram messages the ontology sends".
|
|
610
|
+
A WhatsApp message, its text, its buttons or its approved template, goes to the WhatsApp channel
|
|
611
|
+
of the chat's name at `POST /eve/segmentstream/v1/whatsapp/<name>/deliver` in the same way, which
|
|
612
|
+
sends it from its number. See `docs/agent.md`, "WhatsApp messages the ontology sends".
|
|
605
613
|
- **Replies.** The model answers with `segmentstream__reply`, which ends the turn; at its end the
|
|
606
614
|
channel posts the call's text as it posts a reply part, quoting the message its `replyTo` names.
|
|
607
615
|
<!-- @legacy agent.final-text-replies -->
|
|
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
|
|
|
4
4
|
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
|
-
var version = "0.
|
|
7
|
+
var version = "0.106.0";
|
|
8
8
|
function agentBuild(environment = process.env) {
|
|
9
9
|
return {
|
|
10
10
|
agent: version,
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* `channels.whatsapp`, and `POST /eve/segmentstream/v1/whatsapp/<name>` the number of every other
|
|
4
4
|
* channel of kind `whatsapp`. SegmentStream relays each number's messages to its channel. Without
|
|
5
5
|
* such a channel, or outside production, the route answers 404.
|
|
6
|
+
* `POST /eve/segmentstream/v1/whatsapp/<name>/deliver` sends the messages the ontology decided from
|
|
7
|
+
* the number of the channel named, for the deployment's own functions only.
|
|
6
8
|
*/
|
|
7
9
|
declare const _default: import("eve/channels/chat-sdk").ChatSdkChannel;
|
|
8
10
|
export default _default;
|
|
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
|
|
|
4
4
|
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
|
-
export { t as agentBuild } from "../../_chunks/build-metadata-
|
|
7
|
+
export { t as agentBuild } from "../../_chunks/build-metadata-CxTQ2jH4.mjs";
|
|
@@ -75,6 +75,12 @@ export declare class ConnectionProxyError extends Error {
|
|
|
75
75
|
readonly cause?: unknown;
|
|
76
76
|
});
|
|
77
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Whether a failed proxy call proves the provider never saw it, so nothing was sent: a refusal
|
|
80
|
+
* before the proxy relayed it, as the ontology classifies its own connection failures. A timeout,
|
|
81
|
+
* a lost answer or any other failure may have reached the provider, and a send is then uncertain.
|
|
82
|
+
*/
|
|
83
|
+
export declare function definiteProxyFailure(error: unknown): boolean;
|
|
78
84
|
export interface ConnectionProxy {
|
|
79
85
|
readonly connection: string;
|
|
80
86
|
request(call: ProxyCall, abortSignal?: AbortSignal): Promise<ProxyReply>;
|
|
@@ -37,6 +37,37 @@ var ConnectionProxyError = class extends Error {
|
|
|
37
37
|
this.requestId = input.requestId;
|
|
38
38
|
}
|
|
39
39
|
};
|
|
40
|
+
const UNRELAYED_PROXY_CODES = new Set([
|
|
41
|
+
"connection_authorization_required",
|
|
42
|
+
"connections_not_deployed",
|
|
43
|
+
"connections_redeployment_required",
|
|
44
|
+
"connection_not_found",
|
|
45
|
+
"connection_not_granted",
|
|
46
|
+
"runtime_unauthorized",
|
|
47
|
+
"runtime_value_not_granted",
|
|
48
|
+
"unauthorized",
|
|
49
|
+
"connection_provider_refused",
|
|
50
|
+
"invalid_connection",
|
|
51
|
+
"invalid_request",
|
|
52
|
+
"mcp_request_not_permitted"
|
|
53
|
+
]);
|
|
54
|
+
const RELAYED_PROXY_CODES = new Set([
|
|
55
|
+
"connection_provider_unavailable",
|
|
56
|
+
"connection_provider_timeout",
|
|
57
|
+
"connection_proxy_unavailable",
|
|
58
|
+
"connection_response_too_large",
|
|
59
|
+
"service_unavailable",
|
|
60
|
+
"timeout",
|
|
61
|
+
"unavailable",
|
|
62
|
+
"invalid_response",
|
|
63
|
+
"too_large"
|
|
64
|
+
]);
|
|
65
|
+
function definiteProxyFailure(error) {
|
|
66
|
+
if (!(error instanceof ConnectionProxyError)) return false;
|
|
67
|
+
if (UNRELAYED_PROXY_CODES.has(error.code)) return true;
|
|
68
|
+
if (RELAYED_PROXY_CODES.has(error.code)) return false;
|
|
69
|
+
return error.status !== void 0 && error.status < 500;
|
|
70
|
+
}
|
|
40
71
|
function isRecord(value) {
|
|
41
72
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
42
73
|
}
|
|
@@ -227,4 +258,4 @@ async function framedReply(connection, body, maxBytes) {
|
|
|
227
258
|
body: new Uint8Array(Buffer.concat(chunks))
|
|
228
259
|
};
|
|
229
260
|
}
|
|
230
|
-
export { ConnectionProxyError, MAXIMUM_DOWNLOAD_BYTES, MAXIMUM_PROXY_BODY_BYTES, MAXIMUM_PROXY_FRAME_BYTES, PROXY_STREAM_MEDIA_TYPE, connectionProxy };
|
|
261
|
+
export { ConnectionProxyError, MAXIMUM_DOWNLOAD_BYTES, MAXIMUM_PROXY_BODY_BYTES, MAXIMUM_PROXY_FRAME_BYTES, PROXY_STREAM_MEDIA_TYPE, connectionProxy, definiteProxyFailure };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Environment } from "./environment.js";
|
|
2
|
+
import type { RuntimeTokenVerifier } from "./runtime-identity.js";
|
|
3
|
+
/**
|
|
4
|
+
* What every channel's deliver route shares: the route the ontology hands a message it decided and
|
|
5
|
+
* rendered, for the channel to send through its provider (`emailDeliverRoute`,
|
|
6
|
+
* `telegramDeliverRoute` and `whatsappDeliverRoute` of the ontology SDK). Only the deployment's own
|
|
7
|
+
* functions may call one, with its runtime identity; outside production it answers `404`, as it
|
|
8
|
+
* does where the agent has no such route. It serves the agent's channel the path names, by
|
|
9
|
+
* `:channel`, and refuses one the agent has not with `422 channel_unknown`, which an agent without
|
|
10
|
+
* the route never answers.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* The values of a link to the workspace's file storage that grant its read, the link itself and its
|
|
14
|
+
* signature: none of them may reach a diagnostic.
|
|
15
|
+
*/
|
|
16
|
+
export declare function linkSecrets(url: string): ReadonlyArray<string>;
|
|
17
|
+
/** A deliver route's refusal: its code, and what the ontology may act on beside it. */
|
|
18
|
+
export declare function deliverError(code: string, status: number, detail?: Readonly<Record<string, unknown>>): Response;
|
|
19
|
+
/**
|
|
20
|
+
* The deliver request: its caller verified, its channel's name, and the JSON object it carries; or
|
|
21
|
+
* the response that refuses it.
|
|
22
|
+
*/
|
|
23
|
+
export declare function deliverRequest(request: Request, params: Readonly<Record<string, string | undefined>>, options: {
|
|
24
|
+
readonly environment: Environment;
|
|
25
|
+
readonly verify: () => RuntimeTokenVerifier;
|
|
26
|
+
/** Whether the agent has a channel of the route's kind by this name. */
|
|
27
|
+
readonly declared: (name: string) => boolean;
|
|
28
|
+
}): Promise<{
|
|
29
|
+
readonly failure: Response;
|
|
30
|
+
} | {
|
|
31
|
+
readonly channel: string;
|
|
32
|
+
readonly body: Readonly<Record<string, unknown>>;
|
|
33
|
+
}>;
|
|
@@ -0,0 +1,43 @@
|
|
|
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 { CHANNEL_NAME } from "../config.mjs";
|
|
8
|
+
import { channelsEnabled } from "./environment.mjs";
|
|
9
|
+
import { runtimeRequestFailure } from "./telegram/runtime-request.mjs";
|
|
10
|
+
function linkSecrets(url) {
|
|
11
|
+
const parsed = URL.parse(url);
|
|
12
|
+
const values = [url];
|
|
13
|
+
parsed?.searchParams.forEach((value, name) => {
|
|
14
|
+
if (/signature|credential|token|key/iu.test(name)) values.push(value);
|
|
15
|
+
});
|
|
16
|
+
return values;
|
|
17
|
+
}
|
|
18
|
+
function deliverError(code, status, detail = {}) {
|
|
19
|
+
return Response.json({
|
|
20
|
+
error: code,
|
|
21
|
+
...detail
|
|
22
|
+
}, { status });
|
|
23
|
+
}
|
|
24
|
+
async function deliverRequest(request, params, options) {
|
|
25
|
+
const failure = await runtimeRequestFailure(request, {
|
|
26
|
+
enabled: () => true,
|
|
27
|
+
configured: () => channelsEnabled(options.environment),
|
|
28
|
+
verify: options.verify
|
|
29
|
+
});
|
|
30
|
+
if (failure !== void 0) return { failure };
|
|
31
|
+
const channel = params.channel ?? "";
|
|
32
|
+
if (!CHANNEL_NAME.test(channel) || !options.declared(channel)) return { failure: deliverError("channel_unknown", 422) };
|
|
33
|
+
try {
|
|
34
|
+
const value = await request.json();
|
|
35
|
+
return {
|
|
36
|
+
channel,
|
|
37
|
+
body: typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}
|
|
38
|
+
};
|
|
39
|
+
} catch {
|
|
40
|
+
return { failure: deliverError("invalid_request", 400) };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export { deliverError, deliverRequest, linkSecrets };
|
|
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
|
|
|
4
4
|
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
|
-
import {
|
|
7
|
+
import { PUBSUB_TOPIC } from "../../config.mjs";
|
|
8
8
|
import { admitMessage, localizedText, reportUnadmittedChat } from "../admission.mjs";
|
|
9
9
|
import { agentToolsAttribute } from "../agent-tools.mjs";
|
|
10
10
|
import { providerChat } from "../attachment-tools.mjs";
|
|
@@ -25,7 +25,8 @@ import { channelReview } from "../review/reply.mjs";
|
|
|
25
25
|
import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-DwObe1UV.mjs";
|
|
26
26
|
import { runtimeTokenVerifier } from "../runtime-identity.mjs";
|
|
27
27
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
28
|
-
import {
|
|
28
|
+
import { deliverRequest } from "../deliver-route.mjs";
|
|
29
|
+
import { readDeliveredFile } from "../sent-files.mjs";
|
|
29
30
|
import { workspaceTriage } from "../triage.mjs";
|
|
30
31
|
import { GMAIL_ID, GmailError, ReplyNotSent, gmail, replyKeyOf } from "./gmail.mjs";
|
|
31
32
|
import { inboundMail, parseMail, sentMail } from "./message.mjs";
|
|
@@ -35,7 +36,6 @@ import { EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, EMAIL_RECIPIENTS_LIMIT, GmailMa
|
|
|
35
36
|
import { POST, defineChannel } from "eve/channels";
|
|
36
37
|
const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
|
|
37
38
|
const EMAIL_DELIVER_ROUTE = `${EMAIL_ROUTE}/:channel/deliver`;
|
|
38
|
-
const DELIVER_FILE_TIMEOUT_MS = 3e4;
|
|
39
39
|
const EMAIL_AUTHENTICATOR = "segmentstream-email";
|
|
40
40
|
const MESSAGES_PER_WAKE = 20;
|
|
41
41
|
const WATCH_RENEW_MS = 864e5;
|
|
@@ -1100,35 +1100,14 @@ function emailChannelDefinition(options) {
|
|
|
1100
1100
|
}
|
|
1101
1101
|
} });
|
|
1102
1102
|
let verifier = options.verify;
|
|
1103
|
-
async function linkedFile(file) {
|
|
1104
|
-
const response = await (transport.fetch ?? fetch)(file.url, {
|
|
1105
|
-
redirect: "error",
|
|
1106
|
-
signal: AbortSignal.timeout(DELIVER_FILE_TIMEOUT_MS)
|
|
1107
|
-
});
|
|
1108
|
-
if (!response.ok) {
|
|
1109
|
-
await response.body?.cancel();
|
|
1110
|
-
throw new Error(`The file storage answered with status ${response.status}.`);
|
|
1111
|
-
}
|
|
1112
|
-
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1113
|
-
if (bytes.byteLength !== file.size) throw new Error(`The file read has ${bytes.byteLength} bytes, not the ${file.size} named.`);
|
|
1114
|
-
return bytes;
|
|
1115
|
-
}
|
|
1116
1103
|
async function deliverRoute(request, args) {
|
|
1117
|
-
const
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1104
|
+
const read = await deliverRequest(request, args.params, {
|
|
1105
|
+
environment,
|
|
1106
|
+
verify: () => verifier ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment)),
|
|
1107
|
+
declared: (name) => options.settings(name) !== null
|
|
1121
1108
|
});
|
|
1122
|
-
if (failure
|
|
1123
|
-
const name
|
|
1124
|
-
if (!CHANNEL_NAME.test(name) || options.settings(name) === null) return Response.json({ error: "channel_unknown" }, { status: 422 });
|
|
1125
|
-
let body;
|
|
1126
|
-
try {
|
|
1127
|
-
const value = await request.json();
|
|
1128
|
-
body = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
1129
|
-
} catch {
|
|
1130
|
-
return Response.json({ error: "invalid_request" }, { status: 400 });
|
|
1131
|
-
}
|
|
1109
|
+
if ("failure" in read) return read.failure;
|
|
1110
|
+
const { channel: name, body } = read;
|
|
1132
1111
|
const addresses = (value) => Array.isArray(value) && value.every((address) => typeof address === "string" && isEmailAddress(address)) ? value : void 0;
|
|
1133
1112
|
const to = addresses(body.to);
|
|
1134
1113
|
const cc = addresses(body.cc ?? []);
|
|
@@ -1154,7 +1133,7 @@ function emailChannelDefinition(options) {
|
|
|
1154
1133
|
attachments.push({
|
|
1155
1134
|
filename: file.filename,
|
|
1156
1135
|
contentType: file.content_type,
|
|
1157
|
-
bytes: await
|
|
1136
|
+
bytes: await readDeliveredFile(file, transport.fetch ?? fetch)
|
|
1158
1137
|
});
|
|
1159
1138
|
} catch (cause) {
|
|
1160
1139
|
report("file_unavailable", cause);
|
|
@@ -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 };
|
|
@@ -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-CxTQ2jH4.mjs";
|
|
16
16
|
import { attachmentLifecycle } from "./lifecycle.mjs";
|
|
17
17
|
import { manifestOf } from "../../config.mjs";
|
|
18
18
|
import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
|
|
@@ -39,6 +39,7 @@ 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
45
|
import { a as isNoReplyCall, i as interimTexts, s as replyDelivery } from "../../../_chunks/silent-DwObe1UV.mjs";
|
|
@@ -562,6 +563,14 @@ function segmentstreamTelegram(options) {
|
|
|
562
563
|
confirmationMode: options.confirmationMode?.() ?? null,
|
|
563
564
|
attachmentLifecycle: channelSettings()?.attachmentLifecycle !== void 0
|
|
564
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 }
|
|
565
574
|
})
|
|
566
575
|
]
|
|
567
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,326 @@
|
|
|
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, linkSecrets } 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 telegramDeliverRoute(options) {
|
|
256
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
257
|
+
return POST(TELEGRAM_DELIVER_ROUTE, async (request, args) => {
|
|
258
|
+
const read = await deliverRequest(request, args.params, {
|
|
259
|
+
environment: options.environment,
|
|
260
|
+
verify: options.verify,
|
|
261
|
+
declared: (name) => options.settings(name) !== null
|
|
262
|
+
});
|
|
263
|
+
if ("failure" in read) return read.failure;
|
|
264
|
+
const { channel } = read;
|
|
265
|
+
const named = deliveryOf(read.body);
|
|
266
|
+
if (named === void 0) return deliverError("invalid_request", 400);
|
|
267
|
+
const connection = options.settings(channel)?.connection;
|
|
268
|
+
if (connection === void 0 || named.connection !== connection) return deliverError("channel_unknown", 422);
|
|
269
|
+
for (const file of named.files) {
|
|
270
|
+
const refusal = telegramFileRefusal(file, { stored: true });
|
|
271
|
+
if (refusal !== void 0) return deliverError(refusal.code === "empty" ? "files_unsupported" : "file_too_large", 422);
|
|
272
|
+
}
|
|
273
|
+
const metadata = {
|
|
274
|
+
operationId: named.operationId,
|
|
275
|
+
chatId: named.delivery.chatId
|
|
276
|
+
};
|
|
277
|
+
const secrets = new Set(named.files.flatMap((file) => linkSecrets(file.url)));
|
|
278
|
+
return inChannel("telegram", channel, async () => {
|
|
279
|
+
const files = [];
|
|
280
|
+
for (const file of named.files) try {
|
|
281
|
+
files.push(file.size <= TELEGRAM_INLINE_FILE_BYTES ? {
|
|
282
|
+
filename: file.filename,
|
|
283
|
+
contentType: file.contentType,
|
|
284
|
+
bytes: await readDeliveredFile(file, options.fetch ?? fetch)
|
|
285
|
+
} : {
|
|
286
|
+
filename: file.filename,
|
|
287
|
+
contentType: file.contentType,
|
|
288
|
+
size: file.size,
|
|
289
|
+
read: async () => ({
|
|
290
|
+
url: file.url,
|
|
291
|
+
headers: []
|
|
292
|
+
})
|
|
293
|
+
});
|
|
294
|
+
} catch (cause) {
|
|
295
|
+
reportTelegramError("telegram_deliver_file_unavailable", cause, metadata, secrets);
|
|
296
|
+
return deliverError("file_unavailable", 422);
|
|
297
|
+
}
|
|
298
|
+
const proxy = options.proxy();
|
|
299
|
+
try {
|
|
300
|
+
const outcome = await inTelegramSendQueue(telegramSendScope(options.environment, connection), named.delivery.chatId, () => deliverTelegram({
|
|
301
|
+
...named.delivery,
|
|
302
|
+
files
|
|
303
|
+
}, {
|
|
304
|
+
request: (call) => proxy.request(call),
|
|
305
|
+
sleep
|
|
306
|
+
}));
|
|
307
|
+
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);
|
|
308
|
+
if (outcome.status === "failed") return deliverError(outcome.error ?? "provider_refused", 422, {
|
|
309
|
+
...outcome.refusal === void 0 ? {} : { refusal: outcome.refusal },
|
|
310
|
+
...reference === void 0 ? {} : { reference }
|
|
311
|
+
});
|
|
312
|
+
return Response.json({
|
|
313
|
+
status: outcome.status,
|
|
314
|
+
message_id: outcome.messageId,
|
|
315
|
+
url: outcome.url,
|
|
316
|
+
...outcome.files === void 0 ? {} : { files: outcome.files },
|
|
317
|
+
...reference === void 0 ? {} : { reference }
|
|
318
|
+
});
|
|
319
|
+
} catch (cause) {
|
|
320
|
+
const reference = reportTelegramError("telegram_deliver_failed", cause, metadata, secrets);
|
|
321
|
+
return deliverError("send_failed", 502, { reference });
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
export { TELEGRAM_DELIVER_ROUTE, deliverTelegram, telegramDeliverRoute };
|
|
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
|
|
|
4
4
|
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
7
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-CxTQ2jH4.mjs";
|
|
8
8
|
import { runtimeRequestFailure } from "./runtime-request.mjs";
|
|
9
9
|
import { GET } from "eve/channels";
|
|
10
10
|
const HEALTH_ROUTE = "/eve/v1/telegram/health";
|
|
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
|
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { At as telegramRuntimeSource, Dt as principalRuntimeSource, E as OntologyActionNotPermitted, L as needsConfirmation, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as runtimeEnvelope } from "../../../_chunks/principal-DIQHp6AG.mjs";
|
|
8
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
8
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-CxTQ2jH4.mjs";
|
|
9
9
|
import { object } from "../confirmation-description.mjs";
|
|
10
10
|
var AttachmentLifecycleNotPermitted = class extends Error {
|
|
11
11
|
code = "attachment_lifecycle_not_permitted";
|
|
@@ -10,6 +10,7 @@ import { type Transcriber } from "../inbound-media/speech.js";
|
|
|
10
10
|
import { type ChannelReviewOptions } from "../review/reply.js";
|
|
11
11
|
import { type ConnectionProxy } from "../connection-proxy.js";
|
|
12
12
|
import { type Environment } from "../environment.js";
|
|
13
|
+
import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
13
14
|
import { type AgentIdentities, type PairedMember } from "../identities.js";
|
|
14
15
|
import { type RuntimeToken } from "../runtime-token.js";
|
|
15
16
|
import { type ChatArchive } from "../chat-archive.js";
|
|
@@ -47,6 +48,10 @@ import { type WhatsAppEcho } from "./echoes.js";
|
|
|
47
48
|
* Only paired members are answered. A sender nobody paired gets the workspace's
|
|
48
49
|
* `replies.pairingRequired` text with a button labelled `replies.pairingButton` that opens the
|
|
49
50
|
* app's `/agent/connect`, or the text followed by the link where the workspace sets no label.
|
|
51
|
+
*
|
|
52
|
+
* The messages the ontology decides and renders, an approved draft, a reply its review let go or
|
|
53
|
+
* a post, are sent from each channel's number at
|
|
54
|
+
* `POST /eve/segmentstream/v1/whatsapp/<name>/deliver` (`deliver.ts`), and start no turn.
|
|
50
55
|
*/
|
|
51
56
|
/** The authenticator of a WhatsApp session's principal. */
|
|
52
57
|
export declare const WHATSAPP_AUTHENTICATOR = "segmentstream-whatsapp";
|
|
@@ -98,6 +103,8 @@ export interface WhatsAppChannelOptions {
|
|
|
98
103
|
readonly transcribe?: Transcriber;
|
|
99
104
|
readonly describeImage?: ImageDescriber;
|
|
100
105
|
readonly modelCapabilities?: CapabilityLookup;
|
|
106
|
+
/** Verifies callers of the deliver route; tests pass one on a local key set. */
|
|
107
|
+
readonly verify?: RuntimeTokenVerifier;
|
|
101
108
|
}
|
|
102
109
|
/** What the adapter reads per request: eve binds the mount after it loads the channel. */
|
|
103
110
|
interface WhatsAppRuntime {
|
|
@@ -19,7 +19,8 @@ import { withToolReplies } from "../reply.mjs";
|
|
|
19
19
|
import { channelReview, withReviewedReplies } from "../review/reply.mjs";
|
|
20
20
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
21
21
|
import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
|
|
22
|
-
import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
|
|
22
|
+
import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
|
|
23
|
+
import { runtimeTokenVerifier } from "../runtime-identity.mjs";
|
|
23
24
|
import { admitChannelGuest } from "../channel-guest.mjs";
|
|
24
25
|
import { agentIdentities } from "../identities.mjs";
|
|
25
26
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
@@ -32,6 +33,7 @@ import { recordEchoes, whatsappEchoes } from "./echoes.mjs";
|
|
|
32
33
|
import { withPlainLinks } from "./links.mjs";
|
|
33
34
|
import { collectSent, noteSent, recordSent } from "./sent.mjs";
|
|
34
35
|
import { STATUSES_HEADER, STATUSES_RECORDED } from "./statuses.mjs";
|
|
36
|
+
import { whatsappDeliverRoute } from "./deliver.mjs";
|
|
35
37
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
36
38
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
37
39
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
@@ -491,9 +493,15 @@ function segmentstreamWhatsApp(options) {
|
|
|
491
493
|
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
492
494
|
});
|
|
493
495
|
const channel = withToolReplies(reviewed === void 0 ? recorded : withReviewedReplies(recorded, () => reviewed.review));
|
|
496
|
+
let verify = options.verify;
|
|
494
497
|
return {
|
|
495
498
|
...withSessionChannels("whatsapp", channel),
|
|
496
|
-
routes: withNamedRoutes("whatsapp", channel.routes.flatMap((route) => route.transport === "websocket" ? [] : [route]), (name) => options.settings(name) !== null)
|
|
499
|
+
routes: [...withNamedRoutes("whatsapp", channel.routes.flatMap((route) => route.transport === "websocket" ? [] : [route]), (name) => options.settings(name) !== null), whatsappDeliverRoute({
|
|
500
|
+
settings: options.settings,
|
|
501
|
+
proxy: runtime.proxy,
|
|
502
|
+
environment,
|
|
503
|
+
verify: () => verify ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment))
|
|
504
|
+
})]
|
|
497
505
|
};
|
|
498
506
|
}
|
|
499
507
|
function record(value) {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type HttpRouteDefinition } from "eve/channels";
|
|
2
|
+
import type { ChatSdkChannelState } from "eve/channels/chat-sdk";
|
|
3
|
+
import { type ChannelDeliveredFile, type ChannelRequest, type WhatsAppDeliverMessage, type WhatsAppLinkedFile, type WhatsAppRefusal } from "@segmentstream/ontology/whatsapp";
|
|
4
|
+
import type { WhatsAppSettings } 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 WhatsApp channel `:channel` a message to send (`whatsappDeliverRoute`
|
|
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, its
|
|
12
|
+
* buttons or its approved template with the values; the channel sends what it was given from its
|
|
13
|
+
* number, through the connection proxy its adapter uses, and says what reached the person.
|
|
14
|
+
*
|
|
15
|
+
* - A message without files is one message: a text, a text with its buttons, or a template, as
|
|
16
|
+
* WhatsApp's Cloud API takes it. Nothing is rendered, checked or rewritten here.
|
|
17
|
+
* - A message with files is one message per file, which WhatsApp fetches by the file's link, the
|
|
18
|
+
* text as the first's caption, or a text message of its own before them when no caption can
|
|
19
|
+
* carry it, as `sendWhatsAppFiles` sends them for every channel. The messages go in order, in
|
|
20
|
+
* this one request; no lock is held while WhatsApp answers.
|
|
21
|
+
* - Each message is one `POST /phone/messages`, never retried, by WhatsApp's adapter or here: the
|
|
22
|
+
* adapter's own posts would render and split the text, so the route sends without them.
|
|
23
|
+
* - A failure is classified where it happens: Meta's refusal with an error code, or SegmentStream's
|
|
24
|
+
* before the call, sent nothing; anything else may have. Meta's refusal of a message without
|
|
25
|
+
* files names its reason, such as `outside_reply_window` for a person who last wrote more than
|
|
26
|
+
* 24 hours ago. The original errors, Meta's answers included, go to the deployment's logs, the
|
|
27
|
+
* files' links and a template's links redacted, under the reference the answer names.
|
|
28
|
+
*/
|
|
29
|
+
export declare const WHATSAPP_DELIVER_ROUTE = "/eve/segmentstream/v1/whatsapp/:channel/deliver";
|
|
30
|
+
/** A message the deliver route sends, as its request names it. */
|
|
31
|
+
export interface WhatsAppDelivery {
|
|
32
|
+
/** The person, by their WhatsApp id. */
|
|
33
|
+
readonly to: string;
|
|
34
|
+
/** The message, for one without files. */
|
|
35
|
+
readonly message?: WhatsAppDeliverMessage;
|
|
36
|
+
/** The text with the files. */
|
|
37
|
+
readonly caption?: string;
|
|
38
|
+
readonly files: ReadonlyArray<WhatsAppLinkedFile>;
|
|
39
|
+
}
|
|
40
|
+
/** Why nothing of a delivery was sent. */
|
|
41
|
+
export type WhatsAppDeliveryError = "provider_refused" | "connection_refused" | "file_unavailable" | "file_too_large";
|
|
42
|
+
/** What became of a delivery, as Meta's answers prove it. */
|
|
43
|
+
export interface WhatsAppDeliveryOutcome {
|
|
44
|
+
/** `sent` when every message was; `failed` when none reached the person; else `uncertain`. */
|
|
45
|
+
readonly status: "sent" | "uncertain" | "failed";
|
|
46
|
+
/** The first message that reached the person. */
|
|
47
|
+
readonly messageId: string | null;
|
|
48
|
+
/** Why nothing was sent, for a `failed` delivery. */
|
|
49
|
+
readonly error?: WhatsAppDeliveryError;
|
|
50
|
+
/** Meta's refusal of a `failed` message without files, when its code names one. */
|
|
51
|
+
readonly refusal?: WhatsAppRefusal;
|
|
52
|
+
/** What became of each file, by its index, for a delivery with files. */
|
|
53
|
+
readonly files?: ReadonlyArray<ChannelDeliveredFile>;
|
|
54
|
+
/** Each original failure: Meta's answer, or the connection's error. */
|
|
55
|
+
readonly causes: ReadonlyArray<unknown>;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Sends a delivery: its one message, or its files, one message each, the caption on the first or
|
|
59
|
+
* before them. Each message's result is what Meta's answer proves.
|
|
60
|
+
*/
|
|
61
|
+
export declare function deliverWhatsApp(delivery: WhatsAppDelivery, options: {
|
|
62
|
+
readonly request: ChannelRequest;
|
|
63
|
+
}): Promise<WhatsAppDeliveryOutcome>;
|
|
64
|
+
/** The WhatsApp channel's deliver route; see {@link WHATSAPP_DELIVER_ROUTE}. */
|
|
65
|
+
export declare function whatsappDeliverRoute(options: {
|
|
66
|
+
/** The WhatsApp channel `name` the mount declares, or `null`. */
|
|
67
|
+
readonly settings: (name: string) => WhatsAppSettings | null;
|
|
68
|
+
/** The connection proxy of the channel the current request runs for, which its adapter uses. */
|
|
69
|
+
readonly proxy: () => ConnectionProxy;
|
|
70
|
+
readonly environment: Environment;
|
|
71
|
+
readonly verify: () => RuntimeTokenVerifier;
|
|
72
|
+
}): HttpRouteDefinition<ChatSdkChannelState>;
|
|
@@ -0,0 +1,225 @@
|
|
|
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, linkSecrets } from "../deliver-route.mjs";
|
|
10
|
+
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { ChannelAnswerError, WHATSAPP_DELIVER_FILES, sendWhatsAppFiles, sendWhatsAppMessage, whatsappFileRefusal } from "@segmentstream/ontology/whatsapp";
|
|
13
|
+
import { POST } from "eve/channels";
|
|
14
|
+
const WHATSAPP_DELIVER_ROUTE = "/eve/segmentstream/v1/whatsapp/:channel/deliver";
|
|
15
|
+
const WA_ID = /^[1-9][0-9]{5,19}$/u;
|
|
16
|
+
const LINK_USABLE_MS = 3e4;
|
|
17
|
+
function isRecord(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function contentOf(message) {
|
|
21
|
+
return message.type === "text" ? message.text : message.type === "interactive" ? message.interactive : message.template;
|
|
22
|
+
}
|
|
23
|
+
function errorOf(part) {
|
|
24
|
+
return part.code === "unavailable" ? "file_unavailable" : part.code === "too_large" ? "file_too_large" : part.cause instanceof ChannelAnswerError ? "provider_refused" : "connection_refused";
|
|
25
|
+
}
|
|
26
|
+
async function deliverWhatsApp(delivery, options) {
|
|
27
|
+
const { message, files } = delivery;
|
|
28
|
+
const recipient = { to: delivery.to };
|
|
29
|
+
const parts = message !== void 0 ? [await sendWhatsAppMessage({
|
|
30
|
+
request: options.request,
|
|
31
|
+
recipient,
|
|
32
|
+
type: message.type,
|
|
33
|
+
message: contentOf(message),
|
|
34
|
+
definite: definiteProxyFailure
|
|
35
|
+
})] : await sendWhatsAppFiles({
|
|
36
|
+
request: options.request,
|
|
37
|
+
recipient,
|
|
38
|
+
files,
|
|
39
|
+
...delivery.caption === void 0 ? {} : { caption: delivery.caption },
|
|
40
|
+
definite: definiteProxyFailure
|
|
41
|
+
});
|
|
42
|
+
const sent = parts.length > 0 && parts.every((part) => part.status === "sent");
|
|
43
|
+
const none = parts.every((part) => part.status === "failed");
|
|
44
|
+
const status = sent ? "sent" : none ? "failed" : "uncertain";
|
|
45
|
+
const firstFailed = parts.find((part) => part.status === "failed");
|
|
46
|
+
const refusal = message === void 0 ? void 0 : parts[0]?.refusal;
|
|
47
|
+
return {
|
|
48
|
+
status,
|
|
49
|
+
messageId: status === "failed" ? null : parts.find((part) => part.status === "sent")?.messageIds[0] ?? null,
|
|
50
|
+
...status === "failed" ? { error: firstFailed === void 0 ? "provider_refused" : errorOf(firstFailed) } : {},
|
|
51
|
+
...status === "failed" && refusal !== void 0 ? { refusal } : {},
|
|
52
|
+
...files.length === 0 ? {} : { files: files.map((_file, index) => {
|
|
53
|
+
const part = parts.find((candidate) => candidate.files.includes(index));
|
|
54
|
+
return {
|
|
55
|
+
index,
|
|
56
|
+
status: part?.status ?? "failed",
|
|
57
|
+
message_id: part?.status === "sent" ? part.messageIds[0] ?? null : null
|
|
58
|
+
};
|
|
59
|
+
}) },
|
|
60
|
+
causes: parts.flatMap((part) => part.status === "sent" || part.cause === void 0 ? [] : [part.cause])
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function text(value) {
|
|
64
|
+
return typeof value === "string" && value.trim() !== "";
|
|
65
|
+
}
|
|
66
|
+
function interactiveOf(value) {
|
|
67
|
+
if (!isRecord(value) || !isRecord(value.body) || !text(value.body.text) || !isRecord(value.action)) return;
|
|
68
|
+
const body = { text: value.body.text };
|
|
69
|
+
const { action } = value;
|
|
70
|
+
if (value.type === "cta_url") {
|
|
71
|
+
const parameters = isRecord(action.parameters) ? action.parameters : {};
|
|
72
|
+
return action.name === "cta_url" && text(parameters.display_text) && typeof parameters.url === "string" ? {
|
|
73
|
+
type: "cta_url",
|
|
74
|
+
body,
|
|
75
|
+
action: {
|
|
76
|
+
name: "cta_url",
|
|
77
|
+
parameters: {
|
|
78
|
+
display_text: parameters.display_text,
|
|
79
|
+
url: parameters.url
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
} : void 0;
|
|
83
|
+
}
|
|
84
|
+
if (value.type !== "button" || !Array.isArray(action.buttons)) return;
|
|
85
|
+
const buttons = action.buttons.map((button) => isRecord(button) && button.type === "reply" && isRecord(button.reply) && typeof button.reply.id === "string" && text(button.reply.title) ? {
|
|
86
|
+
type: "reply",
|
|
87
|
+
reply: {
|
|
88
|
+
id: button.reply.id,
|
|
89
|
+
title: button.reply.title
|
|
90
|
+
}
|
|
91
|
+
} : void 0);
|
|
92
|
+
return buttons.length > 0 && buttons.length <= 3 && buttons.every((button) => button !== void 0) ? {
|
|
93
|
+
type: "button",
|
|
94
|
+
body,
|
|
95
|
+
action: { buttons }
|
|
96
|
+
} : void 0;
|
|
97
|
+
}
|
|
98
|
+
function templateOf(value) {
|
|
99
|
+
if (!isRecord(value) || !text(value.name) || !isRecord(value.language) || !text(value.language.code) || value.components !== void 0 && (!Array.isArray(value.components) || !value.components.every(isRecord))) return;
|
|
100
|
+
return {
|
|
101
|
+
name: value.name,
|
|
102
|
+
language: { code: value.language.code },
|
|
103
|
+
...value.components === void 0 ? {} : { components: value.components }
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function messageOf(value) {
|
|
107
|
+
if (!isRecord(value)) return;
|
|
108
|
+
if (value.type === "text") {
|
|
109
|
+
const body = isRecord(value.text) ? value.text : {};
|
|
110
|
+
return text(body.body) && typeof body.preview_url === "boolean" ? {
|
|
111
|
+
type: "text",
|
|
112
|
+
text: {
|
|
113
|
+
body: body.body,
|
|
114
|
+
preview_url: body.preview_url
|
|
115
|
+
}
|
|
116
|
+
} : void 0;
|
|
117
|
+
}
|
|
118
|
+
if (value.type === "interactive") {
|
|
119
|
+
const interactive = interactiveOf(value.interactive);
|
|
120
|
+
return interactive === void 0 ? void 0 : {
|
|
121
|
+
type: "interactive",
|
|
122
|
+
interactive
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
if (value.type === "template") {
|
|
126
|
+
const template = templateOf(value.template);
|
|
127
|
+
return template === void 0 ? void 0 : {
|
|
128
|
+
type: "template",
|
|
129
|
+
template
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function deliveryOf(body) {
|
|
134
|
+
const files = body.files === void 0 ? [] : body.files;
|
|
135
|
+
const message = body.message === void 0 ? void 0 : messageOf(body.message);
|
|
136
|
+
if (typeof body.operation_id !== "string" || body.operation_id === "" || body.operation_id.length > 512 || typeof body.connection !== "string" || typeof body.to !== "string" || !WA_ID.test(body.to) || !Array.isArray(files) || files.length > WHATSAPP_DELIVER_FILES || !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://")) || body.caption !== void 0 && !text(body.caption) || (body.message === void 0 ? files.length === 0 : message === void 0 || files.length > 0 || body.caption !== void 0)) return;
|
|
137
|
+
return {
|
|
138
|
+
operationId: body.operation_id,
|
|
139
|
+
connection: body.connection,
|
|
140
|
+
to: body.to,
|
|
141
|
+
...message === void 0 ? {} : { message },
|
|
142
|
+
...body.caption === void 0 ? {} : { caption: body.caption },
|
|
143
|
+
files: files.map((file) => ({
|
|
144
|
+
filename: file.filename,
|
|
145
|
+
contentType: file.content_type,
|
|
146
|
+
size: file.size,
|
|
147
|
+
url: file.url
|
|
148
|
+
}))
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function linksOf(value) {
|
|
152
|
+
if (Array.isArray(value)) return value.flatMap(linksOf);
|
|
153
|
+
if (!isRecord(value)) return [];
|
|
154
|
+
return Object.entries(value).flatMap(([name, item]) => name === "link" && typeof item === "string" ? [item] : linksOf(item));
|
|
155
|
+
}
|
|
156
|
+
function reportWhatsAppError(operation, error, metadata, secrets) {
|
|
157
|
+
const reference = randomUUID();
|
|
158
|
+
console.error("[segmentstream] WhatsApp delivery diagnostic", {
|
|
159
|
+
...redactDiagnostic(metadata, secrets),
|
|
160
|
+
operation,
|
|
161
|
+
reference,
|
|
162
|
+
error: redactDiagnostic(error, secrets)
|
|
163
|
+
});
|
|
164
|
+
return reference;
|
|
165
|
+
}
|
|
166
|
+
function whatsappDeliverRoute(options) {
|
|
167
|
+
return POST(WHATSAPP_DELIVER_ROUTE, async (request, args) => {
|
|
168
|
+
const received = Date.now();
|
|
169
|
+
const read = await deliverRequest(request, args.params, {
|
|
170
|
+
environment: options.environment,
|
|
171
|
+
verify: options.verify,
|
|
172
|
+
declared: (name) => options.settings(name) !== null
|
|
173
|
+
});
|
|
174
|
+
if ("failure" in read) return read.failure;
|
|
175
|
+
const { channel } = read;
|
|
176
|
+
const named = deliveryOf(read.body);
|
|
177
|
+
if (named === void 0) return deliverError("invalid_request", 400);
|
|
178
|
+
const connection = options.settings(channel)?.connection;
|
|
179
|
+
if (connection === void 0 || named.connection !== connection) return deliverError("channel_unknown", 422);
|
|
180
|
+
for (const file of named.files) {
|
|
181
|
+
const refusal = whatsappFileRefusal(file);
|
|
182
|
+
if (refusal !== void 0) return deliverError(refusal.code === "empty" ? "files_unsupported" : "file_too_large", 422);
|
|
183
|
+
}
|
|
184
|
+
const metadata = {
|
|
185
|
+
operationId: named.operationId,
|
|
186
|
+
channel
|
|
187
|
+
};
|
|
188
|
+
const secrets = new Set([...named.files.flatMap((file) => linkSecrets(file.url)), ...linksOf(named.message).flatMap(linkSecrets)]);
|
|
189
|
+
const files = named.files.map((file, index) => ({
|
|
190
|
+
index,
|
|
191
|
+
filename: file.filename,
|
|
192
|
+
contentType: file.contentType,
|
|
193
|
+
link: async () => {
|
|
194
|
+
if (Date.now() - received > LINK_USABLE_MS) throw new Error("The file's link is too old to hand WhatsApp: it may expire first.");
|
|
195
|
+
return file.url;
|
|
196
|
+
}
|
|
197
|
+
}));
|
|
198
|
+
return inChannel("whatsapp", channel, async () => {
|
|
199
|
+
const proxy = options.proxy();
|
|
200
|
+
try {
|
|
201
|
+
const outcome = await deliverWhatsApp({
|
|
202
|
+
to: named.to,
|
|
203
|
+
...named.message === void 0 ? {} : { message: named.message },
|
|
204
|
+
...named.caption === void 0 ? {} : { caption: named.caption },
|
|
205
|
+
files
|
|
206
|
+
}, { request: (call) => proxy.request(call) });
|
|
207
|
+
const reference = outcome.causes.length === 0 ? void 0 : reportWhatsAppError(`whatsapp_deliver_${outcome.status}`, outcome.causes.length === 1 ? outcome.causes[0] : new AggregateError(outcome.causes, "Parts of the message were not sent."), metadata, secrets);
|
|
208
|
+
if (outcome.status === "failed") return deliverError(outcome.error ?? "provider_refused", 422, {
|
|
209
|
+
...outcome.refusal === void 0 ? {} : { refusal: outcome.refusal },
|
|
210
|
+
...reference === void 0 ? {} : { reference }
|
|
211
|
+
});
|
|
212
|
+
return Response.json({
|
|
213
|
+
status: outcome.status,
|
|
214
|
+
message_id: outcome.messageId,
|
|
215
|
+
...outcome.files === void 0 ? {} : { files: outcome.files },
|
|
216
|
+
...reference === void 0 ? {} : { reference }
|
|
217
|
+
});
|
|
218
|
+
} catch (cause) {
|
|
219
|
+
const reference = reportWhatsAppError("whatsapp_deliver_failed", cause, metadata, secrets);
|
|
220
|
+
return deliverError("send_failed", 502, { reference });
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
export { WHATSAPP_DELIVER_ROUTE, deliverWhatsApp, whatsappDeliverRoute };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.106.0",
|
|
4
4
|
"description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SegmentStream",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"@chat-adapter/state-memory": "4.42.0",
|
|
90
90
|
"@chat-adapter/telegram": "4.41.0",
|
|
91
91
|
"@chat-adapter/whatsapp": "4.42.0",
|
|
92
|
-
"@segmentstream/ontology": "0.
|
|
92
|
+
"@segmentstream/ontology": "0.185.0",
|
|
93
93
|
"@vercel/oidc": "^3.8.4",
|
|
94
94
|
"ai": "^7.0.172",
|
|
95
95
|
"chat": "4.42.0",
|