@segmentstream/agent 0.93.0 → 0.95.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 +62 -0
- package/dist/_chunks/{build-metadata-CP0iLqzp.mjs → build-metadata-CX7xleFw.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/connection-proxy.d.ts +12 -0
- package/dist/extension/lib/connection-proxy.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/dist/extension/lib/workspace-channel/attachments-send.d.ts +8 -4
- package/dist/extension/lib/workspace-channel/attachments-send.mjs +17 -18
- package/dist/extension/lib/workspace-channel/channel.d.ts +37 -5
- package/dist/extension/lib/workspace-channel/channel.mjs +65 -8
- package/dist/extension/lib/workspace-channel/connection.d.ts +10 -1
- package/dist/extension/lib/workspace-channel/connection.mjs +13 -2
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,67 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.95.0
|
|
4
|
+
|
|
5
|
+
Workspace channels take files by link, with a file limit of their own and the provider's
|
|
6
|
+
refusals.
|
|
7
|
+
|
|
8
|
+
- **Files by link.** Each file `send` receives is `{ filename, contentType, size, url, read() }`.
|
|
9
|
+
`url` is a short-lived link to the file in the workspace's file storage, to hand to a provider
|
|
10
|
+
that fetches files itself. `read()` reads the bytes once and checks their size. The ontology and
|
|
11
|
+
`segmentstream__attachments_send` no longer put files' bytes in the send route's request, so a
|
|
12
|
+
message can carry more than 3 MiB.
|
|
13
|
+
- **`limits.fileBytes`.** The most bytes of files one message carries, up to 64 MiB, 3 MiB when
|
|
14
|
+
absent. Files past it are refused (`file_too_large`) and nothing is sent.
|
|
15
|
+
- **`file` on the connection.** The channel's connection takes `file`, one of the files `send` was
|
|
16
|
+
given, as the whole body of a `POST`, `PUT` or `PATCH`. SegmentStream reads it from file storage,
|
|
17
|
+
up to 64 MiB, so its bytes never pass through the function.
|
|
18
|
+
- **Refusals.** `send` may return `{ refusal }`: `outside_reply_window`, `recipient_unreachable`
|
|
19
|
+
or `recipient_opted_out`. The message sent nothing, and the platform records the refusal as
|
|
20
|
+
WhatsApp's.
|
|
21
|
+
|
|
22
|
+
Action required for a workspace channel whose `send` reads `file.bytes`: call `await file.read()`,
|
|
23
|
+
or hand `file.url` to the provider. `bytes` is deprecated and present only while a message's files
|
|
24
|
+
are at most 3 MiB together. Upgrade the agent and ontology SDKs together; each still works with
|
|
25
|
+
the other's previous release.
|
|
26
|
+
|
|
27
|
+
Pins @segmentstream/ontology 0.177.0.
|
|
28
|
+
|
|
29
|
+
## 0.94.0
|
|
30
|
+
|
|
31
|
+
The ontology's replies to mail, a draft a member approves and a staff reply from the inbox, are
|
|
32
|
+
handed to the agent's email channel of the chat's name, which sends them as its own replies: in the
|
|
33
|
+
thread, from the mailbox, keyed so a lost answer is never sent twice, and signed and quoted by the
|
|
34
|
+
channel's `signature` and `quote`, so every reply from the mailbox looks the same. The reply's files
|
|
35
|
+
go by short-lived links to the workspace's file storage, checked against the revision the draft
|
|
36
|
+
holds before anything is reserved; the channel refuses a file whose size differs and sends nothing.
|
|
37
|
+
The channel serves this at `POST /eve/segmentstream/v1/email/<name>/deliver`, for the deployment's
|
|
38
|
+
own functions only.
|
|
39
|
+
|
|
40
|
+
An agent from before the route answers 404, and the ontology sends the reply from the mailbox
|
|
41
|
+
itself, as before: signed by `signature` on its `chat` entry and never quoted.
|
|
42
|
+
|
|
43
|
+
Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and set
|
|
44
|
+
`signature` (and `quote`, if wanted) on `channels.email` in `agent/segmentstream.json`. The
|
|
45
|
+
ontology's `chat.email.signature` now signs only replies sent for an agent from before the route; it
|
|
46
|
+
is deprecated and stops working on 2027-05-27.
|
|
47
|
+
|
|
48
|
+
The email channel takes `quote` in `agent/segmentstream.json`: each reply the agent sends from the
|
|
49
|
+
mailbox, files included, quotes under its text and signature the mail it answers, in Gmail's
|
|
50
|
+
markup, with `> ` lines in its plain-text part. `attribution` is the line above the quote in the
|
|
51
|
+
workspace's own words, with `{from}`, `{date}` and `{time}`, written in `locale` and `timeZone`:
|
|
52
|
+
|
|
53
|
+
```json
|
|
54
|
+
"quote": { "attribution": "On {date} at {time}, {from} wrote:", "locale": "en-GB", "timeZone": "Europe/Madrid" }
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The quoted mail is read with Gmail's `messages.get` in its `full` format, without its files; a mail
|
|
58
|
+
Gmail does not return, or one too long to carry, leaves the reply unquoted and the deployment's logs
|
|
59
|
+
say why. Only the message sent carries the quote: the chat keeps the reply as written. Drafts a
|
|
60
|
+
member approves and staff replies from the inbox, which the ontology sends, do not quote yet. Off
|
|
61
|
+
when absent.
|
|
62
|
+
|
|
63
|
+
Pins @segmentstream/ontology 0.176.0.
|
|
64
|
+
|
|
3
65
|
## 0.93.0
|
|
4
66
|
|
|
5
67
|
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.95.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-CX7xleFw.mjs";
|
|
@@ -26,6 +26,18 @@ export interface ProxyCall {
|
|
|
26
26
|
readonly path: string;
|
|
27
27
|
readonly headers: ReadonlyArray<readonly [string, string]>;
|
|
28
28
|
readonly body: Uint8Array;
|
|
29
|
+
/**
|
|
30
|
+
* A file in the workspace's file storage, by its signed read, that the proxy reads and sends as
|
|
31
|
+
* the body in place of `body`, which is then empty: up to 64 MiB, never through this function.
|
|
32
|
+
*/
|
|
33
|
+
readonly file?: ProxyFile;
|
|
34
|
+
}
|
|
35
|
+
/** The signed read of a byte range of a stored file, as the proxy reads it. */
|
|
36
|
+
export interface ProxyFile {
|
|
37
|
+
readonly url: string;
|
|
38
|
+
readonly headers: ReadonlyArray<readonly [string, string]>;
|
|
39
|
+
readonly start: number;
|
|
40
|
+
readonly end: number;
|
|
29
41
|
}
|
|
30
42
|
/** What the provider answered, buffered by the proxy. */
|
|
31
43
|
export interface ProxyReply {
|
|
@@ -78,7 +78,7 @@ function connectionProxy(input) {
|
|
|
78
78
|
method: call.method,
|
|
79
79
|
path: call.path,
|
|
80
80
|
headers: call.headers,
|
|
81
|
-
body: Buffer.from(call.body).toString("base64")
|
|
81
|
+
...call.file === void 0 ? { body: Buffer.from(call.body).toString("base64") } : { file: call.file }
|
|
82
82
|
}),
|
|
83
83
|
redirect: "error",
|
|
84
84
|
signal: abortSignal === void 0 ? AbortSignal.timeout(CALL_TIMEOUT_MS) : AbortSignal.any([abortSignal, AbortSignal.timeout(CALL_TIMEOUT_MS)])
|
|
@@ -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-CX7xleFw.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-CX7xleFw.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-CX7xleFw.mjs";
|
|
9
9
|
import { object } from "../confirmation-description.mjs";
|
|
10
10
|
var AttachmentLifecycleNotPermitted = class extends Error {
|
|
11
11
|
code = "attachment_lifecycle_not_permitted";
|
|
@@ -3,14 +3,18 @@ import { type AttachmentSendFailure, type AttachmentSendRefusal } from "../attac
|
|
|
3
3
|
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
|
+
/**
|
|
7
|
+
* The most bytes of files one message carries on any workspace channel; the channel's send route
|
|
8
|
+
* refuses those past its own `limits.fileBytes`.
|
|
9
|
+
*/
|
|
7
10
|
export declare const MAXIMUM_SENT_FILE_BYTES: number;
|
|
8
11
|
/**
|
|
9
12
|
* `attachments_send` in a chat of a channel the workspace defines in its own code: the stored
|
|
10
13
|
* files go in one message, the caption as its text, through the channel's own `send`, which the
|
|
11
|
-
* agent reaches at the channel's send route as the deployment, as the ontology does.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
+
* agent reaches at the channel's send route as the deployment, as the ontology does. Each file
|
|
15
|
+
* goes by a short-lived link, never its bytes. A channel whose code takes no files
|
|
16
|
+
* (`limits.files`) refuses them, and one refuses files past its `limits.fileBytes`. The checks and
|
|
17
|
+
* failures are every channel's (`../attachments-send.ts`).
|
|
14
18
|
*/
|
|
15
19
|
/** What became of one requested file. */
|
|
16
20
|
export interface ChannelSentFile extends Partial<AttachmentSendFailure> {
|
|
@@ -8,10 +8,10 @@ import { It as chatChannel, _ as AttachmentError } from "../../../_chunks/princi
|
|
|
8
8
|
import { sendStoredAttachments } from "../attachments-send.mjs";
|
|
9
9
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
10
10
|
import { ontologyDeploymentHeaders } from "../environment.mjs";
|
|
11
|
-
import { StoredFileError,
|
|
11
|
+
import { StoredFileError, storedFileGrant } from "../sent-files.mjs";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
|
-
import {
|
|
14
|
-
const MAXIMUM_SENT_FILE_BYTES =
|
|
13
|
+
import { WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES, isWorkspaceChannelRefusal, workspaceChannelFiles, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
|
|
14
|
+
const MAXIMUM_SENT_FILE_BYTES = WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES;
|
|
15
15
|
const TOO_LARGE = `One message carries at most ${MAXIMUM_SENT_FILE_BYTES / 1024 / 1024} MiB of files.`;
|
|
16
16
|
function reportChannelError(operation, error, secrets) {
|
|
17
17
|
const reference = randomUUID();
|
|
@@ -37,26 +37,25 @@ async function sendChannelAttachments(options) {
|
|
|
37
37
|
const read = [];
|
|
38
38
|
let total = 0;
|
|
39
39
|
for (const [index, reference] of input.documentIds.entries()) try {
|
|
40
|
-
const file = await
|
|
40
|
+
const file = await storedFileGrant({
|
|
41
41
|
reference,
|
|
42
42
|
owner,
|
|
43
43
|
origin,
|
|
44
44
|
token,
|
|
45
45
|
fetch,
|
|
46
|
-
secrets
|
|
47
|
-
tooLarge: () => new AttachmentError({
|
|
48
|
-
code: "too_large",
|
|
49
|
-
message: TOO_LARGE
|
|
50
|
-
}),
|
|
51
|
-
limit: ({ size }) => {
|
|
52
|
-
if (total + size > MAXIMUM_SENT_FILE_BYTES) throw new AttachmentError({
|
|
53
|
-
code: "too_large",
|
|
54
|
-
message: TOO_LARGE
|
|
55
|
-
});
|
|
56
|
-
return MAXIMUM_SENT_FILE_BYTES - total;
|
|
57
|
-
}
|
|
46
|
+
secrets
|
|
58
47
|
});
|
|
59
|
-
|
|
48
|
+
if (!file.url.startsWith("https://") || Object.keys(file.headers).length > 0) throw new StoredFileError({
|
|
49
|
+
code: "unsupported",
|
|
50
|
+
message: "The file's download link is not one the channel can follow.",
|
|
51
|
+
filename: file.filename
|
|
52
|
+
});
|
|
53
|
+
if (total + file.size > MAXIMUM_SENT_FILE_BYTES) throw new StoredFileError({
|
|
54
|
+
code: "too_large",
|
|
55
|
+
message: TOO_LARGE,
|
|
56
|
+
filename: file.filename
|
|
57
|
+
});
|
|
58
|
+
total += file.size;
|
|
60
59
|
read.push({
|
|
61
60
|
index,
|
|
62
61
|
file
|
|
@@ -96,7 +95,7 @@ async function sendChannelAttachments(options) {
|
|
|
96
95
|
});
|
|
97
96
|
const answer = await response.json().catch(() => ({}));
|
|
98
97
|
if (!response.ok) throw new AttachmentError({
|
|
99
|
-
code: answer.error === "files_unsupported" ? "unsupported" : "send_failed",
|
|
98
|
+
code: answer.error === "files_unsupported" ? "unsupported" : answer.error === "file_too_large" ? "too_large" : isWorkspaceChannelRefusal(answer.error) ? answer.error : "send_failed",
|
|
100
99
|
message: `The channel did not take the files (${String(answer.error ?? response.status)}).`
|
|
101
100
|
});
|
|
102
101
|
messageId = typeof answer.message_id === "string" ? answer.message_id : void 0;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Channel, type ChannelEvents } from "eve/channels";
|
|
2
2
|
import type { SessionAuthContext } from "eve/context";
|
|
3
|
+
import { type WorkspaceChannelRefusal } from "@segmentstream/ontology/workspace-channel";
|
|
3
4
|
import { type SegmentStreamAgentConfigInput } from "../../config.js";
|
|
4
5
|
import { type AgentAttachments } from "../attachments.js";
|
|
5
6
|
import { type ChatArchive } from "../chat-archive.js";
|
|
@@ -141,12 +142,36 @@ export type ChannelEvent = ChannelMessageEvent | {
|
|
|
141
142
|
/** The provider's refusal of a failed message, as a code such as `recipient_unreachable`. */
|
|
142
143
|
readonly reason?: string;
|
|
143
144
|
};
|
|
144
|
-
/**
|
|
145
|
+
/**
|
|
146
|
+
* A file the agent sends, by a short-lived link to it in the workspace's file storage: hand `url`
|
|
147
|
+
* to a provider that fetches files itself, send it through the connection with the `file` option,
|
|
148
|
+
* or `read()` its bytes. Its bytes never travel in a request to the agent, so a file may be as large
|
|
149
|
+
* as the channel's `limits.fileBytes`.
|
|
150
|
+
*/
|
|
145
151
|
export interface ChannelReplyFile {
|
|
146
152
|
readonly filename: string;
|
|
147
153
|
readonly contentType: string;
|
|
148
|
-
|
|
154
|
+
/** Its size in bytes, which `read()` and the connection's `file` check. */
|
|
155
|
+
readonly size: number;
|
|
156
|
+
/**
|
|
157
|
+
* An `https` link that reads the file without credentials, valid about a minute: hand it to the
|
|
158
|
+
* provider at once. Absent only for a file an ontology before links sends, which `read()` reads.
|
|
159
|
+
*/
|
|
160
|
+
readonly url?: string;
|
|
161
|
+
/** Its bytes, read once; rejects when the read is not `size` bytes. */
|
|
162
|
+
read(): Promise<Uint8Array>;
|
|
163
|
+
/**
|
|
164
|
+
* @deprecated Call `read()`.
|
|
165
|
+
* @legacy agent.channel-reply-file-bytes Its bytes, read beforehand, only while the message's
|
|
166
|
+
* files are at most 3 MiB together, as files were before links.
|
|
167
|
+
*/
|
|
168
|
+
readonly bytes?: Uint8Array;
|
|
149
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* Why the provider refused a message, as `send` answers it: nothing was sent, and the platform
|
|
172
|
+
* records the refusal as a first-party channel's, such as WhatsApp's.
|
|
173
|
+
*/
|
|
174
|
+
export type ChannelRefusal = WorkspaceChannelRefusal;
|
|
150
175
|
/** A message the channel's code sends: the agent's reply, a reviewed one, or a chat post. */
|
|
151
176
|
export interface ChannelReply {
|
|
152
177
|
/** The person's chat; for a chat post, the one they last wrote from on the channel. */
|
|
@@ -213,18 +238,25 @@ export interface ChannelDefinition {
|
|
|
213
238
|
* `outbound` message; a delivery receipt is a `status`. An event that holds nothing holds none.
|
|
214
239
|
*/
|
|
215
240
|
parse(event: unknown, context: ChannelContext): ReadonlyArray<ChannelEvent> | Promise<ReadonlyArray<ChannelEvent>>;
|
|
216
|
-
/**
|
|
241
|
+
/**
|
|
242
|
+
* Sends one message; answers the provider's id of it, when it gives one, or the provider's
|
|
243
|
+
* refusal of it ({@link ChannelRefusal}), such as a person outside the provider's reply window: a
|
|
244
|
+
* refused message sent nothing. Throw for any other failure, which may have sent it.
|
|
245
|
+
*/
|
|
217
246
|
send(reply: ChannelReply, context: ChannelContext): Promise<{
|
|
218
247
|
readonly id?: string;
|
|
248
|
+
} | {
|
|
249
|
+
readonly refusal: ChannelRefusal;
|
|
219
250
|
} | undefined | void>;
|
|
220
251
|
/**
|
|
221
252
|
* What the provider takes: `maxLength`, the most characters of one message, longer replies leave
|
|
222
|
-
* in several; `files`, whether messages carry files both ways
|
|
223
|
-
* files.
|
|
253
|
+
* in several; `files`, whether messages carry files both ways; `fileBytes`, the most bytes of
|
|
254
|
+
* files one message carries, at most 64 MiB. Without them, any length, no files, and 3 MiB.
|
|
224
255
|
*/
|
|
225
256
|
readonly limits?: {
|
|
226
257
|
readonly maxLength?: number;
|
|
227
258
|
readonly files?: boolean;
|
|
259
|
+
readonly fileBytes?: number;
|
|
228
260
|
};
|
|
229
261
|
}
|
|
230
262
|
export interface WorkspaceChannelOptions extends ChannelDefinition {
|
|
@@ -21,6 +21,7 @@ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
|
|
|
21
21
|
import { gatewayTranscriber } from "../inbound-media/speech.mjs";
|
|
22
22
|
import { channelReview } from "../review/reply.mjs";
|
|
23
23
|
import { g as turnFiles, n as completionKind } from "../../../_chunks/silent-xJcJ8SNJ.mjs";
|
|
24
|
+
import { boundedDownload } from "../sent-files.mjs";
|
|
24
25
|
import { replyFilesSender } from "../attachments-dispatch.mjs";
|
|
25
26
|
import { runtimeTokenVerifier } from "../runtime-identity.mjs";
|
|
26
27
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
@@ -30,7 +31,7 @@ import { ChannelCheckUnavailable, channelChecks } from "./secrets.mjs";
|
|
|
30
31
|
import { decide } from "eve/ai";
|
|
31
32
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
32
33
|
import { reply } from "eve/events";
|
|
33
|
-
import { WORKSPACE_CHANNEL_ID, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
|
|
34
|
+
import { WORKSPACE_CHANNEL_FILES_BYTES, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES, isWorkspaceChannelRefusal, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
|
|
34
35
|
import { POST, defineChannel as defineChannel$1 } from "eve/channels";
|
|
35
36
|
const WORKSPACE_CHANNEL_AUTHENTICATOR = "segmentstream-channel";
|
|
36
37
|
const MAXIMUM_CURSOR_LENGTH = 16384;
|
|
@@ -39,6 +40,38 @@ var TooManyMessages = class extends Error {
|
|
|
39
40
|
name = "TooManyMessages";
|
|
40
41
|
};
|
|
41
42
|
const MAXIMUM_TEXT = 2e4;
|
|
43
|
+
const FILE_READ_TIMEOUT_MS = 3e4;
|
|
44
|
+
var ChannelSendRefused = class extends Error {
|
|
45
|
+
refusal;
|
|
46
|
+
name = "ChannelSendRefused";
|
|
47
|
+
constructor(refusal) {
|
|
48
|
+
super(`The provider refused the message (${refusal}).`);
|
|
49
|
+
this.refusal = refusal;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
function replyFile(file, fetchImpl) {
|
|
53
|
+
let read;
|
|
54
|
+
return {
|
|
55
|
+
filename: file.filename,
|
|
56
|
+
contentType: file.contentType,
|
|
57
|
+
size: file.size,
|
|
58
|
+
...file.url === void 0 ? {} : { url: file.url },
|
|
59
|
+
read: () => read ??= (async () => {
|
|
60
|
+
if (file.bytes !== void 0) return file.bytes;
|
|
61
|
+
const response = await fetchImpl(file.url, {
|
|
62
|
+
redirect: "error",
|
|
63
|
+
signal: AbortSignal.timeout(FILE_READ_TIMEOUT_MS)
|
|
64
|
+
});
|
|
65
|
+
if (!response.ok) {
|
|
66
|
+
await response.body?.cancel();
|
|
67
|
+
throw new Error(`Storage answered the file's read with status ${response.status}.`);
|
|
68
|
+
}
|
|
69
|
+
const bytes = await boundedDownload(response, file.size, () => new Error(`The file's read exceeds the ${file.size} bytes it was sent with.`));
|
|
70
|
+
if (bytes.byteLength !== file.size) throw new Error(`The file's read has ${bytes.byteLength} bytes, not ${file.size}.`);
|
|
71
|
+
return bytes;
|
|
72
|
+
})()
|
|
73
|
+
};
|
|
74
|
+
}
|
|
42
75
|
function error(code, status) {
|
|
43
76
|
return Response.json({ error: code }, { status });
|
|
44
77
|
}
|
|
@@ -224,6 +257,8 @@ function workspaceChannelDefinition(options) {
|
|
|
224
257
|
const identity = workspaceIdentityProvider(name);
|
|
225
258
|
const maxLength = options.limits?.maxLength;
|
|
226
259
|
const files = options.limits?.files === true;
|
|
260
|
+
const fileBytes = options.limits?.fileBytes ?? WORKSPACE_CHANNEL_FILES_BYTES;
|
|
261
|
+
if (!Number.isSafeInteger(fileBytes) || fileBytes < 1 || fileBytes > WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES) throw new TypeError(`limits.fileBytes must be a whole number of bytes from 1 to ${WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES}.`);
|
|
227
262
|
let connection = options.connection;
|
|
228
263
|
let identities = options.identities;
|
|
229
264
|
let attachments = options.attachments;
|
|
@@ -259,13 +294,14 @@ function workspaceChannelDefinition(options) {
|
|
|
259
294
|
environment,
|
|
260
295
|
...transport
|
|
261
296
|
});
|
|
262
|
-
const report = (operation, cause) =>
|
|
297
|
+
const report = (operation, cause) => redacted(operation, cause, new Set());
|
|
298
|
+
const redacted = (operation, cause, secrets) => {
|
|
263
299
|
const reference = randomUUID();
|
|
264
300
|
log("[segmentstream] workspace channel diagnostic", {
|
|
265
301
|
channel: name,
|
|
266
302
|
operation,
|
|
267
303
|
reference,
|
|
268
|
-
error: redactDiagnostic(cause,
|
|
304
|
+
error: redactDiagnostic(cause, secrets)
|
|
269
305
|
});
|
|
270
306
|
return reference;
|
|
271
307
|
};
|
|
@@ -277,6 +313,7 @@ function workspaceChannelDefinition(options) {
|
|
|
277
313
|
text,
|
|
278
314
|
...index === 0 || reply.files === void 0 ? {} : { files: [] }
|
|
279
315
|
}, context());
|
|
316
|
+
if (sent !== void 0 && "refusal" in sent) throw new ChannelSendRefused(sent.refusal);
|
|
280
317
|
parts.push({
|
|
281
318
|
text,
|
|
282
319
|
id: typeof sent?.id === "string" && sent.id !== "" ? sent.id : null
|
|
@@ -625,15 +662,34 @@ function workspaceChannelDefinition(options) {
|
|
|
625
662
|
if (chatId !== null && (typeof chatId !== "string" || !WORKSPACE_CHANNEL_ID.test(chatId)) || typeof recipient !== "string" || !WORKSPACE_CHANNEL_ID.test(recipient) || replyTo !== null && replyTo !== void 0 && (typeof replyTo !== "string" || !WORKSPACE_CHANNEL_ID.test(replyTo)) || typeof text !== "string" || body.files !== void 0 && sent === void 0) return error("invalid_request", 400);
|
|
626
663
|
if (sent !== void 0 && !files) return error("files_unsupported", 422);
|
|
627
664
|
if (sent === void 0 && maxLength !== void 0 && text.length > maxLength) return error("text_too_long", 422);
|
|
628
|
-
const
|
|
665
|
+
const declared = [];
|
|
629
666
|
for (const file of sent ?? []) {
|
|
630
|
-
if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || typeof file.data !== "string") return error("invalid_request", 400);
|
|
631
|
-
|
|
667
|
+
if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || file.url !== void 0 && (typeof file.url !== "string" || !file.url.startsWith("https://")) || file.data !== void 0 && typeof file.data !== "string" || file.url === void 0 && file.data === void 0) return error("invalid_request", 400);
|
|
668
|
+
const bytes = typeof file.data === "string" ? new Uint8Array(Buffer.from(file.data, "base64")) : void 0;
|
|
669
|
+
const size = file.size ?? bytes?.byteLength;
|
|
670
|
+
if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return error("invalid_request", 400);
|
|
671
|
+
if (bytes !== void 0 && bytes.byteLength !== size) return error("file_unavailable", 422);
|
|
672
|
+
declared.push({
|
|
632
673
|
filename: file.filename,
|
|
633
674
|
contentType: file.content_type,
|
|
634
|
-
|
|
675
|
+
size,
|
|
676
|
+
...typeof file.url === "string" ? { url: file.url } : {},
|
|
677
|
+
...bytes === void 0 ? {} : { bytes }
|
|
635
678
|
});
|
|
636
679
|
}
|
|
680
|
+
const total = declared.reduce((sum, file) => sum + file.size, 0);
|
|
681
|
+
if (total > fileBytes) return error("file_too_large", 422);
|
|
682
|
+
const secrets = new Set(declared.flatMap((file) => file.url === void 0 ? [] : [file.url]));
|
|
683
|
+
const replyFiles = declared.map((file) => replyFile(file, options.fetch ?? fetch));
|
|
684
|
+
if (total <= WORKSPACE_CHANNEL_FILES_BYTES) try {
|
|
685
|
+
for (const [index, file] of replyFiles.entries()) replyFiles[index] = {
|
|
686
|
+
...file,
|
|
687
|
+
bytes: await file.read()
|
|
688
|
+
};
|
|
689
|
+
} catch (cause) {
|
|
690
|
+
redacted("file_unavailable", cause, secrets);
|
|
691
|
+
return error("file_unavailable", 422);
|
|
692
|
+
}
|
|
637
693
|
let chat;
|
|
638
694
|
try {
|
|
639
695
|
chat = typeof chatId === "string" ? chatId : await lastChat(recipient);
|
|
@@ -651,9 +707,10 @@ function workspaceChannelDefinition(options) {
|
|
|
651
707
|
...sent === void 0 ? {} : { files: replyFiles }
|
|
652
708
|
};
|
|
653
709
|
const answer = await options.send(reply, context());
|
|
710
|
+
if (answer !== void 0 && "refusal" in answer) return error(isWorkspaceChannelRefusal(answer.refusal) ? answer.refusal : "send_refused", 422);
|
|
654
711
|
return Response.json({ message_id: typeof answer?.id === "string" && answer.id !== "" ? answer.id : null });
|
|
655
712
|
} catch (cause) {
|
|
656
|
-
const reference =
|
|
713
|
+
const reference = redacted("send_failed", cause, secrets);
|
|
657
714
|
return Response.json({
|
|
658
715
|
error: "send_failed",
|
|
659
716
|
reference
|
|
@@ -17,8 +17,17 @@ export interface ChannelConnectionRequestOptions {
|
|
|
17
17
|
readonly json?: unknown;
|
|
18
18
|
/** A form body, sent with `content-type: application/x-www-form-urlencoded`. */
|
|
19
19
|
readonly form?: Readonly<Record<string, string>>;
|
|
20
|
-
/** A raw body. Set at most one of `json`, `form` and `
|
|
20
|
+
/** A raw body. Set at most one of `json`, `form`, `body` and `file`. */
|
|
21
21
|
readonly body?: string | Uint8Array;
|
|
22
|
+
/**
|
|
23
|
+
* A file `send` was given, as the whole body of a `POST`, `PUT` or `PATCH`: SegmentStream reads it
|
|
24
|
+
* from the workspace's file storage and sends it, so its bytes never pass through the function.
|
|
25
|
+
* Set its content type in `headers`.
|
|
26
|
+
*/
|
|
27
|
+
readonly file?: {
|
|
28
|
+
readonly url?: string;
|
|
29
|
+
readonly size: number;
|
|
30
|
+
};
|
|
22
31
|
}
|
|
23
32
|
export interface ChannelConnectionRequest extends ChannelConnectionRequestOptions {
|
|
24
33
|
readonly method: ChannelConnectionMethod;
|
|
@@ -14,7 +14,12 @@ function queryString(query) {
|
|
|
14
14
|
return text === "" ? "" : `?${text}`;
|
|
15
15
|
}
|
|
16
16
|
function connectionCall(request) {
|
|
17
|
-
if ((request.json !== void 0 ? 1 : 0) + (request.form !== void 0 ? 1 : 0) + (request.body !== void 0 ? 1 : 0) > 1) throw new TypeError("Set at most one of json, form and
|
|
17
|
+
if ((request.json !== void 0 ? 1 : 0) + (request.form !== void 0 ? 1 : 0) + (request.body !== void 0 ? 1 : 0) + (request.file !== void 0 ? 1 : 0) > 1) throw new TypeError("Set at most one of json, form, body and file.");
|
|
18
|
+
if (request.file !== void 0 && (request.file.url === void 0 || !Number.isSafeInteger(request.file.size) || request.file.size < 1 || ![
|
|
19
|
+
"POST",
|
|
20
|
+
"PUT",
|
|
21
|
+
"PATCH"
|
|
22
|
+
].includes(request.method))) throw new TypeError("A file goes as the body of a POST, PUT or PATCH, by its link.");
|
|
18
23
|
const headers = Array.isArray(request.headers) ? [...request.headers] : Object.entries(request.headers ?? {});
|
|
19
24
|
const typed = headers.some(([name]) => name.toLowerCase() === "content-type");
|
|
20
25
|
const encoder = new TextEncoder();
|
|
@@ -33,7 +38,13 @@ function connectionCall(request) {
|
|
|
33
38
|
method: request.method,
|
|
34
39
|
path: `${request.path}${separator === "&" ? query.replace("?", "&") : query}`,
|
|
35
40
|
headers,
|
|
36
|
-
body
|
|
41
|
+
body,
|
|
42
|
+
...request.file === void 0 ? {} : { file: {
|
|
43
|
+
url: request.file.url,
|
|
44
|
+
headers: [],
|
|
45
|
+
start: 0,
|
|
46
|
+
end: request.file.size - 1
|
|
47
|
+
} }
|
|
37
48
|
};
|
|
38
49
|
}
|
|
39
50
|
function channelConnection(proxy) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.95.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.177.0",
|
|
92
92
|
"@vercel/oidc": "^3.8.4",
|
|
93
93
|
"ai": "^7.0.172",
|
|
94
94
|
"chat": "4.42.0",
|