@segmentstream/ontology 0.166.1 → 0.167.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.167.0
4
+
5
+ Staff answer an email thread's chat (`chats: "thread"`) from the inbox. `agent_chat.postMessage`,
6
+ and `send` as the agent, into a thread's chat reply to the thread's latest mail, to everyone in it,
7
+ as the agent's reply does: to its sender, copying the other people of its `To` and `Cc` without the
8
+ mailbox's own address, or, under the mailbox's own mail, to whom that mail went; in the same
9
+ thread, with `Re:` and the thread's subject, `In-Reply-To` and `References`, from the mailbox. The
10
+ reply is read in the chat by the members among the people it went to. A thread the mailbox cannot
11
+ read is refused before anything is reserved or sent, and a replay of the key returns the first
12
+ delivery without reading the thread again. Before, such a post was refused as having no person to
13
+ answer.
14
+
15
+ A reply to mail never threads under a draft of the mailbox's: it goes under the thread's last
16
+ message anyone received. A staff reply in a person's email chat is named by its own post
17
+ (`X-SegmentStream-Reply: post-…`) rather than by the chat, as the agent's replies are named by
18
+ theirs.
19
+
3
20
  ## 0.166.1
4
21
 
5
22
  In an app preview that runs the agent, the agent's tools and recall now act for an eval session's
package/dist/email.d.ts CHANGED
@@ -18,6 +18,26 @@ export declare function emailRecipients(input: {
18
18
  readonly to: string | ReadonlyArray<string>;
19
19
  readonly cc?: ReadonlyArray<string>;
20
20
  }): EmailRecipients;
21
+ /**
22
+ * The plain addresses an address header lists (`To`, `Cc`, `From`), in lower case and once each:
23
+ * `Name <a@example.com>` and a bare `a@example.com` alike, a group's members for a group, and
24
+ * nothing a quoted name or a comment holds. Anything that is no plain address is left out.
25
+ */
26
+ export declare function headerAddresses(value: string | null | undefined): ReadonlyArray<string>;
27
+ /** The people of one message, as its `From`, `To` and `Cc` headers name them. */
28
+ export interface EmailParties {
29
+ readonly from: string | null | undefined;
30
+ readonly to: string | null | undefined;
31
+ readonly cc: string | null | undefined;
32
+ }
33
+ /**
34
+ * Whom a reply to all of a message goes to, as the email channel's agent replies to all: the
35
+ * message's sender in `To`, and the other addresses of its `To` and `Cc` in `Cc`, without the
36
+ * mailbox's own addresses. A reply to the mailbox's own message goes to whom that message went to,
37
+ * its `To`, and copies its `Cc`. At most {@link EMAIL_RECIPIENTS_LIMIT} together; `undefined` when
38
+ * the message names no one else.
39
+ */
40
+ export declare function replyAllRecipients(message: EmailParties, own: ReadonlyArray<string>): EmailRecipients | undefined;
21
41
  /**
22
42
  * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
23
43
  * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
package/dist/email.js CHANGED
@@ -37,6 +37,98 @@ export function emailRecipients(input) {
37
37
  }
38
38
  return { to, cc };
39
39
  }
40
+ /**
41
+ * The plain addresses an address header lists (`To`, `Cc`, `From`), in lower case and once each:
42
+ * `Name <a@example.com>` and a bare `a@example.com` alike, a group's members for a group, and
43
+ * nothing a quoted name or a comment holds. Anything that is no plain address is left out.
44
+ */
45
+ export function headerAddresses(value) {
46
+ const items = [];
47
+ let current = "";
48
+ let quoted = false;
49
+ let comment = 0;
50
+ let angle = false;
51
+ for (let index = 0; index < (value ?? "").length; index++) {
52
+ const character = value[index];
53
+ if (quoted) {
54
+ if (character === "\\") {
55
+ index++;
56
+ }
57
+ else if (character === '"') {
58
+ quoted = false;
59
+ }
60
+ continue;
61
+ }
62
+ if (comment > 0) {
63
+ if (character === "\\") {
64
+ index++;
65
+ }
66
+ else if (character === "(") {
67
+ comment++;
68
+ }
69
+ else if (character === ")") {
70
+ comment--;
71
+ }
72
+ continue;
73
+ }
74
+ if (character === '"') {
75
+ quoted = true;
76
+ }
77
+ else if (character === "(") {
78
+ comment = 1;
79
+ }
80
+ else if (character === "<") {
81
+ angle = true;
82
+ // Only what the brackets hold names the address: the name before them is dropped.
83
+ current = "<";
84
+ }
85
+ else if (character === ">") {
86
+ angle = false;
87
+ current += ">";
88
+ }
89
+ else if (!angle && (character === "," || character === ";")) {
90
+ items.push(current);
91
+ current = "";
92
+ }
93
+ else if (!angle && character === ":") {
94
+ // A group's name: its members follow.
95
+ current = "";
96
+ }
97
+ else {
98
+ current += character;
99
+ }
100
+ }
101
+ items.push(current);
102
+ const addresses = items.flatMap((item) => {
103
+ const bracketed = /<([^<>]*)>/.exec(item)?.[1];
104
+ const address = (bracketed ?? item).trim().toLowerCase();
105
+ return isEmailAddress(address) ? [address] : [];
106
+ });
107
+ return [...new Set(addresses)];
108
+ }
109
+ /**
110
+ * Whom a reply to all of a message goes to, as the email channel's agent replies to all: the
111
+ * message's sender in `To`, and the other addresses of its `To` and `Cc` in `Cc`, without the
112
+ * mailbox's own addresses. A reply to the mailbox's own message goes to whom that message went to,
113
+ * its `To`, and copies its `Cc`. At most {@link EMAIL_RECIPIENTS_LIMIT} together; `undefined` when
114
+ * the message names no one else.
115
+ */
116
+ export function replyAllRecipients(message, own) {
117
+ const mailbox = new Set(own.map((address) => address.trim().toLowerCase()));
118
+ const others = (list) => list.filter((address) => !mailbox.has(address));
119
+ const from = headerAddresses(message.from)[0];
120
+ const sender = from !== undefined && !mailbox.has(from) ? from : undefined;
121
+ const to = headerAddresses(message.to);
122
+ const cc = headerAddresses(message.cc);
123
+ const primary = sender === undefined ? others(to) : [sender];
124
+ const copies = others(sender === undefined ? cc : [...to, ...cc]).filter((address) => !primary.includes(address));
125
+ // A message of the mailbox's that went to no one in `To` is answered to its first copy.
126
+ const all = [...primary, ...copies].slice(0, EMAIL_RECIPIENTS_LIMIT);
127
+ const named = Math.max(Math.min(primary.length, all.length), Math.min(all.length, 1));
128
+ return all.length === 0
129
+ ? undefined
130
+ : emailRecipients({ to: all.slice(0, named), cc: all.slice(named) });
131
+ }
40
132
  /**
41
133
  * An address header, folded so that no line runs much past 78 characters however many addresses it
42
134
  * lists: each line after the first starts with a space, as RFC 5322 folds a header.
@@ -1296,8 +1296,9 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
1296
1296
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
1297
1297
  * declared connection, and the attribution it adds. Absent, or without a channel, delivers
1298
1298
  * nowhere. The channel named after each kind has its key; `channels` holds the others by name,
1299
- * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail leave
1300
- * from; no chat post goes to it, nor to another channel of its kind. Within version 16, a
1299
+ * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail and
1300
+ * staff's replies in the inbox leave from; no other chat post goes to it, nor to another channel
1301
+ * of its kind. Within version 16, a
1301
1302
  * channel may carry `files: { keep: true }`, written only when declared: its chats keep their
1302
1303
  * files as long as their messages. Older readers ignore it and keep files 24 hours.
1303
1304
  */
@@ -3301,8 +3302,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3301
3302
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
3302
3303
  * declared connection, and the attribution it adds. Absent, or without a channel, delivers
3303
3304
  * nowhere. The channel named after each kind has its key; `channels` holds the others by name,
3304
- * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail leave
3305
- * from; no chat post goes to it, nor to another channel of its kind. Within version 16, a
3305
+ * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail and
3306
+ * staff's replies in the inbox leave from; no other chat post goes to it, nor to another channel
3307
+ * of its kind. Within version 16, a
3306
3308
  * channel may carry `files: { keep: true }`, written only when declared: its chats keep their
3307
3309
  * files as long as their messages. Older readers ignore it and keep files 24 hours.
3308
3310
  */
@@ -3804,8 +3806,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3804
3806
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
3805
3807
  * declared connection, and the attribution it adds. Absent, or without a channel, delivers
3806
3808
  * nowhere. The channel named after each kind has its key; `channels` holds the others by name,
3807
- * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail leave
3808
- * from; no chat post goes to it, nor to another channel of its kind. Within version 16, a
3809
+ * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail and
3810
+ * staff's replies in the inbox leave from; no other chat post goes to it, nor to another channel
3811
+ * of its kind. Within version 16, a
3809
3812
  * channel may carry `files: { keep: true }`, written only when declared: its chats keep their
3810
3813
  * files as long as their messages. Older readers ignore it and keep files 24 hours.
3811
3814
  */
package/dist/manifest.js CHANGED
@@ -609,8 +609,9 @@ const OntologyManifestModel = Schema.Struct({
609
609
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
610
610
  * declared connection, and the attribution it adds. Absent, or without a channel, delivers
611
611
  * nowhere. The channel named after each kind has its key; `channels` holds the others by name,
612
- * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail leave
613
- * from; no chat post goes to it, nor to another channel of its kind. Within version 16, a
612
+ * with their kinds. `email`, within version 15, is the mailbox reviewed replies to mail and
613
+ * staff's replies in the inbox leave from; no other chat post goes to it, nor to another channel
614
+ * of its kind. Within version 16, a
614
615
  * channel may carry `files: { keep: true }`, written only when declared: its chats keep their
615
616
  * files as long as their messages. Older readers ignore it and keep files 24 hours.
616
617
  */
@@ -17,7 +17,7 @@ import { reviewSender } from "./review-delivery.js";
17
17
  import { chatPeopleQuery, historyImporter } from "./history-import.js";
18
18
  import { reviewReviser } from "./review-revision.js";
19
19
  import { CHAT_DRAFT_PERMISSION, chatDrafter } from "./chat-draft.js";
20
- import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
20
+ import { channelIdentityProvider, WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
21
21
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
22
  /** The channels a runtime source can name, which a verified pairing's provider is one of. */
23
23
  const CHANNEL_PROVIDERS = new Set(["telegram", "slack", "whatsapp"]);
@@ -180,7 +180,9 @@ chats) {
180
180
  const invalid = () => new ActionRejected({
181
181
  message: "The exact attributed message or reply target is invalid or too long. Nothing was truncated.",
182
182
  });
183
- if (!provider.isTargetId(target.external_id, target.kind) ||
183
+ if (
184
+ // A shared thread's reply goes to the people its provider names when it is sent.
185
+ (inbox?.shared !== true && !provider.isTargetId(target.external_id, target.kind)) ||
184
186
  (replyTo !== null && !provider.isReplyId(replyTo)) ||
185
187
  !input.idempotencyKey ||
186
188
  input.idempotencyKey.length > 512) {
@@ -369,10 +371,14 @@ chats) {
369
371
  query: chatPeopleQuery(chat),
370
372
  })
371
373
  .pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat's person could not be read.", cause })))).items;
372
- // A thread's chat on a mailbox has no one person to answer: staff answer it in the mail.
373
- const mailThread = chatKind(ontology.manifest.chat, String(record.provider)) === "email" &&
374
- !(typeof record.recipient === "string" && record.recipient !== "");
375
- if (people.length !== 1 || mailThread) {
374
+ const threadId = typeof record.thread_id === "string" && record.thread_id !== "" ? record.thread_id : null;
375
+ // A thread's chat on a mailbox has no one person: a reply goes to everyone in the thread,
376
+ // as the agent's does, whoever of them are the chat's members.
377
+ const shared = !(typeof record.recipient === "string" && record.recipient !== "") &&
378
+ threadId !== null &&
379
+ channelProvider(ontology.manifest.chat, String(record.provider))?.threadRecipients !==
380
+ undefined;
381
+ if (!shared && people.length !== 1) {
376
382
  return yield* new ActionRejected({
377
383
  message: "The chat has no person to answer. Nothing was sent.",
378
384
  });
@@ -388,12 +394,11 @@ chats) {
388
394
  provider: String(record.provider),
389
395
  external_id: recipient,
390
396
  kind: "private",
391
- participantIds: [String(people[0].id)],
397
+ participantIds: shared ? [] : [String(people[0].id)],
392
398
  },
393
399
  chatId,
394
- threadId: typeof record.thread_id === "string" && record.thread_id !== ""
395
- ? record.thread_id
396
- : null,
400
+ threadId,
401
+ shared,
397
402
  };
398
403
  });
399
404
  /**
@@ -456,6 +461,32 @@ chats) {
456
461
  }
457
462
  : undefined;
458
463
  });
464
+ /**
465
+ * The members among the addresses a reply goes to, by the accounts of the channel's kind paired
466
+ * with them, live and active: who reads the reply in a thread's chat, as the agent's channel
467
+ * finds who reads its own reply there.
468
+ */
469
+ const readersOf = (channel, addresses) => Effect.gen(function* () {
470
+ const agents = context.backend.agents;
471
+ const kind = chatKind(ontology.manifest.chat, channel);
472
+ if (agents === undefined || kind === undefined) {
473
+ return [];
474
+ }
475
+ const readers = [];
476
+ for (const address of new Set(addresses)) {
477
+ const identity = yield* agents.findIdentity({
478
+ provider: channelIdentityProvider(kind, channel),
479
+ externalId: address,
480
+ });
481
+ if (identity !== undefined &&
482
+ identity.revokedAt === null &&
483
+ !readers.includes(identity.userId) &&
484
+ (yield* agents.member(identity.userId)) !== undefined) {
485
+ readers.push(identity.userId);
486
+ }
487
+ }
488
+ return readers;
489
+ });
459
490
  const report = (phase, cause) => Effect.logWarning("ontology.chat.delivery_diagnostic").pipe(Effect.annotateLogs({
460
491
  phase,
461
492
  requestId: context.requestId,
@@ -574,9 +605,12 @@ chats) {
574
605
  refusal: "files_unsupported",
575
606
  });
576
607
  }
577
- // A message read when it is sent, a template, may read differently by the time its key
578
- // is replayed, or not at all: a replay recovers the first attempt's receipt before it.
579
- if ((("template" in input && input.template !== undefined) || named.length > 0) &&
608
+ // A message read when it is sent, a template, its files, or the people of a shared
609
+ // thread's reply, may read differently by the time its key is replayed, or not at all: a
610
+ // replay recovers the first attempt's receipt before it.
611
+ if ((("template" in input && input.template !== undefined) ||
612
+ named.length > 0 ||
613
+ inbox?.shared === true) &&
580
614
  archive.find !== undefined) {
581
615
  const found = yield* archive
582
616
  .find({ delivery: { scope, key, fingerprint }, identityToken: context.identityToken })
@@ -621,6 +655,24 @@ chats) {
621
655
  });
622
656
  }
623
657
  const { preview, payload, summary } = yield* compose;
658
+ const transport = connections({
659
+ identityToken: context.identityToken,
660
+ audit: {
661
+ action: asAgent ? "agent_chat.send" : "agent_chat.post_message",
662
+ principalId: context.principal.id,
663
+ requestId: context.requestId,
664
+ },
665
+ });
666
+ // A shared thread's reply goes to all of its latest message's people and is read by the
667
+ // members among them, as the agent's own reply there is.
668
+ const audience = inbox?.shared === true && inbox.threadId !== null && provider.threadRecipients
669
+ ? yield* provider
670
+ .threadRecipients({ transport, connection, threadId: inbox.threadId })
671
+ .pipe(Effect.tapError((error) => error.cause === undefined ? Effect.void : report("recipients", error.cause)))
672
+ : undefined;
673
+ const participantIds = audience === undefined
674
+ ? target.participantIds
675
+ : yield* readersOf(target.provider, [...audience.to, ...audience.cc]);
624
676
  // The message as sent without formatting: the text, then any attribution.
625
677
  const plainText = preview.attribution === ""
626
678
  ? preview.text
@@ -647,7 +699,7 @@ chats) {
647
699
  chatId: place?.chatId ?? target.external_id,
648
700
  chatType: target.kind,
649
701
  threadId: place?.threadId ?? null,
650
- participantIds: target.participantIds,
702
+ participantIds,
651
703
  senderId: staff ? requester.id : "agent",
652
704
  senderName: staff ? requester.name : "agent",
653
705
  senderIsBot: !staff,
@@ -700,7 +752,7 @@ chats) {
700
752
  });
701
753
  }
702
754
  const outcome = yield* provider.send({
703
- destination: target,
755
+ destination: { ...target, participantIds },
704
756
  connection,
705
757
  text: preview.text,
706
758
  separator: preview.attribution === "" ? "" : separator,
@@ -715,18 +767,14 @@ chats) {
715
767
  ...(buttons === undefined ? {} : { buttons }),
716
768
  ...(sendFiles.length === 0 ? {} : { files: sendFiles }),
717
769
  ...(inbox === undefined ? {} : { threadId: inbox.threadId, chatId: inbox.chatId }),
770
+ ...(audience === undefined
771
+ ? {}
772
+ : { recipients: { to: audience.to, cc: audience.cc }, thread: audience.thread }),
718
773
  // Files go in the person's chat, which their account is not on Slack.
719
774
  ...(inbox === undefined && sendFiles.length > 0 && place !== undefined
720
775
  ? { chatId: place.chatId }
721
776
  : {}),
722
- transport: connections({
723
- identityToken: context.identityToken,
724
- audit: {
725
- action: asAgent ? "agent_chat.send" : "agent_chat.post_message",
726
- principalId: context.principal.id,
727
- requestId: context.requestId,
728
- },
729
- }),
777
+ transport,
730
778
  });
731
779
  if (outcome.cause !== undefined) {
732
780
  yield* report("provider", outcome.cause);
@@ -1,5 +1,22 @@
1
1
  import { Effect } from "effect";
2
- import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
2
+ import { type EmailRecipients } from "../../../email.js";
3
+ import type { ConnectionTransport } from "../../../connection.js";
4
+ import { ActionRejected } from "../../../errors.js";
5
+ import { type ChatProvider, type ChatSend, type ProviderOutcome, type ThreadHeaders } from "./provider.js";
6
+ /**
7
+ * Whom a reply to all in a Gmail thread goes to, as the email channel's agent replies to all: the
8
+ * thread's latest mail, a draft never, answered to its sender and copying the other people of its
9
+ * `To` and `Cc`, without the mailbox's own address, which its profile names. A reply under the
10
+ * mailbox's own latest message goes to whom that message went to. It reads the thread and the
11
+ * profile and sends nothing: a failure is refused before anything is reserved or sent.
12
+ */
13
+ export declare function emailThreadRecipients(input: {
14
+ readonly transport: ConnectionTransport["Service"];
15
+ readonly connection: string;
16
+ readonly threadId: string;
17
+ }): Effect.Effect<EmailRecipients & {
18
+ readonly thread: ThreadHeaders;
19
+ }, ActionRejected>;
3
20
  /**
4
21
  * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
5
22
  * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
@@ -8,12 +25,13 @@ import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provid
8
25
  * with the thread id, never retried. A reply sends no attribution and names no sender, so it
9
26
  * leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
10
27
  * `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
11
- * keys. Files go after the text in the same message, uploaded in chunks when one request cannot
12
- * carry it (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
28
+ * keys; a post into the inbox's chat carries `post-<its operation>` instead. Files go after the
29
+ * text in the same message, uploaded in chunks when one request cannot carry it
30
+ * (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
13
31
  */
14
32
  export declare function sendEmail(input: ChatSend): Effect.Effect<ProviderOutcome>;
15
33
  /**
16
- * Email through a connected mailbox. It only sends replies the agent held for review, in the
17
- * person's thread: an exact chat post never goes to an inbox.
34
+ * Email through a connected mailbox. It sends replies the agent held for review and staff's replies
35
+ * from the inbox, in the chat's thread: no chat post or tool reaches a mailbox otherwise.
18
36
  */
19
37
  export declare const emailProvider: ChatProvider;
@@ -1,6 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
3
- import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, GmailMaybeSent, renderEmailHtml, sendGmailMessage, } from "../../../email.js";
3
+ import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, } from "../../../email.js";
4
+ import { ActionRejected } from "../../../errors.js";
4
5
  import { EMAIL_PATTERN } from "../../../property.js";
5
6
  import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportFailure, } from "./provider.js";
6
7
  /** A Gmail id, of a thread or a message. */
@@ -26,6 +27,67 @@ function headersOf(message) {
26
27
  }
27
28
  return found;
28
29
  }
30
+ /** A message's `labelIds`, which Gmail lists on each message of a thread. */
31
+ function labelsOf(message) {
32
+ const labels = record(message).labelIds;
33
+ return Array.isArray(labels) ? labels : [];
34
+ }
35
+ /**
36
+ * One GET on the mailbox's Gmail API, as JSON. It fails with the connection's own failure, or a
37
+ * {@link GmailError} that keeps Gmail's explanation of a refusal, for operators' diagnostics.
38
+ */
39
+ function readGmail(transport, connection, operation, path) {
40
+ return transport
41
+ .request({ connection, api: "gmail", method: "GET", path, headers: [], body: new Uint8Array() })
42
+ .pipe(Effect.flatMap((reply) => reply.status >= 300
43
+ ? Effect.fail(new GmailError(operation, reply.status, gmailExplanation(reply)))
44
+ : Effect.succeed(parse(reply.body) ?? {})));
45
+ }
46
+ /**
47
+ * Whom a reply to all in a Gmail thread goes to, as the email channel's agent replies to all: the
48
+ * thread's latest mail, a draft never, answered to its sender and copying the other people of its
49
+ * `To` and `Cc`, without the mailbox's own address, which its profile names. A reply under the
50
+ * mailbox's own latest message goes to whom that message went to. It reads the thread and the
51
+ * profile and sends nothing: a failure is refused before anything is reserved or sent.
52
+ */
53
+ export function emailThreadRecipients(input) {
54
+ return Effect.gen(function* () {
55
+ // The rejection the caller sees is sanitized; its cause keeps the original failure.
56
+ const unread = (cause) => new ActionRejected({
57
+ message: "The mail thread could not be read, so whom to answer is unknown. Nothing was sent.",
58
+ cause,
59
+ });
60
+ if (!GMAIL_ID.test(input.threadId)) {
61
+ return yield* unread(new Error("The chat names no Gmail thread."));
62
+ }
63
+ const read = (operation, path) => readGmail(input.transport, input.connection, operation, path).pipe(Effect.mapError(unread));
64
+ const profile = yield* read("profile", "/users/me/profile");
65
+ const thread = yield* read("threads.get", `/users/me/threads/${input.threadId}?format=metadata&fields=messages(labelIds,payload/headers)`);
66
+ const own = profile.emailAddress;
67
+ const messages = thread.messages;
68
+ if (typeof own !== "string" || !Array.isArray(messages)) {
69
+ return yield* unread(new Error("Gmail answered without the mailbox's address or messages."));
70
+ }
71
+ const received = messages.filter((message) => !labelsOf(message).includes("DRAFT"));
72
+ const headers = headersOf(received.at(-1));
73
+ const recipients = replyAllRecipients({ from: headers.get("from"), to: headers.get("to"), cc: headers.get("cc") }, [own]);
74
+ return recipients === undefined
75
+ ? yield* new ActionRejected({
76
+ message: "The thread's latest mail names no one to answer. Nothing was sent.",
77
+ })
78
+ : { ...recipients, thread: threadHeaders(received) };
79
+ });
80
+ }
81
+ /** The thread's subject, from its first message, and the ids of the last one a reply answers. */
82
+ function threadHeaders(received) {
83
+ const first = headersOf(received[0]);
84
+ const last = headersOf(received.at(-1));
85
+ return {
86
+ subject: first.get("subject") ?? null,
87
+ inReplyTo: last.get("message-id") ?? null,
88
+ references: last.get("references") ?? null,
89
+ };
90
+ }
29
91
  /**
30
92
  * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
31
93
  * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
@@ -34,8 +96,9 @@ function headersOf(message) {
34
96
  * with the thread id, never retried. A reply sends no attribution and names no sender, so it
35
97
  * leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
36
98
  * `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
37
- * keys. Files go after the text in the same message, uploaded in chunks when one request cannot
38
- * carry it (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
99
+ * keys; a post into the inbox's chat carries `post-<its operation>` instead. Files go after the
100
+ * text in the same message, uploaded in chunks when one request cannot carry it
101
+ * (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
39
102
  */
40
103
  export function sendEmail(input) {
41
104
  return Effect.gen(function* () {
@@ -50,40 +113,48 @@ export function sendEmail(input) {
50
113
  if (threadId === null || !GMAIL_ID.test(threadId)) {
51
114
  return failed(new Error("An email reply needs the Gmail thread it answers."));
52
115
  }
53
- const thread = yield* input.transport
54
- .request({
55
- connection: input.connection,
56
- api: "gmail",
57
- method: "GET",
58
- // Every header of every message, without bodies. The connection proxy refuses a
59
- // repeated query parameter, so the headers are not named one `metadataHeaders` each.
60
- path: `/users/me/threads/${threadId}?format=metadata&fields=messages(payload/headers)`,
61
- headers: [],
62
- body: new Uint8Array(),
63
- })
64
- .pipe(Effect.exit);
116
+ // The headers read with the reply's people, or else the thread as it is now.
117
+ const thread = input.thread !== undefined
118
+ ? undefined
119
+ : yield* input.transport
120
+ .request({
121
+ connection: input.connection,
122
+ api: "gmail",
123
+ method: "GET",
124
+ // Every header of every message, without bodies. The connection proxy refuses a
125
+ // repeated query parameter, so the headers are not named one `metadataHeaders` each.
126
+ path: `/users/me/threads/${threadId}?format=metadata&fields=messages(labelIds,payload/headers)`,
127
+ headers: [],
128
+ body: new Uint8Array(),
129
+ })
130
+ .pipe(Effect.exit);
65
131
  // Reading the thread sends nothing: any failure here is definite.
66
- if (thread._tag === "Failure" || thread.value.status >= 300) {
132
+ if (thread !== undefined && (thread._tag === "Failure" || thread.value.status >= 300)) {
67
133
  return failed(thread._tag === "Failure"
68
134
  ? thread.cause
69
135
  : new Error(`Gmail answered the thread read with status ${thread.value.status}.`));
70
136
  }
71
- const messages = record(parse(thread.value.body)).messages;
72
- const list = Array.isArray(messages) ? messages : [];
73
- const first = headersOf(list[0]);
74
- const last = headersOf(list.at(-1));
137
+ // A draft in the thread is no mail anyone received: the reply goes under the last that is.
138
+ const answered = input.thread ??
139
+ threadHeaders((() => {
140
+ const messages = thread?._tag === "Success" ? record(parse(thread.value.body)).messages : [];
141
+ return (Array.isArray(messages) ? messages : []).filter((message) => !labelsOf(message).includes("DRAFT"));
142
+ })());
75
143
  // The agent's reply, as the email channel sends its own: marked as a program's, so no
76
- // autoresponder answers it, and named by its review, so the channel knows it for the agent's.
77
- const key = `review-${input.destination.id}`;
144
+ // autoresponder answers it, and named by its review, or by the post's own operation, so the
145
+ // channel knows it for the workspace's and never records it again as staff's mail.
146
+ const key = input.operationId !== undefined && input.operationId !== input.destination.id
147
+ ? `post-${input.operationId}`
148
+ : `review-${input.destination.id}`;
78
149
  const to = input.recipients?.to ?? [input.destination.external_id];
79
150
  const cc = input.recipients?.cc ?? [];
80
151
  const files = input.files ?? [];
81
152
  const raw = emailReplyMessage({
82
153
  to,
83
154
  ...(cc.length === 0 ? {} : { cc }),
84
- subject: first.get("subject") ?? null,
85
- inReplyTo: last.get("message-id") ?? null,
86
- references: last.get("references") ?? null,
155
+ subject: answered.subject,
156
+ inReplyTo: answered.inReplyTo,
157
+ references: answered.references,
87
158
  text: input.plainText,
88
159
  html: input.finalText,
89
160
  autoSubmitted: true,
@@ -170,8 +241,8 @@ export function sendEmail(input) {
170
241
  });
171
242
  }
172
243
  /**
173
- * Email through a connected mailbox. It only sends replies the agent held for review, in the
174
- * person's thread: an exact chat post never goes to an inbox.
244
+ * Email through a connected mailbox. It sends replies the agent held for review and staff's replies
245
+ * from the inbox, in the chat's thread: no chat post or tool reaches a mailbox otherwise.
175
246
  */
176
247
  export const emailProvider = {
177
248
  provider: "email",
@@ -187,4 +258,5 @@ export const emailProvider = {
187
258
  // The files go in the reply's one message, under the bound every email sender keeps.
188
259
  files: { count: AGENT_DRAFT_FILES_LIMIT, bytes: EMAIL_FILES_BYTES },
189
260
  send: sendEmail,
261
+ threadRecipients: emailThreadRecipients,
190
262
  };
@@ -6,6 +6,12 @@ import { ConnectionError, type ConnectionReply, type ConnectionTransport } from
6
6
  import type { ActionRejected } from "../../../errors.js";
7
7
  import type { Destination } from "../resolve.js";
8
8
  import type { ResolvedTemplate, StoredFileLink, StoredFileReference, TemplateRequest } from "./whatsapp-template.js";
9
+ /** What a reply in a mail thread answers: the thread's subject and its latest mail's ids. */
10
+ export interface ThreadHeaders {
11
+ readonly subject: string | null;
12
+ readonly inReplyTo: string | null;
13
+ readonly references: string | null;
14
+ }
9
15
  /** One delivery attempt's result. A `failed` attempt definitely sent nothing; `uncertain` may have. */
10
16
  export interface ProviderOutcome {
11
17
  /** The text and its format as the provider received them, for the delivery's history. */
@@ -115,6 +121,11 @@ export interface ChatSend {
115
121
  readonly to: ReadonlyArray<string>;
116
122
  readonly cc: ReadonlyArray<string>;
117
123
  };
124
+ /**
125
+ * The thread's headers a reply to mail answers, read with its `recipients` from one snapshot of
126
+ * the thread; without them the provider reads the thread itself. Others ignore them.
127
+ */
128
+ readonly thread?: ThreadHeaders;
118
129
  }
119
130
  /**
120
131
  * A channel the platform posts exact chat messages to. Each provider names its own ids, renders
@@ -128,7 +139,8 @@ export interface ChatProvider {
128
139
  readonly limit: number;
129
140
  /**
130
141
  * Whether exact chat posts and the chat tools reach the provider's chats. `false` for one that
131
- * only sends replies the agent held for review, such as email. Omitted, it is `true`.
142
+ * only sends replies the agent held for review and staff's replies in the inbox, such as email.
143
+ * Omitted, it is `true`.
132
144
  */
133
145
  readonly posts?: boolean;
134
146
  /**
@@ -173,6 +185,21 @@ export interface ChatProvider {
173
185
  }>) => ChatFilesRefusal | undefined;
174
186
  /** One attempt: `sent` only when the provider's answer proves it. */
175
187
  readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
188
+ /**
189
+ * Whom a reply in a thread several people share goes to, read from the provider before anything
190
+ * is reserved or sent, for a provider whose chat can be such a thread, such as a mailbox's: the
191
+ * people of the thread's latest message, as a reply to all.
192
+ */
193
+ readonly threadRecipients?: (input: {
194
+ readonly transport: ConnectionTransport["Service"];
195
+ readonly connection: string;
196
+ readonly threadId: string;
197
+ }) => Effect.Effect<{
198
+ readonly to: ReadonlyArray<string>;
199
+ readonly cc: ReadonlyArray<string>;
200
+ /** The headers of the same snapshot of the thread, which the reply answers. */
201
+ readonly thread: ThreadHeaders;
202
+ }, ActionRejected>;
176
203
  /**
177
204
  * The provider's approved template, read and rendered before anything is sent, for a provider
178
205
  * that takes templates, such as WhatsApp; others take text alone.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.166.1",
3
+ "version": "0.167.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",