@segmentstream/agent 0.93.0 → 0.94.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 +36 -0
- package/dist/_chunks/{build-metadata-CP0iLqzp.mjs → build-metadata-Da-608Iv.mjs} +1 -1
- package/dist/extension/config.d.ts +15 -0
- package/dist/extension/config.mjs +34 -2
- package/dist/extension/lib/attachments-dispatch.mjs +2 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/email/attachments-send.d.ts +3 -0
- package/dist/extension/lib/email/attachments-send.mjs +4 -2
- package/dist/extension/lib/email/channel.d.ts +8 -0
- package/dist/extension/lib/email/channel.mjs +108 -9
- package/dist/extension/lib/email/gmail.d.ts +18 -4
- package/dist/extension/lib/email/gmail.mjs +38 -8
- package/dist/extension/lib/email/quote-settings.d.ts +19 -0
- package/dist/extension/lib/email/quote-settings.mjs +32 -0
- package/dist/extension/lib/email/quote.d.ts +41 -0
- package/dist/extension/lib/email/quote.mjs +96 -0
- package/dist/extension/lib/telegram/adapter.mjs +2 -2
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,41 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.94.0
|
|
4
|
+
|
|
5
|
+
The ontology's replies to mail, a draft a member approves and a staff reply from the inbox, are
|
|
6
|
+
handed to the agent's email channel of the chat's name, which sends them as its own replies: in the
|
|
7
|
+
thread, from the mailbox, keyed so a lost answer is never sent twice, and signed and quoted by the
|
|
8
|
+
channel's `signature` and `quote`, so every reply from the mailbox looks the same. The reply's files
|
|
9
|
+
go by short-lived links to the workspace's file storage, checked against the revision the draft
|
|
10
|
+
holds before anything is reserved; the channel refuses a file whose size differs and sends nothing.
|
|
11
|
+
The channel serves this at `POST /eve/segmentstream/v1/email/<name>/deliver`, for the deployment's
|
|
12
|
+
own functions only.
|
|
13
|
+
|
|
14
|
+
An agent from before the route answers 404, and the ontology sends the reply from the mailbox
|
|
15
|
+
itself, as before: signed by `signature` on its `chat` entry and never quoted.
|
|
16
|
+
|
|
17
|
+
Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and set
|
|
18
|
+
`signature` (and `quote`, if wanted) on `channels.email` in `agent/segmentstream.json`. The
|
|
19
|
+
ontology's `chat.email.signature` now signs only replies sent for an agent from before the route; it
|
|
20
|
+
is deprecated and stops working on 2027-05-27.
|
|
21
|
+
|
|
22
|
+
The email channel takes `quote` in `agent/segmentstream.json`: each reply the agent sends from the
|
|
23
|
+
mailbox, files included, quotes under its text and signature the mail it answers, in Gmail's
|
|
24
|
+
markup, with `> ` lines in its plain-text part. `attribution` is the line above the quote in the
|
|
25
|
+
workspace's own words, with `{from}`, `{date}` and `{time}`, written in `locale` and `timeZone`:
|
|
26
|
+
|
|
27
|
+
```json
|
|
28
|
+
"quote": { "attribution": "On {date} at {time}, {from} wrote:", "locale": "en-GB", "timeZone": "Europe/Madrid" }
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The quoted mail is read with Gmail's `messages.get` in its `full` format, without its files; a mail
|
|
32
|
+
Gmail does not return, or one too long to carry, leaves the reply unquoted and the deployment's logs
|
|
33
|
+
say why. Only the message sent carries the quote: the chat keeps the reply as written. Drafts a
|
|
34
|
+
member approves and staff replies from the inbox, which the ontology sends, do not quote yet. Off
|
|
35
|
+
when absent.
|
|
36
|
+
|
|
37
|
+
Pins @segmentstream/ontology 0.176.0.
|
|
38
|
+
|
|
3
39
|
## 0.93.0
|
|
4
40
|
|
|
5
41
|
Allow workspace operators to enable bounded, tool-free answers to unlinked senders in individual Telegram and Slack group chats. Dedicated connections can use a verified inviter's existing permission to open a newly joined group.
|
|
@@ -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.94.0";
|
|
8
8
|
function agentBuild(environment = process.env) {
|
|
9
9
|
return {
|
|
10
10
|
agent: version,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type GroupPolicyInput } from "@segmentstream/ontology/groups";
|
|
2
2
|
import { type GroupPolicy } from "./lib/group-routing/policy.js";
|
|
3
|
+
import { type QuoteSettings } from "./lib/email/quote-settings.js";
|
|
3
4
|
import { type StructuredInbound } from "./lib/telegram/structured-settings.js";
|
|
4
5
|
import type { WorkspaceActionHook } from "./lib/workspace-action.js";
|
|
5
6
|
import { type TelegramTexts } from "./lib/telegram/texts.js";
|
|
@@ -344,6 +345,18 @@ export interface EmailChannelInput {
|
|
|
344
345
|
* (`reply` cannot be `sender` with it).
|
|
345
346
|
*/
|
|
346
347
|
readonly chats?: "sender" | "thread";
|
|
348
|
+
/** Whether the agent's replies end with the mailbox's own signature, as its owner set it in Gmail. */
|
|
349
|
+
readonly signature?: boolean;
|
|
350
|
+
/**
|
|
351
|
+
* The mail a reply answers, quoted under it as Gmail quotes it: `attribution` is the line above
|
|
352
|
+
* the quote in the workspace's words, with `{from}`, `{date}` and `{time}`, written in `locale`
|
|
353
|
+
* and `timeZone`. No quote when absent.
|
|
354
|
+
*/
|
|
355
|
+
readonly quote?: {
|
|
356
|
+
readonly attribution: string;
|
|
357
|
+
readonly locale: string;
|
|
358
|
+
readonly timeZone: string;
|
|
359
|
+
};
|
|
347
360
|
}
|
|
348
361
|
/**
|
|
349
362
|
* A channel the workspace defines in its own code, `defineChannel` in `agent/agent/channels/`,
|
|
@@ -660,6 +673,8 @@ export interface EmailSettings {
|
|
|
660
673
|
readonly chats?: "thread";
|
|
661
674
|
/** `true` when the agent's replies end with the mailbox's own signature; absent, they do not. */
|
|
662
675
|
readonly signature?: true;
|
|
676
|
+
/** How the agent's replies quote the mail they answer; absent, they quote nothing. */
|
|
677
|
+
readonly quote?: QuoteSettings;
|
|
663
678
|
}
|
|
664
679
|
/**
|
|
665
680
|
* A channel the workspace defines in its own code (`defineChannel`): the connection its code calls
|
|
@@ -6,6 +6,7 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { effectiveGroupPolicy, groupPolicy, ignoredGroupSettings, inapplicableGroupThresholds } from "./lib/group-routing/policy.mjs";
|
|
8
8
|
import { localizedText as localizedText$1 } from "./lib/admission.mjs";
|
|
9
|
+
import { quoteSettingsIssue } from "./lib/email/quote-settings.mjs";
|
|
9
10
|
import { STRUCTURED_KINDS } from "./lib/telegram/structured-settings.mjs";
|
|
10
11
|
import { TELEGRAM_TEXT_KEYS } from "./lib/telegram/texts.mjs";
|
|
11
12
|
import { IDENTIFIER_POLICIES, isTechnicalText } from "./lib/customer-text-safety.mjs";
|
|
@@ -426,7 +427,8 @@ function emailSettings(value, issues, path = ["channels", "email"]) {
|
|
|
426
427
|
"recordQuery",
|
|
427
428
|
"reply",
|
|
428
429
|
"chats",
|
|
429
|
-
"signature"
|
|
430
|
+
"signature",
|
|
431
|
+
"quote"
|
|
430
432
|
],
|
|
431
433
|
issues
|
|
432
434
|
});
|
|
@@ -491,6 +493,31 @@ function emailSettings(value, issues, path = ["channels", "email"]) {
|
|
|
491
493
|
message: "must be true or false",
|
|
492
494
|
path: [...path, "signature"]
|
|
493
495
|
});
|
|
496
|
+
const quote = email.quote === void 0 ? void 0 : section({
|
|
497
|
+
value: email.quote,
|
|
498
|
+
path: [...path, "quote"],
|
|
499
|
+
allowed: [
|
|
500
|
+
"attribution",
|
|
501
|
+
"locale",
|
|
502
|
+
"timeZone"
|
|
503
|
+
],
|
|
504
|
+
issues
|
|
505
|
+
});
|
|
506
|
+
for (const key of [
|
|
507
|
+
"attribution",
|
|
508
|
+
"locale",
|
|
509
|
+
"timeZone"
|
|
510
|
+
]) {
|
|
511
|
+
const issue = quote === void 0 ? void 0 : quoteSettingsIssue(key, quote[key]);
|
|
512
|
+
if (issue !== void 0) issues.push({
|
|
513
|
+
message: issue,
|
|
514
|
+
path: [
|
|
515
|
+
...path,
|
|
516
|
+
"quote",
|
|
517
|
+
key
|
|
518
|
+
]
|
|
519
|
+
});
|
|
520
|
+
}
|
|
494
521
|
if (issues.length > before) return null;
|
|
495
522
|
return {
|
|
496
523
|
connection: email.connection,
|
|
@@ -503,7 +530,12 @@ function emailSettings(value, issues, path = ["channels", "email"]) {
|
|
|
503
530
|
} : {},
|
|
504
531
|
...reply === "all" ? { reply: "all" } : {},
|
|
505
532
|
...chats === "thread" ? { chats: "thread" } : {},
|
|
506
|
-
...email.signature === true ? { signature: true } : {}
|
|
533
|
+
...email.signature === true ? { signature: true } : {},
|
|
534
|
+
...quote === void 0 ? {} : { quote: {
|
|
535
|
+
attribution: quote.attribution.trim(),
|
|
536
|
+
locale: quote.locale.trim(),
|
|
537
|
+
timeZone: quote.timeZone.trim()
|
|
538
|
+
} }
|
|
507
539
|
};
|
|
508
540
|
}
|
|
509
541
|
function telegramSettings(value, issues, path = ["channels", "telegram"]) {
|
|
@@ -32,7 +32,8 @@ async function sendStoredFiles(input) {
|
|
|
32
32
|
callId: input.callId,
|
|
33
33
|
connection: channelOf(channels, "email", name)?.connection,
|
|
34
34
|
cc: replyCopies(principal, channelOf(channels, "email", name)),
|
|
35
|
-
signature: channelOf(channels, "email", name)?.signature === true
|
|
35
|
+
signature: channelOf(channels, "email", name)?.signature === true,
|
|
36
|
+
quote: channelOf(channels, "email", name)?.quote
|
|
36
37
|
});
|
|
37
38
|
if (provider === "whatsapp") return sendWhatsAppAttachments({
|
|
38
39
|
...options,
|
|
@@ -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-Da-608Iv.mjs";
|
|
@@ -4,6 +4,7 @@ import { type Environment } from "../environment.js";
|
|
|
4
4
|
import type { RuntimeToken } from "../runtime-token.js";
|
|
5
5
|
import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
|
|
6
6
|
import { type Gmail } from "./gmail.js";
|
|
7
|
+
import type { QuoteSettings } from "./quote-settings.js";
|
|
7
8
|
/**
|
|
8
9
|
* `attachments_send` in an email chat: the stored files go in one reply in the person's Gmail
|
|
9
10
|
* thread, from the channel's mailbox, to the people the channel's text replies go to: under the
|
|
@@ -38,6 +39,8 @@ export declare function sendEmailAttachments(options: {
|
|
|
38
39
|
readonly cc?: ReadonlyArray<string>;
|
|
39
40
|
/** Whether the reply ends with the mailbox's own signature, as the channel's text replies do. */
|
|
40
41
|
readonly signature?: boolean;
|
|
42
|
+
/** How the reply quotes the mail it answers, as the channel's text replies do; none when absent. */
|
|
43
|
+
readonly quote?: QuoteSettings;
|
|
41
44
|
readonly environment?: Environment;
|
|
42
45
|
readonly token?: RuntimeToken;
|
|
43
46
|
readonly fetch?: typeof fetch;
|
|
@@ -10,7 +10,7 @@ import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
|
|
|
10
10
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
11
11
|
import { proxyEnvironment } from "../environment.mjs";
|
|
12
12
|
import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
|
|
13
|
-
import { GmailError, gmail, replyKeyOf } from "./gmail.mjs";
|
|
13
|
+
import { GmailError, ReplyNotSent, gmail, replyKeyOf } from "./gmail.mjs";
|
|
14
14
|
import { randomUUID } from "node:crypto";
|
|
15
15
|
import { EMAIL_FILES_BYTES } from "@segmentstream/ontology/email";
|
|
16
16
|
const MAXIMUM_EMAIL_ATTACHMENT_BYTES = EMAIL_FILES_BYTES;
|
|
@@ -25,7 +25,8 @@ function reportEmailError(operation, error, secrets) {
|
|
|
25
25
|
return reference;
|
|
26
26
|
}
|
|
27
27
|
function sendFailure(error) {
|
|
28
|
-
const
|
|
28
|
+
const original = error instanceof ReplyNotSent ? error.cause : error;
|
|
29
|
+
const code = original instanceof GmailError ? original.status === 413 ? "too_large" : original.status === 401 || original.status === 403 ? "forbidden" : "send_failed" : original instanceof ConnectionProxyError && original.code === "invalid_request" ? "too_large" : "send_failed";
|
|
29
30
|
return new AttachmentError({
|
|
30
31
|
code,
|
|
31
32
|
message: "Gmail did not take the reply.",
|
|
@@ -107,6 +108,7 @@ async function sendEmailAttachments(options) {
|
|
|
107
108
|
text: input.caption ?? "",
|
|
108
109
|
key: replyKeyOf(options.sessionId, options.callId, "files"),
|
|
109
110
|
...options.signature === true ? { signature: true } : {},
|
|
111
|
+
...options.quote === void 0 ? {} : { quote: options.quote },
|
|
110
112
|
attachments: read.map(({ file }) => ({
|
|
111
113
|
filename: file.filename,
|
|
112
114
|
contentType: file.contentType,
|
|
@@ -11,6 +11,7 @@ import { type ImageDescriber } from "../inbound-media/images.js";
|
|
|
11
11
|
import { type Transcriber } from "../inbound-media/speech.js";
|
|
12
12
|
import { channelReview } from "../review/reply.js";
|
|
13
13
|
import type { ReviewDecideFunction } from "../review/judge.js";
|
|
14
|
+
import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
14
15
|
import { type RuntimeToken } from "../runtime-token.js";
|
|
15
16
|
import { type Gmail } from "./gmail.js";
|
|
16
17
|
/**
|
|
@@ -38,6 +39,11 @@ import { type Gmail } from "./gmail.js";
|
|
|
38
39
|
*/
|
|
39
40
|
/** Where SegmentStream wakes the channel named `email`; another email channel adds its name. */
|
|
40
41
|
export declare const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
|
|
42
|
+
/**
|
|
43
|
+
* Where the ontology hands an email channel, by its name (`email` for the channel named after its
|
|
44
|
+
* kind), a reply to send from its mailbox: `emailDeliverRoute(name)` of the ontology SDK.
|
|
45
|
+
*/
|
|
46
|
+
export declare const EMAIL_DELIVER_ROUTE = "/eve/segmentstream/v1/email/:channel/deliver";
|
|
41
47
|
/** The authenticator of an email session's principal. */
|
|
42
48
|
export declare const EMAIL_AUTHENTICATOR = "segmentstream-email";
|
|
43
49
|
/**
|
|
@@ -76,6 +82,8 @@ export interface EmailChannelOptions {
|
|
|
76
82
|
readonly now?: () => number;
|
|
77
83
|
/** Waits between attempts to send a reply; tests pass one that does not wait. */
|
|
78
84
|
readonly sleep?: (ms: number) => Promise<void>;
|
|
85
|
+
/** Verifies the deployment's own token on the deliver route; tests pass their own. */
|
|
86
|
+
readonly verify?: RuntimeTokenVerifier;
|
|
79
87
|
}
|
|
80
88
|
/**
|
|
81
89
|
* One person's private chat in a Gmail thread: the thread and the sender's address. Two people who
|
|
@@ -4,32 +4,36 @@ 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 { PUBSUB_TOPIC } from "../../config.mjs";
|
|
7
|
+
import { CHANNEL_NAME, 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";
|
|
11
11
|
import { Bt as participantsOf, Ft as chatAddressOf, Mt as PARTICIPANTS_ATTRIBUTE, S as fetchStoredAttachment, Vt as withChatAddress, b as agentAttachments, d as prepareInboundMedia, i as memberIdOf, m as turnContent } from "../../../_chunks/principal-DL9NdRRP.mjs";
|
|
12
|
-
import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
|
|
12
|
+
import { channelAttributes, currentChannel, currentKey, inChannel, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
|
|
13
13
|
import { a as chatEvent, b as messageInput, d as replyRecipients, g as UNVERIFIED, l as replyEvent, p as storeOf, r as chatArchive, t as AGENT_SENDER } from "../../../_chunks/chat-archive-_IBU0CXG.mjs";
|
|
14
14
|
import { ChatStoreError } from "../chat-store.mjs";
|
|
15
15
|
import { recordChatMessage, recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
|
|
16
16
|
import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
|
|
17
17
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
18
|
-
import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
|
|
18
|
+
import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
|
|
19
19
|
import { AgentIdentityError, agentIdentities } from "../identities.mjs";
|
|
20
20
|
import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
|
|
21
21
|
import { gatewayImageDescriber } from "../inbound-media/images.mjs";
|
|
22
22
|
import { gatewayTranscriber } from "../inbound-media/speech.mjs";
|
|
23
23
|
import { channelReview } from "../review/reply.mjs";
|
|
24
24
|
import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-xJcJ8SNJ.mjs";
|
|
25
|
+
import { runtimeTokenVerifier } from "../runtime-identity.mjs";
|
|
25
26
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
26
|
-
import {
|
|
27
|
+
import { runtimeRequestFailure } from "../telegram/runtime-request.mjs";
|
|
28
|
+
import { GMAIL_ID, GmailError, ReplyNotSent, gmail, replyKeyOf } from "./gmail.mjs";
|
|
27
29
|
import { inboundMail, parseMail, sentMail } from "./message.mjs";
|
|
28
30
|
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
29
31
|
import { reply } from "eve/events";
|
|
30
32
|
import { POST, defineChannel } from "eve/channels";
|
|
31
|
-
import { EMAIL_RECIPIENTS_LIMIT, REPLY_KEY_HEADER, isEmailAddress } from "@segmentstream/ontology/email";
|
|
33
|
+
import { EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, EMAIL_RECIPIENTS_LIMIT, GmailMaybeSent, REPLY_KEY as REPLY_KEY$1, REPLY_KEY_HEADER, isEmailAddress } from "@segmentstream/ontology/email";
|
|
32
34
|
const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
|
|
35
|
+
const EMAIL_DELIVER_ROUTE = `${EMAIL_ROUTE}/:channel/deliver`;
|
|
36
|
+
const DELIVER_FILE_TIMEOUT_MS = 3e4;
|
|
33
37
|
const EMAIL_AUTHENTICATOR = "segmentstream-email";
|
|
34
38
|
const MESSAGES_PER_WAKE = 20;
|
|
35
39
|
const WATCH_RENEW_MS = 864e5;
|
|
@@ -79,6 +83,7 @@ var UnreadableMail = class extends Error {
|
|
|
79
83
|
name = "UnreadableMail";
|
|
80
84
|
};
|
|
81
85
|
function retryable(error) {
|
|
86
|
+
if (error instanceof ReplyNotSent) return retryable(error.cause);
|
|
82
87
|
if (error instanceof UnreadableMail) return false;
|
|
83
88
|
if (error instanceof GmailError) return error.status === 408 || error.status === 429 || error.status >= 500;
|
|
84
89
|
if (error instanceof ConnectionProxyError) return error.code !== "too_large" && error.code !== "invalid_request";
|
|
@@ -237,7 +242,13 @@ function emailChannelDefinition(options) {
|
|
|
237
242
|
environment,
|
|
238
243
|
...transport
|
|
239
244
|
});
|
|
240
|
-
const withSignature = () =>
|
|
245
|
+
const withSignature = () => {
|
|
246
|
+
const current = settings();
|
|
247
|
+
return {
|
|
248
|
+
...current?.signature === true ? { signature: true } : {},
|
|
249
|
+
...current?.quote === void 0 ? {} : { quote: current.quote }
|
|
250
|
+
};
|
|
251
|
+
};
|
|
241
252
|
const archive = () => chats ??= chatArchive({
|
|
242
253
|
environment,
|
|
243
254
|
...transport
|
|
@@ -1015,12 +1026,100 @@ function emailChannelDefinition(options) {
|
|
|
1015
1026
|
});
|
|
1016
1027
|
}
|
|
1017
1028
|
} });
|
|
1029
|
+
let verifier = options.verify;
|
|
1030
|
+
async function linkedFile(file) {
|
|
1031
|
+
const response = await (transport.fetch ?? fetch)(file.url, {
|
|
1032
|
+
redirect: "error",
|
|
1033
|
+
signal: AbortSignal.timeout(DELIVER_FILE_TIMEOUT_MS)
|
|
1034
|
+
});
|
|
1035
|
+
if (!response.ok) {
|
|
1036
|
+
await response.body?.cancel();
|
|
1037
|
+
throw new Error(`The file storage answered with status ${response.status}.`);
|
|
1038
|
+
}
|
|
1039
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1040
|
+
if (bytes.byteLength !== file.size) throw new Error(`The file read has ${bytes.byteLength} bytes, not the ${file.size} named.`);
|
|
1041
|
+
return bytes;
|
|
1042
|
+
}
|
|
1043
|
+
async function deliverRoute(request, args) {
|
|
1044
|
+
const failure = await runtimeRequestFailure(request, {
|
|
1045
|
+
enabled: () => true,
|
|
1046
|
+
configured: () => channelsEnabled(environment),
|
|
1047
|
+
verify: () => verifier ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment))
|
|
1048
|
+
});
|
|
1049
|
+
if (failure !== void 0) return failure;
|
|
1050
|
+
const name = args.params.channel ?? "";
|
|
1051
|
+
if (!CHANNEL_NAME.test(name) || options.settings(name) === null) return Response.json({ error: "channel_unknown" }, { status: 422 });
|
|
1052
|
+
let body;
|
|
1053
|
+
try {
|
|
1054
|
+
const value = await request.json();
|
|
1055
|
+
body = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
1056
|
+
} catch {
|
|
1057
|
+
return Response.json({ error: "invalid_request" }, { status: 400 });
|
|
1058
|
+
}
|
|
1059
|
+
const addresses = (value) => Array.isArray(value) && value.every((address) => typeof address === "string" && isEmailAddress(address)) ? value : void 0;
|
|
1060
|
+
const to = addresses(body.to);
|
|
1061
|
+
const cc = addresses(body.cc ?? []);
|
|
1062
|
+
const files = body.files === void 0 ? [] : body.files;
|
|
1063
|
+
if (typeof body.thread_id !== "string" || !GMAIL_ID.test(body.thread_id) || to === void 0 || to.length === 0 || cc === void 0 || to.length + cc.length > EMAIL_RECIPIENTS_LIMIT || typeof body.text !== "string" || body.text.length > EMAIL_MESSAGE_LIMIT || typeof body.key !== "string" || !REPLY_KEY$1.test(body.key) || !Array.isArray(files) || !files.every((file) => typeof file === "object" && file !== null && typeof file.filename === "string" && typeof file.content_type === "string" && Number.isSafeInteger(file.size) && typeof file.url === "string" && file.url.startsWith("https://"))) return Response.json({ error: "invalid_request" }, { status: 400 });
|
|
1064
|
+
const named = files;
|
|
1065
|
+
if (named.reduce((total, file) => total + file.size, 0) > EMAIL_FILES_BYTES) return Response.json({ error: "file_too_large" }, { status: 422 });
|
|
1066
|
+
const threadId = body.thread_id;
|
|
1067
|
+
const text = body.text;
|
|
1068
|
+
const key = body.key;
|
|
1069
|
+
return inChannel("email", name, async () => {
|
|
1070
|
+
const report = (operation, cause) => {
|
|
1071
|
+
const reference = randomUUID();
|
|
1072
|
+
log("[segmentstream] email delivery diagnostic", {
|
|
1073
|
+
operation,
|
|
1074
|
+
reference,
|
|
1075
|
+
error: redactDiagnostic(cause, new Set())
|
|
1076
|
+
});
|
|
1077
|
+
return reference;
|
|
1078
|
+
};
|
|
1079
|
+
const attachments = [];
|
|
1080
|
+
for (const file of named) try {
|
|
1081
|
+
attachments.push({
|
|
1082
|
+
filename: file.filename,
|
|
1083
|
+
contentType: file.content_type,
|
|
1084
|
+
bytes: await linkedFile(file)
|
|
1085
|
+
});
|
|
1086
|
+
} catch (cause) {
|
|
1087
|
+
report("file_unavailable", cause);
|
|
1088
|
+
return Response.json({ error: "file_unavailable" }, { status: 422 });
|
|
1089
|
+
}
|
|
1090
|
+
try {
|
|
1091
|
+
const id = await mailbox().reply({
|
|
1092
|
+
threadId,
|
|
1093
|
+
to,
|
|
1094
|
+
...cc.length === 0 ? {} : { cc },
|
|
1095
|
+
text,
|
|
1096
|
+
key,
|
|
1097
|
+
...attachments.length === 0 ? {} : { attachments },
|
|
1098
|
+
...withSignature()
|
|
1099
|
+
});
|
|
1100
|
+
return Response.json({ message_id: id === "" ? null : id });
|
|
1101
|
+
} catch (cause) {
|
|
1102
|
+
const reference = report("deliver_failed", cause);
|
|
1103
|
+
if (cause instanceof ReplyNotSent) return Response.json({
|
|
1104
|
+
error: "thread_unavailable",
|
|
1105
|
+
reference
|
|
1106
|
+
}, { status: 422 });
|
|
1107
|
+
return cause instanceof GmailError && !(cause instanceof GmailMaybeSent) && cause.status >= 400 && cause.status < 500 && cause.status !== 408 && cause.status !== 429 ? Response.json({
|
|
1108
|
+
error: "provider_refused",
|
|
1109
|
+
reference
|
|
1110
|
+
}, { status: 422 }) : Response.json({
|
|
1111
|
+
error: "send_failed",
|
|
1112
|
+
reference
|
|
1113
|
+
}, { status: 502 });
|
|
1114
|
+
}
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1018
1117
|
return {
|
|
1019
|
-
routes: withNamedRoutes("email", [POST(EMAIL_ROUTE, wake)], (name) => {
|
|
1118
|
+
routes: [...withNamedRoutes("email", [POST(EMAIL_ROUTE, wake)], (name) => {
|
|
1020
1119
|
return options.settings(name) !== null;
|
|
1021
|
-
}),
|
|
1120
|
+
}), POST(EMAIL_DELIVER_ROUTE, deliverRoute)],
|
|
1022
1121
|
events,
|
|
1023
1122
|
fetchFile: (url, context) => fetchStoredAttachment(files(), url, context)
|
|
1024
1123
|
};
|
|
1025
1124
|
}
|
|
1026
|
-
export { EMAIL_AUTHENTICATOR, EMAIL_OTHERS_ATTRIBUTE, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailChatOf, emailPrincipal, replyCopies, segmentstreamEmail };
|
|
1125
|
+
export { EMAIL_AUTHENTICATOR, EMAIL_DELIVER_ROUTE, EMAIL_OTHERS_ATTRIBUTE, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailChatOf, emailPrincipal, replyCopies, segmentstreamEmail };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { GmailError, type EmailAttachment } from "@segmentstream/ontology/email";
|
|
2
2
|
import type { ConnectionProxy } from "../connection-proxy.js";
|
|
3
|
+
import { type QuoteSettings } from "./quote.js";
|
|
3
4
|
/**
|
|
4
5
|
* The mailbox of a `GmailConnection`, through SegmentStream's connection proxy: the calls the email
|
|
5
6
|
* channel makes, each one Gmail API request on `users/me`.
|
|
@@ -18,6 +19,14 @@ export declare function replyKeyOf(...parts: ReadonlyArray<string>): string;
|
|
|
18
19
|
* channel redacts it where it logs. The ontology's Gmail sender throws the same error.
|
|
19
20
|
*/
|
|
20
21
|
export { GmailError };
|
|
22
|
+
/**
|
|
23
|
+
* A reply that failed before Gmail was asked to send it, as when Gmail did not return the thread:
|
|
24
|
+
* nothing was sent. `cause` is the original failure, which says whether trying again may pass.
|
|
25
|
+
*/
|
|
26
|
+
export declare class ReplyNotSent extends Error {
|
|
27
|
+
readonly name = "ReplyNotSent";
|
|
28
|
+
constructor(cause: unknown);
|
|
29
|
+
}
|
|
21
30
|
/** A message the mailbox received since the cursor, as its history names it. */
|
|
22
31
|
export interface AddedMessage {
|
|
23
32
|
readonly id: string;
|
|
@@ -66,22 +75,27 @@ export interface Gmail {
|
|
|
66
75
|
/** Asks Gmail to push the mailbox's changes to `topic`; resolves the watch's expiry. */
|
|
67
76
|
watch(topic: string): Promise<number>;
|
|
68
77
|
/**
|
|
69
|
-
* Replies in `threadId` to `to`, copying `cc`, under the thread's last
|
|
70
|
-
* Markdown as HTML and as plain text and the files after it, marked
|
|
78
|
+
* Replies in `threadId` to `to`, copying `cc`, under the thread's last mail, a draft never, with
|
|
79
|
+
* the reply's Markdown as HTML and as plain text and the files after it, marked
|
|
71
80
|
* `Auto-Submitted: auto-replied`. Resolves the sent message's id. With `key`, a message in the
|
|
72
81
|
* thread that already carries it is the reply, sent by an earlier attempt whose answer was lost:
|
|
73
82
|
* its id is returned and nothing is sent. With `signature`, the HTML ends with the mailbox's own
|
|
74
|
-
* signature, read from Gmail and kept a while per mailbox; a refused read sends it unsigned.
|
|
83
|
+
* signature, read from Gmail and kept a while per mailbox; a refused read sends it unsigned. With
|
|
84
|
+
* `quote`, the mail the reply threads under is quoted after it, in the workspace's words; a mail
|
|
85
|
+
* Gmail does not return sends the reply unquoted. A thread Gmail does not return fails with
|
|
86
|
+
* {@link ReplyNotSent}: nothing was sent.
|
|
75
87
|
*/
|
|
76
88
|
reply(input: {
|
|
77
89
|
readonly threadId: string;
|
|
78
|
-
|
|
90
|
+
/** Whom the reply goes to: the person, or the people of a reply the ontology hands over. */
|
|
91
|
+
readonly to: string | ReadonlyArray<string>;
|
|
79
92
|
/** The thread's other people the reply copies; none when absent. */
|
|
80
93
|
readonly cc?: ReadonlyArray<string>;
|
|
81
94
|
readonly text: string;
|
|
82
95
|
readonly key?: string;
|
|
83
96
|
readonly attachments?: ReadonlyArray<EmailAttachment>;
|
|
84
97
|
readonly signature?: boolean;
|
|
98
|
+
readonly quote?: QuoteSettings;
|
|
85
99
|
}): Promise<string>;
|
|
86
100
|
}
|
|
87
101
|
export declare function gmail(proxy: () => ConnectionProxy): Gmail;
|
|
@@ -5,12 +5,19 @@ const __filename = __eveFileURLToPath(import.meta.url);
|
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
8
|
+
import { answeredMailOf, withQuotedMail } from "./quote.mjs";
|
|
8
9
|
import { createHash } from "node:crypto";
|
|
9
10
|
import { GmailError, REPLY_KEY_HEADER, emailReplyMessage, gmailExplanation, mailboxSignature, renderEmailHtml, sendGmailMessage, withEmailSignature } from "@segmentstream/ontology/email";
|
|
10
11
|
const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
|
|
11
12
|
function replyKeyOf(...parts) {
|
|
12
13
|
return createHash("sha256").update(parts.join(":")).digest("base64url").slice(0, 32);
|
|
13
14
|
}
|
|
15
|
+
var ReplyNotSent = class extends Error {
|
|
16
|
+
name = "ReplyNotSent";
|
|
17
|
+
constructor(cause) {
|
|
18
|
+
super("The reply failed before it was sent.", { cause });
|
|
19
|
+
}
|
|
20
|
+
};
|
|
14
21
|
const explanation = gmailExplanation;
|
|
15
22
|
const decoder = new TextDecoder();
|
|
16
23
|
function json(reply) {
|
|
@@ -39,6 +46,17 @@ function gmail(proxy) {
|
|
|
39
46
|
if (reply.status < 200 || reply.status >= 300) throw new GmailError(operation, reply.status, explanation(reply));
|
|
40
47
|
return json(reply);
|
|
41
48
|
}
|
|
49
|
+
async function quoteMail(id, reply, settings) {
|
|
50
|
+
try {
|
|
51
|
+
const mail = answeredMailOf(await ok("messages.get", "GET", `/messages/${id}?format=full`));
|
|
52
|
+
const quoted = mail === void 0 ? void 0 : withQuotedMail(reply, mail, settings);
|
|
53
|
+
if (quoted === void 0) console.warn("[segmentstream] email quote left out", { reason: "nothing_to_quote" });
|
|
54
|
+
return quoted;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.warn("[segmentstream] email quote unavailable", { error: redactDiagnostic(error, new Set()) });
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
42
60
|
return {
|
|
43
61
|
async profile() {
|
|
44
62
|
const body = await ok("profile", "GET", "/profile");
|
|
@@ -169,8 +187,14 @@ function gmail(proxy) {
|
|
|
169
187
|
},
|
|
170
188
|
async reply(input) {
|
|
171
189
|
if (!GMAIL_ID.test(input.threadId)) throw new GmailError("threads.get", 400);
|
|
172
|
-
const thread = await ok("threads.get", "GET", `/threads/${input.threadId}?format=metadata&fields=messages(id,payload/headers)`)
|
|
190
|
+
const thread = await ok("threads.get", "GET", `/threads/${input.threadId}?format=metadata&fields=messages(id,labelIds,payload/headers)`).catch((error) => {
|
|
191
|
+
throw new ReplyNotSent(error);
|
|
192
|
+
});
|
|
173
193
|
const messages = Array.isArray(thread.messages) ? thread.messages : [];
|
|
194
|
+
const received = messages.filter((message) => {
|
|
195
|
+
const labels = message?.labelIds;
|
|
196
|
+
return !(Array.isArray(labels) && labels.includes("DRAFT"));
|
|
197
|
+
});
|
|
174
198
|
const header = (message, name) => {
|
|
175
199
|
return text((message?.payload?.headers ?? []).find((item) => String(item.name).toLowerCase() === name.toLowerCase())?.value);
|
|
176
200
|
};
|
|
@@ -179,21 +203,27 @@ function gmail(proxy) {
|
|
|
179
203
|
const id = text(sent?.id);
|
|
180
204
|
if (sent !== void 0) return id ?? "";
|
|
181
205
|
}
|
|
182
|
-
const
|
|
206
|
+
const rendered = renderEmailHtml(input.text);
|
|
183
207
|
const signature = input.signature === true ? await mailboxSignature({
|
|
184
208
|
mailbox: proxy().connection,
|
|
185
209
|
request: (call) => proxy().request(call)
|
|
186
210
|
}).catch((error) => {
|
|
187
211
|
console.warn("[segmentstream] email signature unavailable", { error: redactDiagnostic(error, new Set()) });
|
|
188
212
|
}) : void 0;
|
|
213
|
+
const signed = {
|
|
214
|
+
html: withEmailSignature(rendered, signature),
|
|
215
|
+
text: input.text
|
|
216
|
+
};
|
|
217
|
+
const answered = text(received.at(-1)?.id);
|
|
218
|
+
const { html, text: plain } = input.quote === void 0 || answered === void 0 || !GMAIL_ID.test(answered) ? signed : await quoteMail(answered, signed, input.quote) ?? signed;
|
|
189
219
|
const raw = emailReplyMessage({
|
|
190
220
|
to: input.to,
|
|
191
221
|
...input.cc === void 0 || input.cc.length === 0 ? {} : { cc: input.cc },
|
|
192
|
-
subject: header(
|
|
193
|
-
inReplyTo: header(
|
|
194
|
-
references: header(
|
|
195
|
-
text:
|
|
196
|
-
html
|
|
222
|
+
subject: header(received[0], "Subject") ?? null,
|
|
223
|
+
inReplyTo: header(received.at(-1), "Message-ID") ?? null,
|
|
224
|
+
references: header(received.at(-1), "References") ?? null,
|
|
225
|
+
text: plain,
|
|
226
|
+
html,
|
|
197
227
|
autoSubmitted: true,
|
|
198
228
|
...input.key === void 0 ? {} : { replyKey: input.key },
|
|
199
229
|
...input.attachments === void 0 || input.attachments.length === 0 ? {} : { attachments: input.attachments }
|
|
@@ -208,4 +238,4 @@ function gmail(proxy) {
|
|
|
208
238
|
}
|
|
209
239
|
};
|
|
210
240
|
}
|
|
211
|
-
export { GMAIL_ID, GmailError, gmail, replyKeyOf };
|
|
241
|
+
export { GMAIL_ID, GmailError, ReplyNotSent, gmail, replyKeyOf };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The settings of an email channel's quoted history (`channels.email.quote`), apart from the code
|
|
3
|
+
* that quotes, so the configuration reads them without the mail parser.
|
|
4
|
+
*/
|
|
5
|
+
/** The workspace's line above the quote and how its date and time are written. */
|
|
6
|
+
export interface QuoteSettings {
|
|
7
|
+
/** The line, with `{from}`, `{date}` and `{time}` for the quoted mail's sender, date and time. */
|
|
8
|
+
readonly attribution: string;
|
|
9
|
+
/** A BCP 47 locale, such as `en-GB`, for the date and time. */
|
|
10
|
+
readonly locale: string;
|
|
11
|
+
/** An IANA time zone, such as `Europe/Madrid`, for the date and time. */
|
|
12
|
+
readonly timeZone: string;
|
|
13
|
+
}
|
|
14
|
+
/** The placeholders an attribution may hold. */
|
|
15
|
+
export declare const QUOTE_PLACEHOLDERS: readonly ["from", "date", "time"];
|
|
16
|
+
/** The longest attribution, in characters. */
|
|
17
|
+
export declare const MAX_QUOTE_ATTRIBUTION = 300;
|
|
18
|
+
/** Why a settings value is refused, for the configuration's issues; undefined when it is valid. */
|
|
19
|
+
export declare function quoteSettingsIssue(key: keyof QuoteSettings, value: unknown): string | undefined;
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
const QUOTE_PLACEHOLDERS = [
|
|
8
|
+
"from",
|
|
9
|
+
"date",
|
|
10
|
+
"time"
|
|
11
|
+
];
|
|
12
|
+
const MAX_QUOTE_ATTRIBUTION = 300;
|
|
13
|
+
function quoteSettingsIssue(key, value) {
|
|
14
|
+
if (typeof value !== "string" || value.trim() === "") return "must be a non-empty string";
|
|
15
|
+
switch (key) {
|
|
16
|
+
case "attribution":
|
|
17
|
+
if (value.length > 300) return `must be at most 300 characters`;
|
|
18
|
+
return [...value.matchAll(/\{([^{}]*)\}/gu)].map((match) => match[1]).filter((name) => !QUOTE_PLACEHOLDERS.includes(name)).length === 0 ? void 0 : `takes only ${QUOTE_PLACEHOLDERS.map((name) => `{${name}}`).join(", ")}`;
|
|
19
|
+
case "locale": try {
|
|
20
|
+
return Intl.DateTimeFormat.supportedLocalesOf([value]).length === 1 ? void 0 : "must be a locale the runtime formats dates in, such as en-GB";
|
|
21
|
+
} catch {
|
|
22
|
+
return "must be a BCP 47 locale, such as en-GB";
|
|
23
|
+
}
|
|
24
|
+
case "timeZone": try {
|
|
25
|
+
new Intl.DateTimeFormat("en", { timeZone: value });
|
|
26
|
+
return;
|
|
27
|
+
} catch {
|
|
28
|
+
return "must be an IANA time zone, such as Europe/Madrid";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export { MAX_QUOTE_ATTRIBUTION, QUOTE_PLACEHOLDERS, quoteSettingsIssue };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { QUOTE_PLACEHOLDERS, type QuoteSettings } from "./quote-settings.js";
|
|
2
|
+
export { QUOTE_PLACEHOLDERS, type QuoteSettings };
|
|
3
|
+
/**
|
|
4
|
+
* Quoted history in the mail the agent sends (`channels.email.quote`): under its reply and the
|
|
5
|
+
* mailbox's signature, the mail the reply answers, as Gmail quotes it when a person replies. The
|
|
6
|
+
* line above the quote ("On …, … wrote:") is the workspace's words, with its date and time in the
|
|
7
|
+
* workspace's locale and time zone; the platform adds no words of its own. Only the message sent
|
|
8
|
+
* carries the quote: the chat keeps the reply as the agent or the member wrote it.
|
|
9
|
+
*/
|
|
10
|
+
/** The most characters of the quoted mail's HTML a reply carries; a longer mail is not quoted. */
|
|
11
|
+
export declare const MAX_QUOTED_HTML = 1000000;
|
|
12
|
+
/** The mail a reply answers, as far as quoting it needs. */
|
|
13
|
+
export interface AnsweredMail {
|
|
14
|
+
/** Its `From`, decoded, such as `Anna Ruiz <anna@agency.example>`. */
|
|
15
|
+
readonly from: string | undefined;
|
|
16
|
+
readonly date: Date | undefined;
|
|
17
|
+
readonly html: string | undefined;
|
|
18
|
+
readonly text: string | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The answered mail from Gmail's `messages.get` with `format=full`: its `From` and `Date` and its
|
|
22
|
+
* inline HTML and text bodies, which Gmail returns with the message while files keep only their
|
|
23
|
+
* ids. Undefined when the answer holds no payload.
|
|
24
|
+
*/
|
|
25
|
+
export declare function answeredMailOf(message: unknown): AnsweredMail | undefined;
|
|
26
|
+
/** The attribution with its placeholders filled, on one line. */
|
|
27
|
+
export declare function attributionLine(settings: QuoteSettings, mail: AnsweredMail): string;
|
|
28
|
+
/**
|
|
29
|
+
* The reply with the answered mail quoted under it, in Gmail's markup: `div.gmail_quote`, the
|
|
30
|
+
* attribution in `div.gmail_attr`, and the mail in `blockquote.gmail_quote`. The HTML part gets it
|
|
31
|
+
* before `</body>`, after the signature; the plain-text part gets the attribution and the mail's
|
|
32
|
+
* text with `> ` before each line. Undefined when there is nothing to quote or the mail is too
|
|
33
|
+
* long to carry.
|
|
34
|
+
*/
|
|
35
|
+
export declare function withQuotedMail(reply: {
|
|
36
|
+
readonly html: string;
|
|
37
|
+
readonly text: string;
|
|
38
|
+
}, mail: AnsweredMail, settings: QuoteSettings): {
|
|
39
|
+
readonly html: string;
|
|
40
|
+
readonly text: string;
|
|
41
|
+
} | undefined;
|
|
@@ -0,0 +1,96 @@
|
|
|
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 { htmlToText } from "../html-text.mjs";
|
|
8
|
+
import { QUOTE_PLACEHOLDERS } from "./quote-settings.mjs";
|
|
9
|
+
import { decodeWords } from "postal-mime";
|
|
10
|
+
const MAX_QUOTED_HTML = 1e6;
|
|
11
|
+
const MAX_QUOTED_TEXT = 2e5;
|
|
12
|
+
function headerOf(part, name) {
|
|
13
|
+
const found = (Array.isArray(part.headers) ? part.headers : []).find((header) => typeof header.name === "string" && header.name.toLowerCase() === name)?.value;
|
|
14
|
+
return typeof found === "string" && found.trim() !== "" ? found.trim() : void 0;
|
|
15
|
+
}
|
|
16
|
+
function partText(part) {
|
|
17
|
+
const data = part.body?.data;
|
|
18
|
+
if (typeof data !== "string" || data === "") return;
|
|
19
|
+
const bytes = Buffer.from(data, "base64url");
|
|
20
|
+
const charset = /charset="?([^";\s]+)"?/iu.exec(headerOf(part, "content-type") ?? "")?.[1];
|
|
21
|
+
try {
|
|
22
|
+
return new TextDecoder(charset ?? "utf-8").decode(bytes);
|
|
23
|
+
} catch {
|
|
24
|
+
return new TextDecoder("utf-8").decode(bytes);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function inlineBody(part, mimeType) {
|
|
28
|
+
const type = typeof part.mimeType === "string" ? part.mimeType.toLowerCase() : "";
|
|
29
|
+
const attached = typeof part.filename === "string" && part.filename !== "";
|
|
30
|
+
if (type === mimeType && !attached) return partText(part);
|
|
31
|
+
for (const child of Array.isArray(part.parts) ? part.parts : []) {
|
|
32
|
+
const found = inlineBody(child, mimeType);
|
|
33
|
+
if (found !== void 0) return found;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function answeredMailOf(message) {
|
|
37
|
+
const payload = message?.payload;
|
|
38
|
+
if (payload === void 0 || payload === null || typeof payload !== "object") return;
|
|
39
|
+
const from = headerOf(payload, "from");
|
|
40
|
+
const sent = headerOf(payload, "date");
|
|
41
|
+
const date = sent === void 0 ? void 0 : new Date(sent);
|
|
42
|
+
return {
|
|
43
|
+
from: from === void 0 ? void 0 : decodeWords(from),
|
|
44
|
+
date: date === void 0 || Number.isNaN(date.getTime()) ? void 0 : date,
|
|
45
|
+
html: inlineBody(payload, "text/html"),
|
|
46
|
+
text: inlineBody(payload, "text/plain")
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const HTML_ESCAPES = {
|
|
50
|
+
"&": "&",
|
|
51
|
+
"<": "<",
|
|
52
|
+
">": ">",
|
|
53
|
+
"\"": """,
|
|
54
|
+
"'": "'"
|
|
55
|
+
};
|
|
56
|
+
function escapeHtml(text) {
|
|
57
|
+
return text.replace(/[&<>"']/gu, (character) => HTML_ESCAPES[character] ?? character);
|
|
58
|
+
}
|
|
59
|
+
function attributionLine(settings, mail) {
|
|
60
|
+
const format = (options) => mail.date === void 0 ? "" : new Intl.DateTimeFormat(settings.locale, {
|
|
61
|
+
...options,
|
|
62
|
+
timeZone: settings.timeZone
|
|
63
|
+
}).format(mail.date);
|
|
64
|
+
const values = {
|
|
65
|
+
from: mail.from ?? "",
|
|
66
|
+
date: format({
|
|
67
|
+
weekday: "short",
|
|
68
|
+
year: "numeric",
|
|
69
|
+
month: "short",
|
|
70
|
+
day: "numeric"
|
|
71
|
+
}),
|
|
72
|
+
time: format({
|
|
73
|
+
hour: "numeric",
|
|
74
|
+
minute: "2-digit"
|
|
75
|
+
})
|
|
76
|
+
};
|
|
77
|
+
return settings.attribution.replace(/\{(from|date|time)\}/gu, (_, name) => values[name]).replace(/\s+/gu, " ").trim();
|
|
78
|
+
}
|
|
79
|
+
function quotedHtml(mail) {
|
|
80
|
+
if (mail.html !== void 0) return (/<body[^>]*>([^]*)<\/body>/iu.exec(mail.html)?.[1] ?? mail.html).replace(/<head[^>]*>[^]*?<\/head>/giu, "").replace(/<script[^>]*>[^]*?<\/script>/giu, "").replace(/<style[^>]*>[^]*?<\/style>/giu, "").replace(/<img\b[^>]*\bsrc\s*=\s*["']?cid:[^>]*>/giu, "");
|
|
81
|
+
if (mail.text !== void 0) return escapeHtml(mail.text.slice(0, MAX_QUOTED_TEXT)).replace(/\r?\n/gu, "<br>");
|
|
82
|
+
}
|
|
83
|
+
function withQuotedMail(reply, mail, settings) {
|
|
84
|
+
const quoted = quotedHtml(mail);
|
|
85
|
+
if (quoted === void 0 || quoted.trim() === "" || quoted.length > 1e6) return;
|
|
86
|
+
const line = attributionLine(settings, mail);
|
|
87
|
+
const block = `<br><div class="gmail_quote gmail_quote_container"><div dir="ltr" class="gmail_attr">${escapeHtml(line)}<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">${quoted}</blockquote></div>`;
|
|
88
|
+
const end = reply.html.lastIndexOf("</body>");
|
|
89
|
+
const html = end === -1 ? `${reply.html}${block}` : `${reply.html.slice(0, end)}${block}${reply.html.slice(end)}`;
|
|
90
|
+
const lines = (mail.text ?? htmlToText(mail.html ?? "", "text")).slice(0, MAX_QUOTED_TEXT).replace(/\r\n/gu, "\n").trimEnd().split("\n").map((text) => text === "" ? ">" : `> ${text}`);
|
|
91
|
+
return {
|
|
92
|
+
html,
|
|
93
|
+
text: `${reply.text}\n\n${line}\n\n${lines.join("\n")}\n`
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
export { MAX_QUOTED_HTML, QUOTE_PLACEHOLDERS, answeredMailOf, attributionLine, withQuotedMail };
|
|
@@ -12,7 +12,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
|
|
|
12
12
|
import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
|
|
13
13
|
import { handleWorkspaceCallback } from "./callbacks.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-Da-608Iv.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";
|
|
@@ -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-Da-608Iv.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 { E as OntologyActionNotPermitted, Et as principalRuntimeSource, L as needsConfirmation, Ot as runtimeEnvelope, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName, kt as telegramRuntimeSource } from "../../../_chunks/principal-DL9NdRRP.mjs";
|
|
8
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
8
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-Da-608Iv.mjs";
|
|
9
9
|
import { object } from "../confirmation-description.mjs";
|
|
10
10
|
var AttachmentLifecycleNotPermitted = class extends Error {
|
|
11
11
|
code = "attachment_lifecycle_not_permitted";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.94.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",
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
"@chat-adapter/state-memory": "4.42.0",
|
|
89
89
|
"@chat-adapter/telegram": "4.41.0",
|
|
90
90
|
"@chat-adapter/whatsapp": "4.42.0",
|
|
91
|
-
"@segmentstream/ontology": "0.
|
|
91
|
+
"@segmentstream/ontology": "0.176.0",
|
|
92
92
|
"@vercel/oidc": "^3.8.4",
|
|
93
93
|
"ai": "^7.0.172",
|
|
94
94
|
"chat": "4.42.0",
|