@segmentstream/agent 0.78.0 → 0.80.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 (109) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +1 -1
  3. package/dist/_chunks/{build-metadata-WG90Pemy.mjs → build-metadata-DF7IV-oL.mjs} +1 -1
  4. package/dist/_chunks/{chat-archive-CdumQXGM.mjs → chat-archive-BBd_iZ1d.mjs} +2 -2
  5. package/dist/_chunks/{chat-archive-CUMEaSqy.mjs → chat-archive-DavfKJDI.mjs} +20 -2
  6. package/dist/_chunks/{principal-C7aAjyt4.mjs → principal-CVV9C_nO.mjs} +8 -1
  7. package/dist/extension/config.d.ts +15 -0
  8. package/dist/extension/config.mjs +20 -2
  9. package/dist/extension/connections/ontology.mjs +1 -1
  10. package/dist/extension/hooks/authorization.mjs +1 -1
  11. package/dist/extension/hooks/chat-context.mjs +1 -1
  12. package/dist/extension/hooks/chat-recorder.mjs +1 -1
  13. package/dist/extension/instructions/persona.mjs +1 -1
  14. package/dist/extension/lib/actor.mjs +1 -1
  15. package/dist/extension/lib/admission.d.ts +7 -0
  16. package/dist/extension/lib/admission.mjs +8 -6
  17. package/dist/extension/lib/attachment-tools.mjs +1 -1
  18. package/dist/extension/lib/attachments-send.mjs +1 -1
  19. package/dist/extension/lib/attachments.mjs +1 -1
  20. package/dist/extension/lib/build-metadata.mjs +1 -1
  21. package/dist/extension/lib/chat-address.d.ts +11 -0
  22. package/dist/extension/lib/chat-address.mjs +1 -1
  23. package/dist/extension/lib/chat-archive.d.ts +16 -0
  24. package/dist/extension/lib/chat-archive.mjs +1 -1
  25. package/dist/extension/lib/chat-context.d.ts +7 -0
  26. package/dist/extension/lib/chat-context.mjs +2 -2
  27. package/dist/extension/lib/chat-messages.d.ts +9 -1
  28. package/dist/extension/lib/chat-messages.mjs +5 -5
  29. package/dist/extension/lib/chat-recorder.d.ts +12 -4
  30. package/dist/extension/lib/chat-recorder.mjs +3 -3
  31. package/dist/extension/lib/chat-store.d.ts +6 -0
  32. package/dist/extension/lib/confirmations.mjs +1 -1
  33. package/dist/extension/lib/email/attachments-send.d.ts +6 -4
  34. package/dist/extension/lib/email/attachments-send.mjs +2 -1
  35. package/dist/extension/lib/email/channel.d.ts +31 -5
  36. package/dist/extension/lib/email/channel.mjs +233 -27
  37. package/dist/extension/lib/email/gmail.d.ts +12 -5
  38. package/dist/extension/lib/email/gmail.mjs +12 -0
  39. package/dist/extension/lib/email/message.d.ts +5 -0
  40. package/dist/extension/lib/email/message.mjs +10 -5
  41. package/dist/extension/lib/group-routing/routing-context.mjs +1 -1
  42. package/dist/extension/lib/guest-usage.mjs +1 -1
  43. package/dist/extension/lib/identities.d.ts +2 -0
  44. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  45. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  46. package/dist/extension/lib/model-service-alert.mjs +1 -1
  47. package/dist/extension/lib/ontology-connection.mjs +1 -1
  48. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  49. package/dist/extension/lib/ontology-tools.mjs +1 -1
  50. package/dist/extension/lib/review/client.mjs +68 -31
  51. package/dist/extension/lib/review/hold.d.ts +18 -0
  52. package/dist/extension/lib/review/hold.mjs +7 -1
  53. package/dist/extension/lib/review/judge.mjs +1 -1
  54. package/dist/extension/lib/review/reply.d.ts +5 -0
  55. package/dist/extension/lib/review/reply.mjs +2 -2
  56. package/dist/extension/lib/review/revision-channel.mjs +1 -1
  57. package/dist/extension/lib/role-skill.mjs +1 -1
  58. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  59. package/dist/extension/lib/sent-files.mjs +1 -1
  60. package/dist/extension/lib/slack/adapter.mjs +2 -2
  61. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  62. package/dist/extension/lib/slack/callbacks.mjs +1 -1
  63. package/dist/extension/lib/slack/changes.mjs +1 -1
  64. package/dist/extension/lib/stored-files.mjs +1 -1
  65. package/dist/extension/lib/telegram/adapter.mjs +4 -4
  66. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  67. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  68. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  69. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  70. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  71. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  72. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +1 -1
  73. package/dist/extension/lib/telegram/files.mjs +1 -1
  74. package/dist/extension/lib/telegram/health.mjs +1 -1
  75. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  76. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  77. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  78. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  79. package/dist/extension/lib/telegram/principal.mjs +1 -1
  80. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  81. package/dist/extension/lib/telegram/silent.mjs +1 -1
  82. package/dist/extension/lib/telegram/store-capture.mjs +1 -1
  83. package/dist/extension/lib/telegram/structured.mjs +1 -1
  84. package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
  85. package/dist/extension/lib/web/auth.mjs +1 -1
  86. package/dist/extension/lib/web/channel.mjs +1 -1
  87. package/dist/extension/lib/whatsapp/adapter.mjs +2 -2
  88. package/dist/extension/lib/whatsapp/attachments-send.mjs +2 -2
  89. package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
  90. package/dist/extension/lib/whatsapp/changes.mjs +1 -1
  91. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  92. package/dist/extension/lib/whatsapp/sent.mjs +1 -1
  93. package/dist/extension/lib/workspace-action.mjs +1 -1
  94. package/dist/extension/lib/workspace-channel/attachments-send.mjs +1 -1
  95. package/dist/extension/lib/workspace-channel/channel.mjs +2 -2
  96. package/dist/extension/lib/workspace-chat-archive.mjs +1 -1
  97. package/dist/extension/lib/workspace-source.mjs +1 -1
  98. package/dist/extension/model.mjs +1 -1
  99. package/dist/extension/tools/attachments_discard.mjs +1 -1
  100. package/dist/extension/tools/attachments_list.mjs +1 -1
  101. package/dist/extension/tools/attachments_promote.mjs +1 -1
  102. package/dist/extension/tools/attachments_read.mjs +1 -1
  103. package/dist/extension/tools/attachments_send.mjs +4 -2
  104. package/dist/extension/tools/attachments_stage.mjs +1 -1
  105. package/dist/extension/tools/attachments_table.mjs +1 -1
  106. package/dist/extension/tools/handoff.mjs +1 -1
  107. package/dist/extension/tools/questions_ask.mjs +1 -1
  108. package/dist/extension/tools/workspace_source.mjs +1 -1
  109. package/package.json +2 -2
@@ -6,10 +6,10 @@ import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
6
6
  import { type Gmail } from "./gmail.js";
7
7
  /**
8
8
  * `attachments_send` in an email chat: the stored files go in one reply in the person's Gmail
9
- * thread, from the channel's mailbox, as the channel's text replies go: under the thread's last
10
- * message, marked `Auto-Submitted: auto-replied`, and named by a key of the session and the tool
11
- * call, so a call run again finds the reply it sent rather than sending it twice. The caption is
12
- * the reply's text. The checks and failures are every channel's (`../attachments-send.ts`).
9
+ * thread, from the channel's mailbox, to the people the channel's text replies go to: under the
10
+ * thread's last message, marked `Auto-Submitted: auto-replied`, and named by a key of the session
11
+ * and the tool call, so a call run again finds the reply it sent rather than sending it twice. The
12
+ * caption is the reply's text. The checks and failures are every channel's (`../attachments-send.ts`).
13
13
  */
14
14
  /**
15
15
  * The most bytes of files one reply carries, together: below the 25 MB Gmail takes, with room for
@@ -34,6 +34,8 @@ export declare function sendEmailAttachments(options: {
34
34
  readonly callId: string;
35
35
  /** The connection of the email channel the chat is on, such as `channels.email.connection`. */
36
36
  readonly connection: string | undefined;
37
+ /** The thread's other people the reply copies, as the channel's text replies do. */
38
+ readonly cc?: ReadonlyArray<string>;
37
39
  readonly environment?: Environment;
38
40
  readonly token?: RuntimeToken;
39
41
  readonly fetch?: typeof fetch;
@@ -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 { _ as AttachmentError } from "../../../_chunks/principal-C7aAjyt4.mjs";
7
+ import { _ as AttachmentError } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
8
  import { sendStoredAttachments } from "../attachments-send.mjs";
9
9
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";
@@ -102,6 +102,7 @@ async function sendEmailAttachments(options) {
102
102
  const id = await mailbox.reply({
103
103
  threadId: chat.threadId,
104
104
  to: chat.peer,
105
+ ...options.cc === void 0 || options.cc.length === 0 ? {} : { cc: options.cc },
105
106
  text: input.caption ?? "",
106
107
  key: replyKeyOf(options.sessionId, options.callId, "files"),
107
108
  attachments: read.map(({ file }) => ({
@@ -19,8 +19,10 @@ import { type Gmail } from "./gmail.js";
19
19
  * when Gmail pushes a change and at least every `checkAfterMinutes`, signing the request with the
20
20
  * project's agent webhook secret. A wake carries the cursor the last one answered; the channel
21
21
  * reads what the mailbox received since, starts a turn per message in the person's thread, and
22
- * answers the next cursor. One Gmail thread is one chat with one person. The reply leaves in the
23
- * same thread, or waits for a member when the person's review holds it.
22
+ * answers the next cursor. One Gmail thread is one chat with each person who writes in it, or,
23
+ * with `chats: "thread"`, one chat and one session of everyone in it, each message read by the
24
+ * members it went to. The reply leaves in the same thread, to the person and, as a reply to all, the
25
+ * other people of the mail it answers, or waits for a member when the person's review holds it.
24
26
  *
25
27
  * A reply is an operation of the chat archive, `requested` before it is sent, then `sent` or
26
28
  * `failed`. One Gmail does not take for a while waits there, out of the 16 KiB cursor, and each
@@ -75,14 +77,38 @@ export interface EmailChannelOptions {
75
77
  }
76
78
  /**
77
79
  * One person's private chat in a Gmail thread: the thread and the sender's address. Two people who
78
- * write in the same thread have a chat and a session each, as replies reach only their sender.
80
+ * write in the same thread have a chat and a session each.
79
81
  */
80
82
  export declare function emailChatId(threadId: string, sender: string): string;
83
+ /**
84
+ * The chat a message of `sender` in a Gmail thread is in: the thread itself where the channel keeps
85
+ * one chat per thread (`chats: "thread"`), else the sender's own chat in it.
86
+ */
87
+ export declare function emailChatOf(settings: Pick<EmailSettings, "chats"> | null | undefined, threadId: string, sender: string): string;
88
+ /**
89
+ * The principal's attribute that names the other people of the mail a turn answers, `To` and `Cc`
90
+ * without the sender and the mailbox: a reply to all copies them.
91
+ */
92
+ export declare const EMAIL_OTHERS_ATTRIBUTE = "segmentstreamEmailOthers";
93
+ /**
94
+ * Whom a reply to `principal` copies: the other people of the mail it answers, when the channel
95
+ * replies to all (`reply: "all"`); none when it replies to the sender alone. The first of them, as
96
+ * many as a reply goes to beside its person.
97
+ */
98
+ export declare function replyCopies(principal: SessionAuthContext | null | undefined, settings: Pick<EmailSettings, "reply"> | null | undefined): ReadonlyArray<string>;
81
99
  /**
82
100
  * The principal of an email session: the member who writes from the address, on the email channel
83
- * the current wake runs for.
101
+ * the current wake runs for, with the other people of the mail it answers. In a thread's chat it
102
+ * names the chat and the members who read the mail.
84
103
  */
85
- export declare function emailPrincipal(member: PairedMember, sender: string, threadId: string): SessionAuthContext;
104
+ export declare function emailPrincipal(member: PairedMember, sender: string, threadId: string, options?: {
105
+ /** The other people of the mail the turn answers, whom a reply to all copies. */
106
+ readonly others?: ReadonlyArray<string>;
107
+ /** The chat: the sender's own in the thread when absent. */
108
+ readonly chatId?: string;
109
+ /** The members who read the mail and the replies to it, in a chat several people share. */
110
+ readonly participants?: ReadonlyArray<string>;
111
+ }): SessionAuthContext;
86
112
  /** The email channel of the extension. */
87
113
  export declare function segmentstreamEmail(options: EmailChannelOptions): Channel;
88
114
  /** The email channel's route and events, which {@link segmentstreamEmail} defines as a channel. */
@@ -8,9 +8,10 @@ import { PUBSUB_TOPIC } from "../../config.mjs";
8
8
  import { admitMessage, localizedText, reportUnadmittedChat } from "../admission.mjs";
9
9
  import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
11
- import { Pt as chatAddressOf, S as fetchStoredAttachment, b as agentAttachments, d as prepareInboundMedia, i as memberIdOf, m as turnContent, zt as withChatAddress } from "../../../_chunks/principal-C7aAjyt4.mjs";
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-CVV9C_nO.mjs";
12
12
  import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
13
- import { f as storeOf, h as UNVERIFIED, l as replyEvent, r as chatArchive } from "../../../_chunks/chat-archive-CUMEaSqy.mjs";
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-DavfKJDI.mjs";
14
+ import { ChatStoreError } from "../chat-store.mjs";
14
15
  import { recordChatMessage, recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
15
16
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
16
17
  import { redactDiagnostic } from "../diagnostics.mjs";
@@ -27,7 +28,7 @@ import { inboundMail, parseMail, sentMail } from "./message.mjs";
27
28
  import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
28
29
  import { reply } from "eve/events";
29
30
  import { POST, defineChannel } from "eve/channels";
30
- import { REPLY_KEY_HEADER } from "@segmentstream/ontology/email";
31
+ import { EMAIL_RECIPIENTS_LIMIT, REPLY_KEY_HEADER, isEmailAddress } from "@segmentstream/ontology/email";
31
32
  const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
32
33
  const EMAIL_AUTHENTICATOR = "segmentstream-email";
33
34
  const MESSAGES_PER_WAKE = 20;
@@ -55,15 +56,18 @@ const DISCARDED = new Set([
55
56
  "SPAM",
56
57
  "TRASH"
57
58
  ]);
59
+ const THREADS_REMEMBERED = 1e3;
58
60
  function waitingReply(event) {
59
61
  const key = event.operationId?.startsWith("reply:") ? event.operationId.slice(6) : void 0;
60
62
  const threadId = event.threadId;
61
- const to = threadId !== null && event.chatId.startsWith(`${threadId}:`) ? event.chatId.slice(threadId.length + 1) : void 0;
62
- return key === void 0 || threadId === null || !GMAIL_ID.test(threadId) || to === void 0 || !to.includes("@") || event.text === null ? void 0 : {
63
+ const named = replyRecipients(event);
64
+ const to = named?.to.length === 1 ? named.to[0] : threadId !== null && event.chatId.startsWith(`${threadId}:`) ? event.chatId.slice(threadId.length + 1) : void 0;
65
+ return key === void 0 || threadId === null || !GMAIL_ID.test(threadId) || to === void 0 || !isEmailAddress(to) || event.text === null ? void 0 : {
63
66
  key,
64
67
  chatId: event.chatId,
65
68
  threadId,
66
69
  to,
70
+ cc: (named?.cc ?? []).filter(isEmailAddress).slice(0, EMAIL_RECIPIENTS_LIMIT - 1),
67
71
  text: event.text,
68
72
  participantIds: event.participantIds,
69
73
  sessionId: event.sessionId,
@@ -131,8 +135,17 @@ function decodeCursor(value) {
131
135
  function emailChatId(threadId, sender) {
132
136
  return `${threadId}:${sender}`;
133
137
  }
134
- function emailPrincipal(member, sender, threadId) {
138
+ function emailChatOf(settings, threadId, sender) {
139
+ return settings?.chats === "thread" ? threadId : emailChatId(threadId, sender);
140
+ }
141
+ const EMAIL_OTHERS_ATTRIBUTE = "segmentstreamEmailOthers";
142
+ function replyCopies(principal, settings) {
143
+ const others = principal?.attributes[EMAIL_OTHERS_ATTRIBUTE];
144
+ return settings?.reply !== "all" || !Array.isArray(others) ? [] : others.filter(isEmailAddress).slice(0, EMAIL_RECIPIENTS_LIMIT - 1);
145
+ }
146
+ function emailPrincipal(member, sender, threadId, options = {}) {
135
147
  const channel = currentChannel("email");
148
+ const others = options.others ?? [];
136
149
  return withChatAddress({
137
150
  authenticator: EMAIL_AUTHENTICATOR,
138
151
  issuer: "email",
@@ -146,12 +159,14 @@ function emailPrincipal(member, sender, threadId) {
146
159
  ...agentToolsAttribute(member.agentTools),
147
160
  ...member.name === null ? {} : { memberName: member.name },
148
161
  ...member.locale === void 0 ? {} : { locale: member.locale },
149
- ...channelAttributes("email", channel)
162
+ ...channelAttributes("email", channel),
163
+ ...others.length === 0 ? {} : { [EMAIL_OTHERS_ATTRIBUTE]: others.slice(0, EMAIL_RECIPIENTS_LIMIT - 1) },
164
+ ...options.participants === void 0 ? {} : { [PARTICIPANTS_ATTRIBUTE]: options.participants }
150
165
  }
151
166
  }, {
152
167
  provider: "email",
153
168
  ...channel === "email" ? {} : { channel },
154
- chatId: emailChatId(threadId, sender),
169
+ chatId: options.chatId ?? emailChatId(threadId, sender),
155
170
  threadId,
156
171
  kind: "private",
157
172
  peer: sender
@@ -235,6 +250,7 @@ function emailChannelDefinition(options) {
235
250
  return await mailbox().reply({
236
251
  threadId: reply.threadId,
237
252
  to: reply.to,
253
+ ...reply.cc.length === 0 ? {} : { cc: reply.cc },
238
254
  text: reply.text,
239
255
  key: reply.key
240
256
  });
@@ -257,7 +273,11 @@ function emailChannelDefinition(options) {
257
273
  text: reply.text,
258
274
  status,
259
275
  ...messageId === void 0 ? {} : { messageId },
260
- ...status === "requested" ? { at: reply.at } : {}
276
+ ...status === "requested" ? { at: reply.at } : {},
277
+ recipients: {
278
+ to: [reply.to],
279
+ cc: reply.cc
280
+ }
261
281
  }));
262
282
  return true;
263
283
  } catch (error) {
@@ -326,7 +346,143 @@ function emailChannelDefinition(options) {
326
346
  }
327
347
  return resolved && page.nextCursor !== null;
328
348
  }
329
- async function dispatch(added, mail, args, skipped) {
349
+ async function membersOf(addresses, known = new Map()) {
350
+ const unique = [...new Set(addresses)].slice(0, EMAIL_RECIPIENTS_LIMIT);
351
+ await Promise.all(unique.filter((address) => !known.has(address)).map(async (address) => {
352
+ const found = await people().lookup({
353
+ provider: "email",
354
+ externalId: address
355
+ });
356
+ known.set(address, found.status === "paired" ? found.member.id : null);
357
+ }));
358
+ return [...new Set(unique.flatMap((address) => {
359
+ const id = known.get(address);
360
+ return id === null || id === void 0 ? [] : [id];
361
+ }))];
362
+ }
363
+ const histories = new Set();
364
+ async function threadHistory(threadId, before, own) {
365
+ const channel = currentChannel("email");
366
+ const key = `${channel}:${threadId}`;
367
+ const remember = () => {
368
+ histories.add(key);
369
+ if (histories.size > THREADS_REMEMBERED) histories.delete(histories.values().next().value);
370
+ };
371
+ if (histories.has(key)) return;
372
+ const store = await storeOf(archive());
373
+ if (store === void 0) return;
374
+ const [newest] = (await store.read({
375
+ channel,
376
+ chatId: threadId,
377
+ limit: 1
378
+ })).messages;
379
+ if (newest !== void 0 && (newest.importedAt ?? null) === null) {
380
+ remember();
381
+ return;
382
+ }
383
+ const gmail = mailbox();
384
+ const listed = await gmail.thread(threadId);
385
+ const index = listed.findIndex((message) => message.id === before);
386
+ const earlier = (index < 0 ? [] : listed.slice(0, index)).filter((message) => !message.labelIds.some((label) => DISCARDED.has(label))).slice(-20);
387
+ const known = new Map();
388
+ for (const { id, labelIds } of earlier) {
389
+ let raw;
390
+ let parsed;
391
+ try {
392
+ raw = await gmail.raw(id);
393
+ } catch (error) {
394
+ if (retryable(error)) throw error;
395
+ log("[segmentstream] email thread history message skipped", {
396
+ message: id,
397
+ error: redactDiagnostic(error, new Set())
398
+ });
399
+ continue;
400
+ }
401
+ if (raw.labelIds.some((label) => DISCARDED.has(label))) continue;
402
+ try {
403
+ parsed = await parseMail(raw.bytes);
404
+ } catch (error) {
405
+ log("[segmentstream] email thread history message skipped", {
406
+ message: id,
407
+ error: redactDiagnostic(error, new Set())
408
+ });
409
+ continue;
410
+ }
411
+ const at = Date.parse(parsed.date ?? "");
412
+ if (!Number.isFinite(at)) continue;
413
+ const sent = labelIds.includes("SENT") || raw.labelIds.includes("SENT");
414
+ const eventId = `email:history:${id}`;
415
+ let event;
416
+ if (sent) {
417
+ const mail = sentMail(parsed, own);
418
+ const agent = parsed.headers.some((header) => header.key === REPLY_KEY_HEADER.toLowerCase());
419
+ if (mail.text === "" && mail.attachments.length === 0) continue;
420
+ event = chatEvent({
421
+ eventId,
422
+ provider: channel,
423
+ chatId: threadId,
424
+ chatType: "private",
425
+ threadId,
426
+ participantIds: await membersOf(mail.recipients, known),
427
+ senderId: agent ? AGENT_SENDER : mail.fromAddress ?? null,
428
+ senderName: agent ? null : mail.fromName ?? null,
429
+ senderIsBot: agent || mail.automated,
430
+ kind: "outbound",
431
+ messageId: id,
432
+ text: mail.text,
433
+ status: "sent",
434
+ at: new Date(at).toISOString(),
435
+ attachments: mail.attachments.map((file, position) => ({
436
+ id: `${eventId}:file:${position}`,
437
+ kind: "file",
438
+ filename: file.filename,
439
+ contentType: file.contentType,
440
+ size: file.size
441
+ }))
442
+ });
443
+ } else {
444
+ const mail = inboundMail(parsed, own);
445
+ if (!mail.verified || mail.skip !== void 0) continue;
446
+ event = chatEvent({
447
+ eventId,
448
+ provider: channel,
449
+ chatId: threadId,
450
+ chatType: "private",
451
+ threadId,
452
+ participantIds: await membersOf([mail.from, ...mail.others], known),
453
+ senderId: mail.from,
454
+ senderName: mail.fromName ?? null,
455
+ kind: "inbound",
456
+ messageId: id,
457
+ text: turnText(mail),
458
+ at: new Date(at).toISOString(),
459
+ attachments: mail.attachments.map((file, position) => ({
460
+ id: `${eventId}:file:${position}`,
461
+ kind: "file",
462
+ filename: file.filename,
463
+ contentType: file.contentType,
464
+ size: file.bytes.byteLength
465
+ }))
466
+ });
467
+ }
468
+ try {
469
+ await store.record({
470
+ ...messageInput(event),
471
+ imported: true
472
+ });
473
+ } catch (error) {
474
+ if (error instanceof ChatStoreError && error.status === 400) {
475
+ log("[segmentstream] email thread history not imported", { error: redactDiagnostic(error, new Set()) });
476
+ break;
477
+ }
478
+ throw error;
479
+ }
480
+ }
481
+ remember();
482
+ }
483
+ async function dispatch(added, mail, args, skipped, current, own) {
484
+ const thread = current.chats === "thread";
485
+ const chatId = emailChatOf(current, added.threadId, mail.from);
330
486
  const admission = options.admission();
331
487
  const resolution = await admitMessage({
332
488
  identity: {
@@ -341,9 +497,15 @@ function emailChannelDefinition(options) {
341
497
  settings: admission,
342
498
  sendNotice: (text) => answer(added.threadId, mail.from, text),
343
499
  noticeFailed: (error) => log("[segmentstream] email notice failed", { error: redactDiagnostic(error, new Set()) }),
344
- chat: {
500
+ chat: thread ? {
501
+ channel: currentChannel("email"),
502
+ chatId,
503
+ threadId: added.threadId,
504
+ shared: true,
505
+ ...mail.subject === "" ? {} : { title: mail.subject }
506
+ } : {
345
507
  channel: currentChannel("email"),
346
- chatId: emailChatId(added.threadId, mail.from),
508
+ chatId,
347
509
  threadId: added.threadId,
348
510
  recipient: mail.from
349
511
  },
@@ -368,14 +530,17 @@ function emailChannelDefinition(options) {
368
530
  return skipped("limited");
369
531
  }
370
532
  if (resolution.status !== "existing" && resolution.status !== "created") return skipped(resolution.status === "refused" ? "refused" : "identity_unknown");
533
+ const participants = thread ? await membersOf([mail.from, ...mail.others], new Map([[mail.from, resolution.member.id]])) : void 0;
534
+ if (thread) await threadHistory(added.threadId, added.id, own);
371
535
  if (resolution.handled === true) {
372
536
  await recordHandledMessage(archive(), {
373
537
  chat: {
374
538
  channel: currentChannel("email"),
375
- chatId: emailChatId(added.threadId, mail.from),
539
+ chatId,
376
540
  threadId: added.threadId
377
541
  },
378
542
  memberId: resolution.member.id,
543
+ ...participants === void 0 ? {} : { participantIds: participants },
379
544
  senderId: mail.from,
380
545
  senderName: mail.fromName ?? null,
381
546
  messageId: added.id,
@@ -388,7 +553,11 @@ function emailChannelDefinition(options) {
388
553
  });
389
554
  return;
390
555
  }
391
- const auth = emailPrincipal(resolution.member, mail.from, added.threadId);
556
+ const auth = emailPrincipal(resolution.member, mail.from, added.threadId, {
557
+ others: mail.others,
558
+ chatId,
559
+ ...participants === void 0 ? {} : { participants }
560
+ });
392
561
  const memberId = memberIdOf(auth);
393
562
  const inbound = mail.attachments.map((file, index) => ({
394
563
  key: `${added.id}:${index}`,
@@ -430,7 +599,7 @@ function emailChannelDefinition(options) {
430
599
  ...inbound.length === 0 ? {} : { store: {
431
600
  attachments: files(),
432
601
  memberId,
433
- chat: providerChat(currentChannel("email"), emailChatId(added.threadId, mail.from)),
602
+ chat: providerChat(currentChannel("email"), chatId),
434
603
  source: "email",
435
604
  sourceRef: (index) => `${added.threadId}:${added.id}:${index}`
436
605
  } }
@@ -458,7 +627,7 @@ function emailChannelDefinition(options) {
458
627
  text: ""
459
628
  }
460
629
  });
461
- await args.from(emailChatId(added.threadId, mail.from)).send(content, {
630
+ await args.from(chatId).send(content, {
462
631
  auth,
463
632
  idempotencyKey: currentKey("email", `email:${added.id}`),
464
633
  ...media.context.length === 0 ? {} : { context: media.context }
@@ -483,6 +652,27 @@ function emailChannelDefinition(options) {
483
652
  const mail = sentMail(parsed, own);
484
653
  if (mail.automated || parsed.headers.some((header) => header.key === REPLY_KEY_HEADER.toLowerCase()) || threadId === void 0 || mail.text === "" && mail.attachments.length === 0) return;
485
654
  const record = current.record === "all" && (current.recordQuery === void 0 || await finds(current.recordQuery, id, parsed.messageId)) ? "all" : "agent";
655
+ if (current.chats === "thread") {
656
+ if (record === "all") await threadHistory(threadId, id, own);
657
+ await recordSentOutside(archive(), {
658
+ provider: currentChannel("email"),
659
+ chatId: threadId,
660
+ threadId,
661
+ eventId: currentKey("email", `email:staff:${id}`),
662
+ participantIds: await membersOf(mail.recipients),
663
+ by: "human",
664
+ senderId: mail.fromAddress ?? null,
665
+ senderName: mail.fromName ?? null,
666
+ messageId: id,
667
+ text: mail.text,
668
+ files: mail.attachments.map((file) => ({
669
+ name: file.filename,
670
+ mimeType: file.contentType,
671
+ size: file.size
672
+ }))
673
+ }, { record });
674
+ return;
675
+ }
486
676
  for (const recipient of mail.recipients) await recordSentOutside(archive(), {
487
677
  provider: currentChannel("email"),
488
678
  chatId: emailChatId(threadId, recipient),
@@ -504,27 +694,30 @@ function emailChannelDefinition(options) {
504
694
  if (messageId === void 0) return false;
505
695
  return (await mailbox().search(`(${query}) rfc822msgid:${messageId.replace(/[<>"]/gu, "")}`, 5)).includes(id);
506
696
  }
507
- async function recordSkipped(current, message, mail, reason) {
697
+ async function recordSkipped(current, message, mail, reason, own) {
508
698
  if (current.record !== "all") return;
509
699
  const store = await storeOf(archive());
510
700
  if (store === void 0 || current.recordQuery !== void 0 && !await finds(current.recordQuery, message.id, mail.messageId)) return;
701
+ const thread = current.chats === "thread";
511
702
  const chat = {
512
703
  channel: currentChannel("email"),
513
- chatId: emailChatId(message.threadId, mail.from),
704
+ chatId: emailChatOf(current, message.threadId, mail.from),
514
705
  messageId: message.id
515
706
  };
516
707
  const unverified = reason === UNVERIFIED;
517
- const [latest] = unverified ? [] : (await archive().context({
708
+ const [latest] = unverified || thread ? [] : (await archive().context({
518
709
  provider: chat.channel,
519
710
  chatId: chat.chatId,
520
711
  threadId: message.threadId,
521
712
  limit: 1
522
713
  })).events;
714
+ const participants = unverified ? [] : thread ? await membersOf([mail.from, ...mail.others]) : latest?.participantIds ?? [];
715
+ if (thread) await threadHistory(message.threadId, message.id, own);
523
716
  await recordChatMessage(archive(), {
524
717
  provider: chat.channel,
525
718
  chatId: chat.chatId,
526
719
  threadId: message.threadId,
527
- participantIds: latest?.participantIds ?? [],
720
+ participantIds: participants,
528
721
  eventId: currentKey("email", `email:recorded:${message.id}`),
529
722
  direction: "inbound",
530
723
  by: reason === "automated" || reason === "bounce" ? "bot" : "human",
@@ -545,7 +738,7 @@ function emailChannelDefinition(options) {
545
738
  disposition: "skipped",
546
739
  reason
547
740
  });
548
- if (!unverified && (latest === void 0 || latest.participantIds.length === 0)) await reportUnadmittedChat({
741
+ if (!unverified && (thread || participants.length === 0)) await reportUnadmittedChat({
549
742
  identity: {
550
743
  provider: "email",
551
744
  externalId: mail.from,
@@ -555,7 +748,13 @@ function emailChannelDefinition(options) {
555
748
  ...mail.fromName === void 0 ? {} : { display: mail.fromName }
556
749
  },
557
750
  identities: people(),
558
- chat: {
751
+ chat: thread ? {
752
+ channel: chat.channel,
753
+ chatId: chat.chatId,
754
+ threadId: message.threadId,
755
+ shared: true,
756
+ ...mail.subject === "" ? {} : { title: mail.subject }
757
+ } : {
559
758
  channel: chat.channel,
560
759
  chatId: chat.chatId,
561
760
  threadId: message.threadId,
@@ -581,12 +780,12 @@ function emailChannelDefinition(options) {
581
780
  ...added,
582
781
  threadId: raw.threadId
583
782
  };
584
- const skipped = (reason) => recordSkipped(current, message, mail, reason);
783
+ const skipped = (reason) => recordSkipped(current, message, mail, reason, own);
585
784
  if (mail.skip === "no_sender" || mail.skip === "own_address") return;
586
785
  if (!mail.verified) return skipped(UNVERIFIED);
587
786
  if (mail.skip !== void 0) return skipped(mail.skip);
588
787
  if (!restarted && !await finds(current.query, added.id, mail.messageId)) return skipped("not_addressed");
589
- await dispatch(message, mail, args, skipped);
788
+ await dispatch(message, mail, args, skipped, current, own);
590
789
  }
591
790
  async function wake(request, args) {
592
791
  const current = settings();
@@ -749,22 +948,29 @@ function emailChannelDefinition(options) {
749
948
  if (outcome !== "completed" || chat?.provider !== "email" || chat.peer === void 0) return;
750
949
  const text = replyText(ctx.view, turnId);
751
950
  if (completionKind(text) !== "reply") return;
951
+ const cc = replyCopies(principal, settings());
752
952
  const reviewing = review()?.review;
753
953
  if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
754
954
  principal,
755
955
  sessionId: ctx.session.id,
756
956
  turnId,
757
957
  partId: turnId,
758
- text
958
+ text,
959
+ recipients: {
960
+ to: [chat.peer],
961
+ cc
962
+ }
759
963
  }))) return;
760
964
  const memberId = memberIdOf(principal);
965
+ const participantIds = participantsOf(principal) ?? (memberId === void 0 ? [] : [memberId]);
761
966
  const reply = {
762
967
  key: replyKeyOf(ctx.session.id, turnId),
763
968
  chatId: chat.chatId,
764
969
  threadId: chat.threadId,
765
970
  to: chat.peer,
971
+ cc,
766
972
  text,
767
- participantIds: memberId === void 0 ? [] : [memberId],
973
+ participantIds,
768
974
  sessionId: ctx.session.id,
769
975
  turnId,
770
976
  at: new Date(now()).toISOString()
@@ -780,4 +986,4 @@ function emailChannelDefinition(options) {
780
986
  fetchFile: (url, context) => fetchStoredAttachment(files(), url, context)
781
987
  };
782
988
  }
783
- export { EMAIL_AUTHENTICATOR, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailPrincipal, segmentstreamEmail };
989
+ export { EMAIL_AUTHENTICATOR, EMAIL_OTHERS_ATTRIBUTE, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailChatOf, emailPrincipal, replyCopies, segmentstreamEmail };
@@ -64,18 +64,25 @@ export interface Gmail {
64
64
  readonly labelIds: ReadonlyArray<string>;
65
65
  readonly headers: ReadonlyMap<string, string>;
66
66
  }>;
67
+ /** A thread's messages, oldest first, by id with their labels, without headers or bodies. */
68
+ thread(threadId: string): Promise<ReadonlyArray<{
69
+ readonly id: string;
70
+ readonly labelIds: ReadonlyArray<string>;
71
+ }>>;
67
72
  /** Asks Gmail to push the mailbox's changes to `topic`; resolves the watch's expiry. */
68
73
  watch(topic: string): Promise<number>;
69
74
  /**
70
- * Replies in `threadId` to `to`, under the thread's last message, with the reply's Markdown as
71
- * HTML and as plain text and the files after it, marked `Auto-Submitted: auto-replied`.
72
- * Resolves the sent message's id. With `key`, a message in the thread that already carries it
73
- * is the reply, sent by an earlier attempt whose answer was lost: its id is returned and
74
- * nothing is sent.
75
+ * Replies in `threadId` to `to`, copying `cc`, under the thread's last message, with the reply's
76
+ * Markdown as HTML and as plain text and the files after it, marked
77
+ * `Auto-Submitted: auto-replied`. Resolves the sent message's id. With `key`, a message in the
78
+ * thread that already carries it is the reply, sent by an earlier attempt whose answer was lost:
79
+ * its id is returned and nothing is sent.
75
80
  */
76
81
  reply(input: {
77
82
  readonly threadId: string;
78
83
  readonly to: string;
84
+ /** The thread's other people the reply copies; none when absent. */
85
+ readonly cc?: ReadonlyArray<string>;
79
86
  readonly text: string;
80
87
  readonly key?: string;
81
88
  readonly attachments?: ReadonlyArray<EmailAttachment>;
@@ -167,6 +167,17 @@ function gmail(proxy) {
167
167
  headers: found
168
168
  };
169
169
  },
170
+ async thread(threadId) {
171
+ if (!GMAIL_ID.test(threadId)) throw new GmailError("threads.get", 400);
172
+ const body = await ok("threads.get", "GET", `/threads/${threadId}?format=minimal&fields=messages(id,labelIds)`);
173
+ return (Array.isArray(body.messages) ? body.messages : []).flatMap((message) => {
174
+ const id = text(message.id);
175
+ return id === void 0 || !GMAIL_ID.test(id) ? [] : [{
176
+ id,
177
+ labelIds: Array.isArray(message.labelIds) ? message.labelIds.filter((label) => typeof label === "string") : []
178
+ }];
179
+ });
180
+ },
170
181
  async watch(topic) {
171
182
  const body = await ok("watch", "POST", "/watch", {
172
183
  topicName: topic,
@@ -191,6 +202,7 @@ function gmail(proxy) {
191
202
  }
192
203
  const raw = emailReplyMessage({
193
204
  to: input.to,
205
+ ...input.cc === void 0 || input.cc.length === 0 ? {} : { cc: input.cc },
194
206
  subject: header(messages[0], "Subject") ?? null,
195
207
  inReplyTo: header(messages.at(-1), "Message-ID") ?? null,
196
208
  references: header(messages.at(-1), "References") ?? null,
@@ -16,6 +16,11 @@ export interface InboundMail {
16
16
  readonly messageId: string | undefined;
17
17
  /** What the person wrote, without the history they quoted. */
18
18
  readonly text: string;
19
+ /**
20
+ * Whom else the message went to, in `To` and `Cc`, in lower case: without the sender and the
21
+ * mailbox's own addresses. A reply to all copies them.
22
+ */
23
+ readonly others: ReadonlyArray<string>;
19
24
  readonly attachments: ReadonlyArray<MailAttachment>;
20
25
  /**
21
26
  * Whether Gmail's receiving server reported DMARC passing for the sender's own domain: the
@@ -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 { isEmailAddress } from "@segmentstream/ontology/email";
7
8
  const RECEIVER = "mx.google.com";
8
9
  const MAIL_TEXT_LIMIT = 2e4;
9
10
  const ATTRIBUTION_LENGTH = 500;
@@ -14,6 +15,13 @@ function mailbox(address) {
14
15
  name: address.name.trim()
15
16
  };
16
17
  }
18
+ function recipientsOf(email, own) {
19
+ const addresses = [...email.to ?? [], ...email.cc ?? []].flatMap((address) => address.group ?? [address]).flatMap((address) => {
20
+ const found = mailbox(address);
21
+ return found === void 0 || !isEmailAddress(found.address) || own.has(found.address) ? [] : [found.address];
22
+ });
23
+ return [...new Set(addresses)];
24
+ }
17
25
  function header(headers, key) {
18
26
  return headers.find((item) => item.key === key)?.value.trim();
19
27
  }
@@ -59,6 +67,7 @@ function inboundMail(email, own) {
59
67
  subject: (email.subject ?? "").replace(/[\r\n]+/gu, " ").trim(),
60
68
  messageId: email.messageId?.trim(),
61
69
  text,
70
+ others: recipientsOf(email, own).filter((address) => address !== from),
62
71
  attachments: email.attachments.flatMap((attachment) => attachment.disposition === "inline" && attachment.mimeType.startsWith("image/") ? [] : [{
63
72
  filename: attachment.filename ?? "attachment",
64
73
  contentType: attachment.mimeType || "application/octet-stream",
@@ -70,14 +79,10 @@ function inboundMail(email, own) {
70
79
  }
71
80
  function sentMail(email, own) {
72
81
  const sender = mailbox(email.from);
73
- const recipients = [...email.to ?? [], ...email.cc ?? []].flatMap((address) => address.group ?? [address]).flatMap((address) => {
74
- const found = mailbox(address);
75
- return found === void 0 || !found.address.includes("@") || own.has(found.address) ? [] : [found.address];
76
- });
77
82
  const body = email.text !== void 0 && email.text.trim() !== "" ? email.text : email.html === void 0 ? "" : htmlText(email.html);
78
83
  const submitted = header(email.headers, "auto-submitted")?.toLowerCase();
79
84
  return {
80
- recipients: [...new Set(recipients)],
85
+ recipients: recipientsOf(email, own),
81
86
  fromAddress: sender?.address,
82
87
  fromName: sender?.name === "" ? void 0 : sender?.name,
83
88
  text: withoutQuotedHistory(body).slice(0, MAIL_TEXT_LIMIT),