@segmentstream/agent 0.92.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/_chunks/{build-metadata-C_9WeVSz.mjs → build-metadata-Da-608Iv.mjs} +1 -1
  3. package/dist/extension/config.d.ts +24 -0
  4. package/dist/extension/config.mjs +59 -2
  5. package/dist/extension/lib/attachments-dispatch.mjs +2 -1
  6. package/dist/extension/lib/build-metadata.mjs +1 -1
  7. package/dist/extension/lib/chat-persona.d.ts +2 -0
  8. package/dist/extension/lib/chat-persona.mjs +5 -5
  9. package/dist/extension/lib/chats.d.ts +2 -0
  10. package/dist/extension/lib/chats.mjs +4 -2
  11. package/dist/extension/lib/email/attachments-send.d.ts +3 -0
  12. package/dist/extension/lib/email/attachments-send.mjs +4 -2
  13. package/dist/extension/lib/email/channel.d.ts +8 -0
  14. package/dist/extension/lib/email/channel.mjs +108 -9
  15. package/dist/extension/lib/email/gmail.d.ts +18 -4
  16. package/dist/extension/lib/email/gmail.mjs +38 -8
  17. package/dist/extension/lib/email/quote-settings.d.ts +19 -0
  18. package/dist/extension/lib/email/quote-settings.mjs +32 -0
  19. package/dist/extension/lib/email/quote.d.ts +41 -0
  20. package/dist/extension/lib/email/quote.mjs +96 -0
  21. package/dist/extension/lib/public-group.d.ts +19 -0
  22. package/dist/extension/lib/public-group.mjs +77 -0
  23. package/dist/extension/lib/slack/adapter.d.ts +1 -0
  24. package/dist/extension/lib/slack/adapter.mjs +20 -4
  25. package/dist/extension/lib/telegram/adapter.mjs +4 -2
  26. package/dist/extension/lib/telegram/health.mjs +1 -1
  27. package/dist/extension/lib/telegram/inbound.mjs +17 -0
  28. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  29. package/dist/extension/lib/telegram/membership.mjs +8 -2
  30. package/dist/extension/lib/web-search.d.ts +2 -0
  31. package/dist/extension/lib/web-search.mjs +1 -1
  32. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
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
+
39
+ ## 0.93.0
40
+
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.
42
+
43
+ Pins @segmentstream/ontology 0.175.0.
44
+
3
45
  ## 0.92.0
4
46
 
5
47
  Telegram messages, edits and delivery receipts keep the bot account that received or sent them.
@@ -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.92.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";
@@ -74,7 +75,15 @@ export interface FirstContactSettings {
74
75
  }
75
76
  export declare const ADMISSION_REPLY_KEYS: readonly ["pairingRequired", "pairingButton", "groupPairingButton", "limited", "perSenderLimited", "workspaceLimited", "registrationsLimited", "groupPairingRequired", "refused"];
76
77
  export type AdmissionReplies = Partial<Record<(typeof ADMISSION_REPLY_KEYS)[number], LocalizedText>>;
78
+ export interface PublicGroupSettings {
79
+ readonly model: string;
80
+ /** Workspace-published material for an isolated, text-only answer. */
81
+ readonly instructions: string;
82
+ /** Dedicated group connections which may be opened by an authorized inviter. */
83
+ readonly trustedJoinChannels?: readonly string[];
84
+ }
77
85
  export interface AdmissionSettings {
86
+ readonly publicGroups?: PublicGroupSettings;
78
87
  readonly personas?: PersonaSettings;
79
88
  readonly firstContact: FirstContactSettings | null;
80
89
  readonly limits: AdmissionLimits;
@@ -87,6 +96,7 @@ export interface AdmissionSettings {
87
96
  * the values validation allows.
88
97
  */
89
98
  export interface SegmentStreamAgentConfigInput {
99
+ readonly publicGroups?: PublicGroupSettings;
90
100
  readonly groups?: GroupPolicyInput;
91
101
  readonly texts?: TelegramTexts;
92
102
  readonly firstContact?: FirstContactSettings;
@@ -335,6 +345,18 @@ export interface EmailChannelInput {
335
345
  * (`reply` cannot be `sender` with it).
336
346
  */
337
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
+ };
338
360
  }
339
361
  /**
340
362
  * A channel the workspace defines in its own code, `defineChannel` in `agent/agent/channels/`,
@@ -651,6 +673,8 @@ export interface EmailSettings {
651
673
  readonly chats?: "thread";
652
674
  /** `true` when the agent's replies end with the mailbox's own signature; absent, they do not. */
653
675
  readonly signature?: true;
676
+ /** How the agent's replies quote the mail they answer; absent, they quote nothing. */
677
+ readonly quote?: QuoteSettings;
654
678
  }
655
679
  /**
656
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"]) {
@@ -1114,6 +1146,7 @@ function validateConfig(input, options = {}) {
1114
1146
  "sessions",
1115
1147
  "confirmations",
1116
1148
  "firstContact",
1149
+ "publicGroups",
1117
1150
  "limits",
1118
1151
  "replies",
1119
1152
  "texts",
@@ -1259,6 +1292,29 @@ function validateConfig(input, options = {}) {
1259
1292
  const sessions = sessionSettings(root?.sessions, issues);
1260
1293
  const firstContact = firstContactSettings(root?.firstContact, issues, !legacyArchive);
1261
1294
  const limits = admissionLimits(root?.limits, issues);
1295
+ const publicGroupInput = section({
1296
+ value: root?.publicGroups,
1297
+ path: ["publicGroups"],
1298
+ allowed: [
1299
+ "model",
1300
+ "instructions",
1301
+ "trustedJoinChannels"
1302
+ ],
1303
+ issues
1304
+ });
1305
+ let publicGroups;
1306
+ if (publicGroupInput) {
1307
+ const { model, instructions, trustedJoinChannels } = publicGroupInput;
1308
+ if (typeof model !== "string" || !model.trim() || model.length > 256 || typeof instructions !== "string" || !instructions.trim() || instructions.length > 32e3 || trustedJoinChannels !== void 0 && (!Array.isArray(trustedJoinChannels) || !trustedJoinChannels.every((channel) => typeof channel === "string" && Object.hasOwn(channels ?? {}, channel)))) issues.push({
1309
+ path: ["publicGroups"],
1310
+ message: "Supply a model, public instructions and optional configured channel names."
1311
+ });
1312
+ else publicGroups = {
1313
+ model,
1314
+ instructions,
1315
+ ...trustedJoinChannels ? { trustedJoinChannels } : {}
1316
+ };
1317
+ }
1262
1318
  const replies = admissionReplies(root?.replies, issues, !legacyArchive);
1263
1319
  const texts = telegramTexts(root?.texts, issues);
1264
1320
  if (!legacyArchive && replies.groupPairingButton !== void 0 && replies.groupPairingRequired === void 0) issues.push({
@@ -1374,6 +1430,7 @@ function validateConfig(input, options = {}) {
1374
1430
  ...browser === null ? {} : { browser },
1375
1431
  sessions,
1376
1432
  firstContact,
1433
+ ...publicGroups ? { publicGroups } : {},
1377
1434
  limits,
1378
1435
  replies,
1379
1436
  texts,
@@ -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-C_9WeVSz.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-Da-608Iv.mjs";
@@ -1,5 +1,7 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
2
  import { chatPersona, type PersonaSettings } from "../personas.js";
3
+ /** A production runtime lookup on the current chat. An outage must not silently change its persona. */
4
+ export declare function chatRuntimeRequest(operation: string, data: Record<string, unknown>): Promise<any>;
3
5
  export declare function resolveChatPersona(settings: PersonaSettings, principal: SessionAuthContext | null | undefined, read?: (key: string) => Promise<string | null>): Promise<{
4
6
  readonly name: string;
5
7
  readonly source: "chat";
@@ -9,7 +9,7 @@ import { Ft as chatAddressOf, It as chatChannel, i as memberIdOf, ot as guestIdO
9
9
  import { appOrigin, ontologyDeploymentHeaders } from "./environment.mjs";
10
10
  import { localizedText } from "./admission.mjs";
11
11
  import { runtimeToken } from "./runtime-token.mjs";
12
- async function request(operation, data) {
12
+ async function chatRuntimeRequest(operation, data) {
13
13
  const response = await fetch(`${appOrigin()}/api/ontology/agent/chats/${operation}`, {
14
14
  method: "POST",
15
15
  redirect: "error",
@@ -21,11 +21,11 @@ async function request(operation, data) {
21
21
  body: JSON.stringify(data),
22
22
  signal: AbortSignal.timeout(5e3)
23
23
  });
24
- if (!response.ok) throw new Error(`Reading the chat persona failed (HTTP ${response.status}).`);
24
+ if (!response.ok) throw new Error(`The chat runtime request failed (HTTP ${response.status}).`);
25
25
  return response.json();
26
26
  }
27
27
  async function readAssignment(key) {
28
- const body = await request("persona", { key });
28
+ const body = await chatRuntimeRequest("persona", { key });
29
29
  if (body?.persona !== null && typeof body?.persona !== "string") throw new Error("Invalid chat persona response.");
30
30
  return body.persona;
31
31
  }
@@ -47,7 +47,7 @@ async function offerPersona(settings, selection, principal, deliver, locale) {
47
47
  const memberId = memberIdOf(principal);
48
48
  if (!text || !chat || !memberId || selection?.source !== "default" || !selection.name) return;
49
49
  try {
50
- const receipt = await request("persona-notice", {
50
+ const receipt = await chatRuntimeRequest("persona-notice", {
51
51
  key: `${chatChannel(chat)}:${chat.chatId}`,
52
52
  memberId,
53
53
  provider: chat.provider
@@ -72,4 +72,4 @@ async function personaPrincipal(settings, principal, deliver) {
72
72
  }
73
73
  } : principal;
74
74
  }
75
- export { offerPersona, personaPrincipal, resolveChatPersona };
75
+ export { chatRuntimeRequest, offerPersona, personaPrincipal, resolveChatPersona };
@@ -12,6 +12,7 @@ export interface ChatReport {
12
12
  readonly chatId: string;
13
13
  readonly title: ChatTitle;
14
14
  readonly memberId?: string;
15
+ readonly inviter?: string;
15
16
  }
16
17
  export interface AgentChats {
17
18
  /**
@@ -68,6 +69,7 @@ export declare function agentChats(input: {
68
69
  /** The provider whose chats these are, as the registry records them. */
69
70
  readonly provider: string;
70
71
  readonly identities: () => AgentIdentities;
72
+ readonly onInvite?: (chatId: string, inviter: string) => Promise<void>;
71
73
  readonly now?: () => number;
72
74
  readonly log?: (message: string, error: unknown) => void;
73
75
  readonly logError?: (message: string, error: unknown) => void;
@@ -93,7 +93,7 @@ function agentChats(input) {
93
93
  }
94
94
  }
95
95
  return {
96
- async joined({ chatId, title }) {
96
+ async joined({ chatId, title, inviter }) {
97
97
  const known = chats.get(chatId);
98
98
  const remembered = {
99
99
  reportedAt: now(),
@@ -101,7 +101,9 @@ function agentChats(input) {
101
101
  chat: known?.chat
102
102
  };
103
103
  remember(chatId, remembered);
104
- if (await report(chatId, remembered, { title }) === "failed") restore(chatId, remembered, known);
104
+ const outcome = await report(chatId, remembered, { title });
105
+ if (outcome === "failed") restore(chatId, remembered, known);
106
+ else if (outcome === "reported" && inviter) await input.onInvite?.(chatId, inviter);
105
107
  },
106
108
  health() {
107
109
  const failedChats = [...failures.values()];
@@ -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 code = error instanceof GmailError ? error.status === 413 ? "too_large" : error.status === 401 || error.status === 403 ? "forbidden" : "send_failed" : error instanceof ConnectionProxyError && error.code === "invalid_request" ? "too_large" : "send_failed";
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 { GMAIL_ID, GmailError, gmail, replyKeyOf } from "./gmail.mjs";
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 = () => settings()?.signature === true ? { signature: true } : {};
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 message, with the reply's
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
- readonly to: string;
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 html = renderEmailHtml(input.text);
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(messages[0], "Subject") ?? null,
193
- inReplyTo: header(messages.at(-1), "Message-ID") ?? null,
194
- references: header(messages.at(-1), "References") ?? null,
195
- text: input.text,
196
- html: withEmailSignature(html, signature),
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
+ "&": "&amp;",
51
+ "<": "&lt;",
52
+ ">": "&gt;",
53
+ "\"": "&quot;",
54
+ "'": "&#39;"
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 };
@@ -0,0 +1,19 @@
1
+ import type { AdmissionSettings } from "../config.js";
2
+ /** Everyone in an opened group sees the reply, including when an employee asks. */
3
+ export declare function isPublicGroup(admission: AdmissionSettings, channel: string, chat: string, sender: string): Promise<boolean>;
4
+ /** An unlinked sender can only submit this message to the workspace's public instructions.
5
+ * No member principal, history, tools, workspace files or channel tokens enter the model call. */
6
+ export declare function answerPublicGroup(input: {
7
+ admission: AdmissionSettings;
8
+ channel: string;
9
+ chat: string;
10
+ sender: string;
11
+ message: string;
12
+ text: string;
13
+ locale?: string;
14
+ post: (text: string) => Promise<unknown>;
15
+ claim?: () => Promise<boolean>;
16
+ finish?: (delivered: boolean) => Promise<void>;
17
+ }): Promise<boolean>;
18
+ /** An authenticated provider join only offers the inviter's own, row-scoped authority. */
19
+ export declare function publicGroupInvite(admission: AdmissionSettings, provider: "slack" | "telegram", channel: string, chat: string, inviter: string): Promise<void>;
@@ -0,0 +1,77 @@
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 { localizedText } from "./admission.mjs";
8
+ import { chatRuntimeRequest } from "./chat-persona.mjs";
9
+ import { ontologyGuestUsage } from "./guest-usage.mjs";
10
+ import { gatewayCostOf } from "./web-search.mjs";
11
+ import { gateway, generateText } from "ai";
12
+ async function isPublicGroup(admission, channel, chat, sender) {
13
+ if (!admission.publicGroups) return false;
14
+ const result = await chatRuntimeRequest("public-turn", {
15
+ channel,
16
+ chat,
17
+ sender,
18
+ check: true
19
+ });
20
+ if (result?.status !== "public" && result?.status !== "closed") throw new Error("Invalid group access.");
21
+ return result.status === "public";
22
+ }
23
+ async function answerPublicGroup(input) {
24
+ const settings = input.admission.publicGroups;
25
+ if (!settings || !input.text.trim()) return false;
26
+ if (input.claim && !await input.claim()) return true;
27
+ let delivered = false;
28
+ try {
29
+ const turn = await chatRuntimeRequest("public-turn", {
30
+ channel: input.channel,
31
+ chat: input.chat,
32
+ sender: input.sender,
33
+ limits: input.admission.limits
34
+ });
35
+ if (turn?.status === "closed") return false;
36
+ if (turn?.status === "limited") {
37
+ const text = localizedText(input.admission.replies.limited, input.locale);
38
+ if (text) await input.post(text);
39
+ delivered = true;
40
+ return true;
41
+ }
42
+ if (turn?.status !== "admitted" || typeof turn.guestId !== "string") throw new Error("Invalid public group admission.");
43
+ const reply = await generateText({
44
+ model: gateway(settings.model),
45
+ system: settings.instructions,
46
+ prompt: input.text.slice(0, 8e3),
47
+ maxRetries: 0,
48
+ maxOutputTokens: 600,
49
+ abortSignal: AbortSignal.timeout(3e4)
50
+ });
51
+ const costUsd = gatewayCostOf(reply.providerMetadata);
52
+ if (costUsd > 0) await ontologyGuestUsage()({
53
+ guestId: turn.guestId,
54
+ costUsd,
55
+ key: JSON.stringify([
56
+ input.channel,
57
+ input.chat,
58
+ input.message
59
+ ]).slice(0, 256)
60
+ });
61
+ const text = reply.text.trim();
62
+ if (!text) throw new Error("The public group answer was empty.");
63
+ await input.post(text.slice(0, 3500));
64
+ delivered = true;
65
+ return true;
66
+ } finally {
67
+ await input.finish?.(delivered);
68
+ }
69
+ }
70
+ async function publicGroupInvite(admission, provider, channel, chat, inviter) {
71
+ if (admission.publicGroups?.trustedJoinChannels?.includes(channel)) await chatRuntimeRequest("public-invite", {
72
+ key: `${channel}:${chat}`,
73
+ provider,
74
+ inviter
75
+ });
76
+ }
77
+ export { answerPublicGroup, isPublicGroup, publicGroupInvite };
@@ -171,6 +171,7 @@ export declare function receive(input: {
171
171
  readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit" | "slack"> & Partial<Pick<SlackInboundMessageContext, "resolveSession" | "isSubscribed">>;
172
172
  readonly message: Pick<SlackMessage, "author" | "text" | "attachments" | "ts"> & Partial<Pick<SlackMessage, "raw">>;
173
173
  readonly direct: boolean;
174
+ readonly mention?: boolean;
174
175
  readonly admission: AdmissionSettings;
175
176
  readonly identities: AgentIdentities;
176
177
  readonly environment: Environment;
@@ -4,6 +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 { answerPublicGroup, isPublicGroup, publicGroupInvite } from "../public-group.mjs";
7
8
  import { admitMessage, localizedText } from "../admission.mjs";
8
9
  import { agentToolsAttribute } from "../agent-tools.mjs";
9
10
  import { agentChats, channelChats } from "../chats.mjs";
@@ -77,7 +78,8 @@ async function reportMembership(input) {
77
78
  if (typeof bot === "string" && user === bot) {
78
79
  if (joined) await input.chats.joined({
79
80
  chatId,
80
- title
81
+ title,
82
+ ...typeof event.inviter === "string" && event.inviter !== bot && event.inviter ? { inviter: event.inviter } : {}
81
83
  });
82
84
  else await input.chats.agentLeft({
83
85
  chatId,
@@ -229,7 +231,8 @@ function segmentstreamSlack(options) {
229
231
  });
230
232
  const registry = options.chats ?? channelChats("slack", (provider) => agentChats({
231
233
  provider,
232
- identities: pairing
234
+ identities: pairing,
235
+ onInvite: (chat, inviter) => publicGroupInvite(options.admission(), "slack", provider, chat, inviter)
233
236
  }));
234
237
  const chats = () => registry;
235
238
  let records = options.archive;
@@ -275,12 +278,13 @@ function segmentstreamSlack(options) {
275
278
  report: reportWithReference
276
279
  }) }
277
280
  };
278
- const admit = (direct) => (ctx, message) => {
281
+ const admit = (direct, mention = false) => (ctx, message) => {
279
282
  const work = requestWork.getStore();
280
283
  return receive({
281
284
  ctx,
282
285
  message,
283
286
  direct,
287
+ mention,
284
288
  admission: options.admission(),
285
289
  identities: pairing(),
286
290
  environment,
@@ -350,7 +354,7 @@ function segmentstreamSlack(options) {
350
354
  fetch: slackFetch
351
355
  },
352
356
  renderers: [slackConfirmationRenderer(options.texts ?? (() => ({})))],
353
- onAppMention: admit(false),
357
+ onAppMention: admit(false, true),
354
358
  onDirectMessage: admit(true),
355
359
  onMessage: async (ctx, message) => {
356
360
  if (!await followsThreadReply({
@@ -476,6 +480,18 @@ async function receive(input) {
476
480
  } } : {},
477
481
  inboxFailed: (error) => report("inbox_report_failed", error)
478
482
  });
483
+ if (!input.direct && (resolution.status === "pairing_required" || resolution.status === "existing" || resolution.status === "created") && await isPublicGroup(admission, currentChannel("slack"), ctx.slack.channelId, user)) {
484
+ if (input.mention && ctx.edit === void 0) await answerPublicGroup({
485
+ admission,
486
+ channel: currentChannel("slack"),
487
+ chat: ctx.slack.channelId,
488
+ sender: user,
489
+ message: message.ts,
490
+ text: message.text,
491
+ post: (text) => ctx.thread.post(text)
492
+ });
493
+ return null;
494
+ }
479
495
  switch (resolution.status) {
480
496
  case "existing":
481
497
  case "created":
@@ -4,6 +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 { publicGroupInvite } from "../public-group.mjs";
7
8
  import { logConfirmationPress } from "./confirmation-press.mjs";
8
9
  import { object } from "../confirmation-description.mjs";
9
10
  import { archivedRoutingMessages } from "../group-routing/routing-context.mjs";
@@ -11,7 +12,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
11
12
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
12
13
  import { handleWorkspaceCallback } from "./callbacks.mjs";
13
14
  import { telegramText, withTelegramTexts } from "./texts.mjs";
14
- import { t as agentBuild } from "../../../_chunks/build-metadata-C_9WeVSz.mjs";
15
+ import { t as agentBuild } from "../../../_chunks/build-metadata-Da-608Iv.mjs";
15
16
  import { attachmentLifecycle } from "./lifecycle.mjs";
16
17
  import { manifestOf } from "../../config.mjs";
17
18
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -158,7 +159,8 @@ function segmentstreamTelegram(options) {
158
159
  }
159
160
  const chats = channelChats("telegram", (provider) => agentChats({
160
161
  provider,
161
- identities: pairing
162
+ identities: pairing,
163
+ onInvite: (chat, inviter) => publicGroupInvite(options.admission?.() ?? manifestOf({}), "telegram", provider, chat, inviter)
162
164
  }));
163
165
  const capture = telegramChatCapture({
164
166
  archive,
@@ -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-C_9WeVSz.mjs";
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";
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { WorkspaceActionAlreadyDispatched } from "../workspace-action.mjs";
8
8
  import { structuredMessage } from "./structured.mjs";
9
+ import { answerPublicGroup, isPublicGroup } from "../public-group.mjs";
9
10
  import { currentChannel } from "../channel-scope.mjs";
10
11
  import { Ot as runtimeEnvelope, f as attachmentsContext, kt as telegramRuntimeSource, n as chatLanguage, o as telegramPrincipal, x as attachmentUrl, xt as reportTelegramError } from "../../../_chunks/principal-DL9NdRRP.mjs";
11
12
  import { routingBurst } from "../group-routing/burst.mjs";
@@ -406,6 +407,22 @@ async function handleInboundMessage(input) {
406
407
  author: authorOf(sent.from, void 0)
407
408
  });
408
409
  }
410
+ if (group && (lookup.status === "pairing_required" || lookup.status === "existing" || lookup.status === "created") && await isPublicGroup(dependencies.admission(), currentChannel("telegram"), String(sent.chat.id), String(sent.from.id))) {
411
+ if (turn && !input.request?.edited) await answerPublicGroup({
412
+ admission: dependencies.admission(),
413
+ channel: currentChannel("telegram"),
414
+ chat: String(sent.chat.id),
415
+ sender: String(sent.from.id),
416
+ message: String(sent.messageId),
417
+ text: sent.text,
418
+ locale: sent.from.languageCode,
419
+ post: (value) => context.telegram.post(value),
420
+ ...input.request?.claimTurn && { claim: input.request.claimTurn },
421
+ ...input.request?.finishClaim && { finish: input.request.finishClaim }
422
+ });
423
+ await observeRaw();
424
+ return null;
425
+ }
409
426
  if (lookup.status !== "existing" && lookup.status !== "created") {
410
427
  const configuredGroupPairing = lookup.status === "pairing_required" && localizedText(dependencies.admission().replies.groupPairingRequired, sent.from.languageCode) !== void 0;
411
428
  await reject(lookup, addressed !== void 0 && (!group || lookup.status === "limited" || configuredGroupPairing));
@@ -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-C_9WeVSz.mjs";
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";
@@ -22,8 +22,14 @@ async function reportMembership(input) {
22
22
  title: typeof chat.title === "string" ? chat.title : ""
23
23
  };
24
24
  if (mine) {
25
- if (isMember(next)) await input.chats.joined(report);
26
- else if (isMember(previous) && (next.status === "left" || next.status === "kicked" || next.status === "restricted")) await input.chats.agentLeft(report);
25
+ if (isMember(next)) {
26
+ const actor = record(update.from);
27
+ const newlyJoined = previous.status === "left" || previous.status === "kicked" || previous.status === "restricted" && previous.is_member === false;
28
+ await input.chats.joined({
29
+ ...report,
30
+ ...newlyJoined && actor.is_bot === false && typeof actor.id === "number" && Number.isSafeInteger(actor.id) && actor.id > 0 ? { inviter: String(actor.id) } : {}
31
+ });
32
+ } else if (isMember(previous) && (next.status === "left" || next.status === "kicked" || next.status === "restricted")) await input.chats.agentLeft(report);
27
33
  return;
28
34
  }
29
35
  const user = record(next.user);
@@ -51,6 +51,8 @@ export interface SearchAnswer {
51
51
  }
52
52
  /** Runs one search. Tests pass their own. */
53
53
  export type Searcher = (input: WebSearchInput, signal?: AbortSignal) => Promise<SearchAnswer>;
54
+ /** The cost AI Gateway reports in a model answer's metadata, as eve reads it. */
55
+ export declare function gatewayCostOf(metadata: unknown): number;
54
56
  /** The search through AI Gateway, with the deployment's own Gateway identity. */
55
57
  export declare const gatewaySearcher: Searcher;
56
58
  /** The pages of the provider's output, or why there are none. */
@@ -85,4 +85,4 @@ async function searchWeb(input, options = {}) {
85
85
  if (answer.output === void 0) throw new WebSearchFailedError("The search did not run; try again.");
86
86
  return searchResultOf(answer.output);
87
87
  }
88
- export { MAXIMUM_EXCERPT_CHARACTERS, MAXIMUM_OBJECTIVE_CHARACTERS, MAXIMUM_QUERIES, MAXIMUM_QUERY_CHARACTERS, MAXIMUM_RESULTS, WEB_SEARCH_MODEL, WebSearchFailedError, gatewaySearcher, searchResultOf, searchWeb };
88
+ export { MAXIMUM_EXCERPT_CHARACTERS, MAXIMUM_OBJECTIVE_CHARACTERS, MAXIMUM_QUERIES, MAXIMUM_QUERY_CHARACTERS, MAXIMUM_RESULTS, WEB_SEARCH_MODEL, WebSearchFailedError, gatewayCostOf, gatewaySearcher, searchResultOf, searchWeb };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.92.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.174.1",
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",