@segmentstream/ontology 0.153.1 → 0.155.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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.155.0
4
+
5
+ An email thread can be one chat. `"chats": "thread"` on an email channel makes each Gmail thread one chat and one session of the agent, whoever writes in it; `"sender"`, the default, keeps each person's own chat in a thread, as before. Admission stays the sender's: each turn acts as the person who wrote. Each message, and the reply to it, is read by the members it went to, its sender and the members among its `To` and `Cc`, so a person dropped from `Cc` reads none of the thread's later mail. Each admitted person joins the thread's chat in the inbox, which is named after the thread's subject; with `"record": "all"`, any mail the channel records in a thread, even mail the agent does not take from or to members, brings its chat into the inbox where `inbox.channels` lists the channel, and makes no one its member. A reply held for review in a thread's chat is read, once approved, by the same members as a reply the agent sends itself. A new thread chat reads its history from Gmail once, the thread's last 20 messages before it, as imported history. Chats a thread had per person stay, and replies waiting or held there are still sent. A thread's chat replies to all; `"reply": "sender"` is refused with it. Staff answer a thread's chat in Gmail: the inbox's `postMessage` and `send` refuse it. While staff hold a thread's chat, taken over, the agent answers no one in the thread, whatever their role.
6
+
7
+ `POST /api/ontology/agent/chats/seen` takes `shared: true` for a private chat several people share: the member joins its members and none leaves; a member whose roles the inbox does not take joins none, and is answered whether staff hold the chat where it is recorded already. `POST /api/ontology/agent/chats/messages` takes `imported: true` for history a channel read from its provider, never for a send. `POST /api/ontology/agent/reviews` takes `participants`, at most 50 user ids of the members who read a reply in a private chat several people share; `agent_review` keeps them in its new `participants` property, a redraft keeps them, and the approved reply is recorded as read by its `person` and them. An agent on this release whose ontology SDK predates `participants` holds the reply for its person alone.
8
+
9
+ ## 0.154.0
10
+
11
+ An email channel can reply to all: with `"reply": "all"` in `agent/segmentstream.json`, a reply goes to the person who wrote, in `To`, and copies the other addresses of the `To` and `Cc` of the mail it answers, without the mailbox's own address; files `segmentstream__attachments_send` sends go to the same people. `"sender"`, the default, replies to the person alone, as before. Each state of a reply names whom it goes to in its channel state, so a reply a later wake sends goes to the same people.
12
+
13
+ A held reply to mail keeps whom it goes to: `agent_review` gains `to` and `cc`, and `agent_review.approve` takes `to` and `cc`, lists of plain addresses that replace them, refused on a reply that is not mail. The review records whom it was sent to, and approving again to other people is refused. A reply held before goes to its `recipient` alone. `POST /api/ontology/agent/reviews` takes `to` and `cc` for a reply to mail; an agent on this release whose ontology SDK predates them holds the reply for its person alone. `emailReplyMessage` of `@segmentstream/ontology/email` takes several addresses in `to` and `cc`.
14
+
15
+ In the app, `useInboxChat`'s held replies carry `to` and `cc`, and `approve(reply, text?, { to, cc })` replaces them.
16
+
3
17
  ## 0.153.1
4
18
 
5
19
  An edit that replaces a message's files discards the chat's stored attachments it no longer holds, as a deleted message's are, so a channel that keeps files no longer keeps a replaced file until the chats' retention.
@@ -47,12 +47,25 @@ export declare const AGENT_REVIEW_TEXT_LIMIT = 20000;
47
47
  export declare const AGENT_REVIEW_REASON_LIMIT = 2000;
48
48
  /** The longest note a member gives the agent for redrafting a reply. */
49
49
  export declare const AGENT_REVIEW_NOTE_LIMIT = 2000;
50
+ /** The most members a review names as the readers of its reply, as many as a reply to mail goes to. */
51
+ export declare const AGENT_REVIEW_PARTICIPANTS_LIMIT = 50;
52
+ /** Addresses as a review keeps them in `to` and `cc`: separated by commas. */
53
+ export declare function reviewAddresses(addresses: ReadonlyArray<string>): string;
54
+ /** The addresses a review keeps in `to` or `cc`; none for an empty value. */
55
+ export declare function addressesOfReview(value: unknown): ReadonlyArray<string>;
56
+ /** Members as a review keeps them in `participants`: their user ids, once each, by commas. */
57
+ export declare function reviewParticipants(ids: ReadonlyArray<string>): string;
58
+ /** The members a review keeps in `participants`, once each; anything that is no user id is left out. */
59
+ export declare function participantsOfReview(value: unknown): ReadonlyArray<string>;
50
60
  export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
51
61
  readonly key: import("./property.js").Property<string, false, true>;
52
62
  readonly provider: import("./property.js").Property<string, false, false>;
53
63
  readonly channel: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
54
64
  readonly chatId: import("./property.js").Property<string, false, false>;
55
65
  readonly recipient: import("./property.js").Property<string, false, false>;
66
+ readonly to: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
67
+ readonly cc: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
68
+ readonly participants: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
56
69
  readonly chatKind: import("./property.js").Property<"private" | "group", false, false>;
57
70
  readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
58
71
  readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
@@ -78,7 +91,11 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
78
91
  readonly approve: import("./action.js").Action<Schema.Struct<{
79
92
  readonly review: Schema.Codec<string, string, never, never>;
80
93
  readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
94
+ readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
95
+ readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
81
96
  }>, {
97
+ to?: readonly string[] | undefined;
98
+ cc?: readonly string[] | undefined;
82
99
  review: string;
83
100
  status: "sent" | "uncertain" | "failed";
84
101
  message_id: string | null;
@@ -110,6 +127,9 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
110
127
  readonly channel: string | null;
111
128
  readonly chatId: string;
112
129
  readonly recipient: string;
130
+ readonly to: string | null;
131
+ readonly cc: string | null;
132
+ readonly participants: string | null;
113
133
  readonly chatKind: "private" | "group";
114
134
  readonly threadId: string | null;
115
135
  readonly replyTo: string | null;
@@ -1,9 +1,11 @@
1
1
  import { Effect, Option, Schema } from "effect";
2
2
  import { action } from "./action.js";
3
3
  import { ChatDelivery } from "./chat.js";
4
+ import { EMAIL_RECIPIENTS_LIMIT } from "./email.js";
4
5
  import { entity } from "./entity.js";
5
6
  import { ActionRejected } from "./errors.js";
6
- import { p } from "./property.js";
7
+ import { EMAIL_PATTERN, p } from "./property.js";
8
+ import { isUuid } from "./query.js";
7
9
  import { rel } from "./relationship.js";
8
10
  /**
9
11
  * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
@@ -45,6 +47,39 @@ export const AGENT_REVIEW_TEXT_LIMIT = 20_000;
45
47
  export const AGENT_REVIEW_REASON_LIMIT = 2_000;
46
48
  /** The longest note a member gives the agent for redrafting a reply. */
47
49
  export const AGENT_REVIEW_NOTE_LIMIT = 2_000;
50
+ /** The longest list of addresses a review keeps in `to` or `cc`: as many as a reply goes to. */
51
+ const AGENT_REVIEW_RECIPIENTS_LENGTH = EMAIL_RECIPIENTS_LIMIT * 256;
52
+ /** The most members a review names as the readers of its reply, as many as a reply to mail goes to. */
53
+ export const AGENT_REVIEW_PARTICIPANTS_LIMIT = EMAIL_RECIPIENTS_LIMIT;
54
+ /** The longest list of user ids a review keeps in `participants`. */
55
+ const AGENT_REVIEW_PARTICIPANTS_LENGTH = AGENT_REVIEW_PARTICIPANTS_LIMIT * 38;
56
+ /** An address a member names for a reply to mail. */
57
+ const EmailAddress = Schema.String.check(Schema.isMaxLength(254), Schema.isPattern(EMAIL_PATTERN));
58
+ /** Addresses as a review keeps them in `to` and `cc`: separated by commas. */
59
+ export function reviewAddresses(addresses) {
60
+ return addresses.join(", ");
61
+ }
62
+ /** The addresses a review keeps in `to` or `cc`; none for an empty value. */
63
+ export function addressesOfReview(value) {
64
+ return typeof value !== "string"
65
+ ? []
66
+ : value
67
+ .split(",")
68
+ .map((address) => address.trim())
69
+ .filter((address) => address !== "");
70
+ }
71
+ /** Members as a review keeps them in `participants`: their user ids, once each, by commas. */
72
+ export function reviewParticipants(ids) {
73
+ return [...new Set(ids.map((id) => id.toLowerCase()))].join(", ");
74
+ }
75
+ /** The members a review keeps in `participants`, once each; anything that is no user id is left out. */
76
+ export function participantsOfReview(value) {
77
+ return [
78
+ ...new Set(addressesOfReview(value)
79
+ .filter(isUuid)
80
+ .map((id) => id.toLowerCase())),
81
+ ];
82
+ }
48
83
  export const AgentReview = entity("agent_review", {
49
84
  id: "ent_agent_review",
50
85
  label: "Agent reply review",
@@ -77,6 +112,29 @@ export const AgentReview = entity("agent_review", {
77
112
  managed: true,
78
113
  description: "Whom the provider sends the reply to: the chat's id, or the person's number on WhatsApp.",
79
114
  }),
115
+ to: p.text({
116
+ optional: true,
117
+ managed: true,
118
+ maxLength: AGENT_REVIEW_RECIPIENTS_LENGTH,
119
+ description: "A reply to mail: the addresses it goes to, in To, separated by commas; once approved, " +
120
+ "those it was sent to. Empty on another channel, and on a reply held before replies " +
121
+ "named them, which goes to recipient.",
122
+ }),
123
+ cc: p.text({
124
+ optional: true,
125
+ managed: true,
126
+ maxLength: AGENT_REVIEW_RECIPIENTS_LENGTH,
127
+ description: "A reply to mail: the addresses it copies, in Cc, separated by commas, as the thread's " +
128
+ "other people; once approved, those it was sent to. Empty when it copies no one.",
129
+ }),
130
+ participants: p.text({
131
+ optional: true,
132
+ managed: true,
133
+ maxLength: AGENT_REVIEW_PARTICIPANTS_LENGTH,
134
+ description: "A reply in a chat several people share, such as an email thread: the members who " +
135
+ "read it in the chat's history, its person among them, by user id, separated by " +
136
+ "commas, as they read the message it answers. Empty when only its person reads it.",
137
+ }),
80
138
  chatKind: p.select([
81
139
  { value: "private", description: "The person's own chat with the agent." },
82
140
  { value: "group", description: "A group chat." },
@@ -201,8 +259,10 @@ export const AgentReview = entity("agent_review", {
201
259
  }).actions((self) => ({
202
260
  approve: action({
203
261
  description: "Send a reply the agent held for review to the person, as written or with your edit in " +
204
- "text (Markdown), as the agent and without sender attribution. Confirm the final text " +
205
- "with the member first. It is sent at most once: approving again with the same text " +
262
+ "text (Markdown), as the agent and without sender attribution. A reply to mail goes to " +
263
+ "the review's to and cc, the thread's people; to and cc, each a list of addresses, " +
264
+ "replace them. Confirm the final text and, for mail, its recipients with the member " +
265
+ "first. It is sent at most once: approving again with the same text and recipients " +
206
266
  "returns the delivery, and an approved or rejected review is refused otherwise. status " +
207
267
  "failed means the provider refused it and nothing was sent.",
208
268
  hints: { destructive: false, irreversible: true, idempotent: true },
@@ -212,6 +272,18 @@ export const AgentReview = entity("agent_review", {
212
272
  maxLength: AGENT_REVIEW_TEXT_LIMIT,
213
273
  description: "The member's edit of the reply; omit it to send the draft.",
214
274
  })),
275
+ to: Schema.optionalKey(Schema.Array(EmailAddress)
276
+ .check(Schema.isMinLength(1), Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT))
277
+ .annotate({
278
+ description: "A reply to mail: the addresses it goes to, in place of the review's to; omit it " +
279
+ "to keep them.",
280
+ })),
281
+ cc: Schema.optionalKey(Schema.Array(EmailAddress)
282
+ .check(Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT))
283
+ .annotate({
284
+ description: "A reply to mail: the addresses it copies, in place of the review's cc; [] copies " +
285
+ "no one, and omitting it keeps them.",
286
+ })),
215
287
  }),
216
288
  connections: [],
217
289
  prepare: ({ input }) => Effect.gen(function* () {
@@ -225,24 +297,34 @@ export const AgentReview = entity("agent_review", {
225
297
  return yield* send({
226
298
  review: String(input.review),
227
299
  ...(input.text === undefined ? {} : { text: input.text }),
300
+ ...(input.to === undefined ? {} : { to: input.to }),
301
+ ...(input.cc === undefined ? {} : { cc: input.cc }),
228
302
  });
229
303
  }),
230
304
  handler: ({ input, prepared, principal }) => Effect.gen(function* () {
231
305
  const review = yield* self.get(input.review, { forUpdate: true });
306
+ const recipients = prepared.recipients;
232
307
  // The delivery happened, or definitely did not: the record says what the provider did,
233
- // even when another member rejected the review meanwhile.
308
+ // and whom a reply to mail went to, even when another member rejected the review meanwhile.
234
309
  yield* self.update(review, {
235
310
  status: prepared.status,
236
311
  text: prepared.text,
237
312
  messageId: prepared.messageId,
238
313
  decidedAt: review.decidedAt ?? new Date().toISOString(),
239
314
  decidedBy: review.decidedById ?? principal.id,
315
+ ...(recipients === undefined
316
+ ? {}
317
+ : {
318
+ to: reviewAddresses(recipients.to),
319
+ cc: recipients.cc.length === 0 ? null : reviewAddresses(recipients.cc),
320
+ }),
240
321
  });
241
322
  return {
242
323
  review: review.id,
243
324
  status: prepared.status,
244
325
  message_id: prepared.messageId,
245
326
  duplicate: prepared.duplicate,
327
+ ...(recipients === undefined ? {} : { to: recipients.to, cc: recipients.cc }),
246
328
  };
247
329
  }),
248
330
  }),
package/dist/chat.d.ts CHANGED
@@ -206,6 +206,10 @@ export interface ReviewSendInput {
206
206
  /** The `agent_review` record's id. */
207
207
  readonly review: string;
208
208
  readonly text?: string;
209
+ /** A reply to mail: the addresses it goes to, in place of the review's own. */
210
+ readonly to?: ReadonlyArray<string>;
211
+ /** A reply to mail: the addresses it copies, in place of the review's own. */
212
+ readonly cc?: ReadonlyArray<string>;
209
213
  }
210
214
  /** What sending an approved reply did; `duplicate` when an earlier approval already sent it. */
211
215
  export interface ReviewSendResult {
@@ -214,6 +218,11 @@ export interface ReviewSendResult {
214
218
  readonly text: string;
215
219
  readonly messageId: string | null;
216
220
  readonly duplicate: boolean;
221
+ /** A reply to mail: whom it was sent to, or attempted; absent on another channel. */
222
+ readonly recipients?: {
223
+ readonly to: ReadonlyArray<string>;
224
+ readonly cc: ReadonlyArray<string>;
225
+ };
217
226
  }
218
227
  /** A member's request that the agent redraft a reply it held for review. */
219
228
  export interface ReviewReviseInput {
package/dist/email.d.ts CHANGED
@@ -1,5 +1,23 @@
1
1
  /** The most characters of a reply the mail channel sends in one message. */
2
2
  export declare const EMAIL_MESSAGE_LIMIT = 100000;
3
+ /** The most addresses one reply goes to, in `To` and `Cc` together. */
4
+ export declare const EMAIL_RECIPIENTS_LIMIT = 50;
5
+ /** Whether `value` is a plain address a reply may go to. */
6
+ export declare function isEmailAddress(value: string): boolean;
7
+ /** Whom a reply goes to: the people in `To`, and those it copies in `Cc`. */
8
+ export interface EmailRecipients {
9
+ readonly to: ReadonlyArray<string>;
10
+ readonly cc: ReadonlyArray<string>;
11
+ }
12
+ /**
13
+ * A reply's recipients as it sends them: each address trimmed and in lower case, once, an address
14
+ * in `To` left out of `Cc`. Throws when `to` is empty, an address is not a plain one, or there are
15
+ * more than {@link EMAIL_RECIPIENTS_LIMIT} together.
16
+ */
17
+ export declare function emailRecipients(input: {
18
+ readonly to: string | ReadonlyArray<string>;
19
+ readonly cc?: ReadonlyArray<string>;
20
+ }): EmailRecipients;
3
21
  /**
4
22
  * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
5
23
  * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
@@ -20,8 +38,10 @@ export interface EmailAttachment {
20
38
  }
21
39
  /** What a reply in an email thread needs from the message it answers. */
22
40
  export interface EmailReply {
23
- /** The address the reply goes to: a lower-case address without a name. */
24
- readonly to: string;
41
+ /** The addresses the reply goes to, in `To`: plain addresses without a name. */
42
+ readonly to: string | ReadonlyArray<string>;
43
+ /** The addresses the reply copies, in `Cc`; none when absent. */
44
+ readonly cc?: ReadonlyArray<string>;
25
45
  /** The thread's subject; the reply carries it with `Re:`. */
26
46
  readonly subject: string | null;
27
47
  /** The `Message-ID` of the message replied to, which threads the reply under it. */
package/dist/email.js CHANGED
@@ -1,6 +1,62 @@
1
1
  import { Marked } from "marked";
2
2
  /** The most characters of a reply the mail channel sends in one message. */
3
3
  export const EMAIL_MESSAGE_LIMIT = 100_000;
4
+ /** The most addresses one reply goes to, in `To` and `Cc` together. */
5
+ export const EMAIL_RECIPIENTS_LIMIT = 50;
6
+ /** The longest address a reply goes to, as SMTP bounds a path. */
7
+ const EMAIL_ADDRESS_LENGTH = 254;
8
+ /**
9
+ * A plain address, without a name: a local part and a domain with a dot, and nothing a header could
10
+ * read as the end of an address or of the header.
11
+ */
12
+ const PLAIN_ADDRESS = /^[^\s<>@,;:"()[\]\\]+@[^\s<>@,;:"()[\]\\.]+(?:\.[^\s<>@,;:"()[\]\\.]+)+$/;
13
+ /** Whether `value` is a plain address a reply may go to. */
14
+ export function isEmailAddress(value) {
15
+ return value.length <= EMAIL_ADDRESS_LENGTH && PLAIN_ADDRESS.test(value);
16
+ }
17
+ /**
18
+ * A reply's recipients as it sends them: each address trimmed and in lower case, once, an address
19
+ * in `To` left out of `Cc`. Throws when `to` is empty, an address is not a plain one, or there are
20
+ * more than {@link EMAIL_RECIPIENTS_LIMIT} together.
21
+ */
22
+ export function emailRecipients(input) {
23
+ const normalized = (list) => {
24
+ const addresses = list.map((address) => address.trim().toLowerCase());
25
+ if (addresses.some((address) => !isEmailAddress(address))) {
26
+ throw new Error("A reply's recipient is not a plain address.");
27
+ }
28
+ return [...new Set(addresses)];
29
+ };
30
+ const to = normalized(typeof input.to === "string" ? [input.to] : input.to);
31
+ const cc = normalized(input.cc ?? []).filter((address) => !to.includes(address));
32
+ if (to.length === 0) {
33
+ throw new Error("A reply goes to at least one address.");
34
+ }
35
+ if (to.length + cc.length > EMAIL_RECIPIENTS_LIMIT) {
36
+ throw new Error(`A reply goes to at most ${EMAIL_RECIPIENTS_LIMIT} addresses.`);
37
+ }
38
+ return { to, cc };
39
+ }
40
+ /**
41
+ * An address header, folded so that no line runs much past 78 characters however many addresses it
42
+ * lists: each line after the first starts with a space, as RFC 5322 folds a header.
43
+ */
44
+ function addressHeader(name, addresses) {
45
+ const lines = [];
46
+ let line = `${name}:`;
47
+ for (const [index, address] of addresses.entries()) {
48
+ const item = `${address}${index < addresses.length - 1 ? "," : ""}`;
49
+ if (line.length + 1 + item.length > 78 && line !== `${name}:`) {
50
+ lines.push(line);
51
+ line = ` ${item}`;
52
+ }
53
+ else {
54
+ line = `${line} ${item}`;
55
+ }
56
+ }
57
+ lines.push(line);
58
+ return lines.join("\r\n");
59
+ }
4
60
  /**
5
61
  * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
6
62
  * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
@@ -80,9 +136,10 @@ export const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
80
136
  * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
81
137
  */
82
138
  export function emailReplyMessage(reply) {
83
- if (!/^[^\s<>@,;:"]+@[^\s<>@,;:"]+$/.test(reply.to)) {
84
- throw new Error("The reply's recipient is not a plain address.");
85
- }
139
+ const recipients = emailRecipients({
140
+ to: reply.to,
141
+ ...(reply.cc === undefined ? {} : { cc: reply.cc }),
142
+ });
86
143
  if (reply.replyKey !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(reply.replyKey)) {
87
144
  throw new Error("The reply's key holds characters a header cannot carry.");
88
145
  }
@@ -102,7 +159,8 @@ export function emailReplyMessage(reply) {
102
159
  ...(parent === undefined ? [] : [parent]),
103
160
  ];
104
161
  const headers = [
105
- `To: ${reply.to}`,
162
+ addressHeader("To", recipients.to),
163
+ ...(recipients.cc.length === 0 ? [] : [addressHeader("Cc", recipients.cc)]),
106
164
  `Subject: ${headerText(replySubject(reply.subject))}`,
107
165
  ...(parent === undefined ? [] : [`In-Reply-To: ${parent}`]),
108
166
  ...(references.length === 0 ? [] : [`References: ${[...new Set(references)].join(" ")}`]),
@@ -5,7 +5,7 @@ import { SqlClient } from "effect/unstable/sql";
5
5
  import { action } from "../action.js";
6
6
  import { AgentChat, agentChatKey } from "../agent-chat.js";
7
7
  import { chatChannelKind } from "../chat-channel.js";
8
- import { AgentReview } from "../agent-review.js";
8
+ import { addressesOfReview, AgentReview, participantsOfReview, reviewAddresses, reviewParticipants, } from "../agent-review.js";
9
9
  import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
10
10
  import { inboxChannelsOf, inboxRolesOf, takeoverChannelsOf, takeoverProvidersOf, } from "../manifest.js";
11
11
  import { GUEST_ROLE } from "../names.js";
@@ -221,6 +221,17 @@ export function sqlAgentStore(ontology, sql) {
221
221
  channel: input.channel,
222
222
  chat_id: input.chatId,
223
223
  recipient: input.recipient,
224
+ // A reply to mail names whom it goes to: its person, unless the agent said more.
225
+ ...(input.provider === "email"
226
+ ? {
227
+ to: reviewAddresses(input.to ?? [input.recipient]),
228
+ cc: (input.cc ?? []).length === 0 ? null : reviewAddresses(input.cc ?? []),
229
+ }
230
+ : {}),
231
+ // A reply in a chat several people share is read by the members the agent named.
232
+ participants: (input.participants ?? []).length === 0
233
+ ? null
234
+ : reviewParticipants(input.participants ?? []),
224
235
  chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
225
236
  thread_id: input.threadId === "" ? null : input.threadId,
226
237
  reply_to: input.replyTo,
@@ -649,6 +660,9 @@ export function sqlAgentStore(ontology, sql) {
649
660
  .pipe(Effect.orDie),
650
661
  seeInboxChat: (input) => Effect.gen(function* () {
651
662
  const { memberId } = input;
663
+ // Someone the inbox does not take, writing in a chat several people share, such as an
664
+ // email thread: the chat is answered where it is recorded already, and they do not join it.
665
+ let outsider = false;
652
666
  if (memberId === undefined) {
653
667
  // A chat with someone who is no user joins only on a channel the inbox lists, without
654
668
  // members: nobody is created for them, and staff read it within their scope.
@@ -660,9 +674,15 @@ export function sqlAgentStore(ontology, sql) {
660
674
  const roles = inboxRolesOf(ontology.manifest);
661
675
  const member = isRecordId(memberId) ? yield* store.member(memberId) : undefined;
662
676
  // Only the private chats of people whose roles the inbox takes are recorded.
663
- if (member === undefined || !member.principal.roles.some((role) => roles.has(role))) {
677
+ if (member === undefined) {
664
678
  return undefined;
665
679
  }
680
+ if (!member.principal.roles.some((role) => roles.has(role))) {
681
+ if (input.shared !== true) {
682
+ return undefined;
683
+ }
684
+ outsider = true;
685
+ }
666
686
  }
667
687
  return yield* sql.withTransaction(Effect.gen(function* () {
668
688
  yield* beginReplicationWrite(sql);
@@ -684,7 +704,8 @@ export function sqlAgentStore(ontology, sql) {
684
704
  },
685
705
  });
686
706
  // A group chat's id is never a person's private chat.
687
- if (found !== undefined && found.kind !== "private") {
707
+ if ((found !== undefined && found.kind !== "private") ||
708
+ (outsider && found === undefined)) {
688
709
  return undefined;
689
710
  }
690
711
  const now = new Date();
@@ -717,9 +738,11 @@ export function sqlAgentStore(ontology, sql) {
717
738
  values: changes,
718
739
  });
719
740
  // A private chat has one member, its person now: an account paired with someone else
720
- // since leaves the earlier person out. A link already there changes nothing. A report
721
- // without a person leaves the members as they are.
722
- if (memberId !== undefined) {
741
+ // since leaves the earlier person out. A shared chat, such as an email thread several
742
+ // people write in, keeps every member it had: each message names who reads it. A link
743
+ // already there changes nothing. A report without a person, or by someone the inbox
744
+ // does not take, leaves the members as they are.
745
+ if (memberId !== undefined && !outsider) {
723
746
  const members = yield* runtime.related({
724
747
  entity: AgentChat.name,
725
748
  id: String(chat.id),
@@ -727,7 +750,7 @@ export function sqlAgentStore(ontology, sql) {
727
750
  query: { limit: MAX_QUERY_LIMIT },
728
751
  });
729
752
  for (const member of members.items) {
730
- if (String(member.id) !== memberId) {
753
+ if (input.shared !== true && String(member.id) !== memberId) {
731
754
  yield* runtime.unlink({
732
755
  entity: AgentChat.name,
733
756
  relationship: "members",
@@ -892,6 +915,14 @@ export function sqlAgentStore(ontology, sql) {
892
915
  channel: nullableText(previous.channel) ?? String(previous.provider),
893
916
  chatId: String(previous.chat_id),
894
917
  recipient: String(previous.recipient),
918
+ // A redraft goes to the people the reply it replaces goes to, and is read by the
919
+ // members who read that one.
920
+ ...(addressesOfReview(previous.to).length === 0
921
+ ? {}
922
+ : { to: addressesOfReview(previous.to), cc: addressesOfReview(previous.cc) }),
923
+ ...(participantsOfReview(previous.participants).length === 0
924
+ ? {}
925
+ : { participants: participantsOfReview(previous.participants) }),
895
926
  threadId: nullableText(previous.thread_id) ?? "",
896
927
  replyTo: nullableText(previous.reply_to),
897
928
  memberId: String(previous.person_id),
@@ -31,6 +31,7 @@ export declare const ChatMessageRecordRequest: Schema.Struct<{
31
31
  readonly sessionId: Schema.optionalKey<Schema.String>;
32
32
  readonly turnId: Schema.optionalKey<Schema.String>;
33
33
  readonly meta: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
34
+ readonly imported: Schema.optionalKey<Schema.Literal<true>>;
34
35
  }>;
35
36
  /** `POST /api/ontology/agent/chats/messages/change`: one change to a message. */
36
37
  export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Struct<{
@@ -53,6 +53,9 @@ export const ChatMessageRecordRequest = Schema.Struct({
53
53
  sessionId: Schema.optionalKey(Key),
54
54
  turnId: Schema.optionalKey(Key),
55
55
  meta: Schema.optionalKey(BoundedJson),
56
+ // History the channel read from its provider, from before it recorded the chat: no session reads
57
+ // it as new and no figure counts it, as an import's. Never a send.
58
+ imported: Schema.optionalKey(Schema.Literal(true)),
56
59
  });
57
60
  const Target = { channel: Provider, chatId: ChatId, messageId: MessageId };
58
61
  /** `POST /api/ontology/agent/chats/messages/change`: one change to a message. */
@@ -169,7 +172,7 @@ export function recordChatMessage(store) {
169
172
  if (Result.isFailure(decoded)) {
170
173
  return refused(requestId, 400, "invalid_request", schemaIssues(decoded.failure));
171
174
  }
172
- const { threadId, ...message } = decoded.success;
175
+ const { threadId, imported, ...message } = decoded.success;
173
176
  // A send's replay is told apart from another request by its fingerprint.
174
177
  if ((message.operation === undefined) !== (message.fingerprint === undefined)) {
175
178
  return refused(requestId, 400, "operation_requires_fingerprint");
@@ -177,8 +180,18 @@ export function recordChatMessage(store) {
177
180
  if (message.status !== undefined && message.direction !== "outbound") {
178
181
  return refused(requestId, 400, "status_requires_outbound");
179
182
  }
183
+ // Imported history was sent before the chat was recorded: it is no send of the runtime's.
184
+ if (imported === true &&
185
+ (message.operation !== undefined ||
186
+ (message.status !== undefined && message.status !== "sent"))) {
187
+ return refused(requestId, 400, "imported_send");
188
+ }
180
189
  const recorded = yield* store
181
- .record({ ...message, ...(threadId === undefined || threadId === "" ? {} : { threadId }) })
190
+ .record({
191
+ ...message,
192
+ ...(threadId === undefined || threadId === "" ? {} : { threadId }),
193
+ ...(imported === true ? { importedAt: new Date().toISOString() } : {}),
194
+ })
182
195
  .pipe(Effect.result);
183
196
  if (Result.isFailure(recorded)) {
184
197
  return refused(requestId, 409, recorded.failure.code);
@@ -126,6 +126,7 @@ export declare const ChatSeenRequest: Schema.Struct<{
126
126
  readonly kind: Schema.optionalKey<Schema.Literal<"private">>;
127
127
  readonly recipient: Schema.optionalKey<Schema.String>;
128
128
  readonly threadId: Schema.optionalKey<Schema.String>;
129
+ readonly shared: Schema.optionalKey<Schema.Literal<true>>;
129
130
  }>;
130
131
  /**
131
132
  * `POST /api/ontology/agent/chats/handoff`: the agent hands a person's private chat over to staff,
@@ -147,6 +148,9 @@ export declare const ReviewRequest: Schema.Struct<{
147
148
  readonly channel: Schema.optionalKey<Schema.String>;
148
149
  readonly chat_id: Schema.String;
149
150
  readonly recipient: Schema.String;
151
+ readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
152
+ readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
153
+ readonly participants: Schema.optionalKey<Schema.$Array<Schema.String>>;
150
154
  readonly thread_id: Schema.String;
151
155
  readonly reply_to: Schema.NullOr<Schema.String>;
152
156
  readonly member_id: Schema.String;
@@ -1,6 +1,9 @@
1
1
  import { randomInt } from "node:crypto";
2
2
  import { Schema } from "effect";
3
+ import { AGENT_REVIEW_PARTICIPANTS_LIMIT } from "../../agent-review.js";
3
4
  import { ChatChannelName } from "../../chat-channel.js";
5
+ import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
6
+ import { EMAIL_PATTERN } from "../../property.js";
4
7
  import { GUEST_USD_CEILINGS, MAX_GUEST_USAGE_REPORT_USD } from "../../runtime/agent-counters.js";
5
8
  /** How long a member has to open the connect link, sign in and approve the pairing. */
6
9
  export const PAIRING_TTL_MS = 10 * 60 * 1000;
@@ -126,6 +129,8 @@ export const LimitNoticeRequest = Schema.Struct({
126
129
  notification_id: Schema.String.check(Schema.isUUID()),
127
130
  delivered: Schema.Boolean,
128
131
  });
132
+ /** An address a reply to mail goes to. */
133
+ const EmailAddress = Schema.String.check(Schema.isMaxLength(254), Schema.isPattern(EMAIL_PATTERN));
129
134
  /** A chat's id on the channel. */
130
135
  const ChatId = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH));
131
136
  /**
@@ -160,6 +165,10 @@ export const ChatSeenRequest = Schema.Struct({
160
165
  description: "Whom a reply in the private chat is sent to, where it differs from externalId.",
161
166
  })),
162
167
  threadId: Schema.optionalKey(ChatId.annotate({ description: "The thread a reply in the private chat stays in." })),
168
+ shared: Schema.optionalKey(Schema.Literal(true).annotate({
169
+ description: "A private chat several people write in, such as an email thread: memberId joins its " +
170
+ "members, and no member leaves it. Each message names who reads it.",
171
+ })),
163
172
  });
164
173
  /**
165
174
  * `POST /api/ontology/agent/chats/handoff`: the agent hands a person's private chat over to staff,
@@ -190,6 +199,20 @@ export const ReviewRequest = Schema.Struct({
190
199
  recipient: ChatId.annotate({
191
200
  description: "Whom the provider sends the reply to: the chat's id, or the person's number.",
192
201
  }),
202
+ to: Schema.optionalKey(Schema.Array(EmailAddress)
203
+ .check(Schema.isMinLength(1), Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT))
204
+ .annotate({
205
+ description: "A reply to mail: the addresses it goes to, in To; the recipient when absent.",
206
+ })),
207
+ cc: Schema.optionalKey(Schema.Array(EmailAddress).check(Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT)).annotate({
208
+ description: "A reply to mail: the addresses it copies, in Cc, the thread's other people.",
209
+ })),
210
+ participants: Schema.optionalKey(Schema.Array(Schema.String.check(Schema.isUUID()))
211
+ .check(Schema.isMaxLength(AGENT_REVIEW_PARTICIPANTS_LIMIT))
212
+ .annotate({
213
+ description: "A reply in a chat several people share, such as an email thread: the members who " +
214
+ "read it, by user id, as they read the message it answers; its member alone when absent.",
215
+ })),
193
216
  thread_id: Schema.String.check(Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH)).annotate({
194
217
  description: "The chat's thread or topic; empty without one.",
195
218
  }),
@@ -312,7 +312,7 @@ function seeChat(store) {
312
312
  if (Result.isFailure(decoded)) {
313
313
  return invalidBody(requestId, schemaIssues(decoded.failure));
314
314
  }
315
- const { kind, recipient, threadId, ...seen } = decoded.success;
315
+ const { kind, recipient, threadId, shared, ...seen } = decoded.success;
316
316
  if (kind === "private") {
317
317
  // A person's private chat joins the inbox, which records nothing for anyone else; one
318
318
  // without a person, someone who is no user, joins on a channel the inbox lists.
@@ -328,6 +328,7 @@ function seeChat(store) {
328
328
  ...(seen.memberId === undefined ? {} : { memberId: seen.memberId }),
329
329
  ...(recipient === undefined ? {} : { recipient }),
330
330
  ...(threadId === undefined ? {} : { threadId }),
331
+ ...(shared === undefined ? {} : { shared }),
331
332
  });
332
333
  if (inboxed === undefined) {
333
334
  return toServerResponse(notFound(requestId, "The chat is not one the inbox takes."));
@@ -377,12 +378,23 @@ function holdReply(store) {
377
378
  { path: ["channel"], message: "A workspace channel's reply names its channel." },
378
379
  ]);
379
380
  }
381
+ // Only a reply to mail names whom it goes to beside its recipient.
382
+ if (body.provider !== "email" && (body.to !== undefined || body.cc !== undefined)) {
383
+ return invalidBody(requestId, [
384
+ { path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
385
+ ]);
386
+ }
380
387
  const review = yield* store.holdReply({
381
388
  key: body.key,
382
389
  provider: body.provider,
383
390
  channel: body.channel ?? body.provider,
384
391
  chatId: body.chat_id,
385
392
  recipient: body.recipient,
393
+ ...(body.to === undefined ? {} : { to: body.to.map((address) => address.toLowerCase()) }),
394
+ ...(body.cc === undefined ? {} : { cc: body.cc.map((address) => address.toLowerCase()) }),
395
+ ...(body.participants === undefined
396
+ ? {}
397
+ : { participants: [...new Set(body.participants.map((id) => id.toLowerCase()))] }),
386
398
  threadId: body.thread_id,
387
399
  replyTo: body.reply_to,
388
400
  memberId: body.member_id,
@@ -359,7 +359,10 @@ chats) {
359
359
  query: chatPeopleQuery(chat),
360
360
  })
361
361
  .pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat's person could not be read.", cause })))).items;
362
- if (people.length !== 1) {
362
+ // A thread's chat on a mailbox has no one person to answer: staff answer it in the mail.
363
+ const mailThread = chatKind(ontology.manifest.chat, String(record.provider)) === "email" &&
364
+ !(typeof record.recipient === "string" && record.recipient !== "");
365
+ if (people.length !== 1 || mailThread) {
363
366
  return yield* new ActionRejected({
364
367
  message: "The chat has no person to answer. Nothing was sent.",
365
368
  });
@@ -38,5 +38,13 @@ export declare function deliveryFingerprint(preview: Pick<ChatPreview, "chatId"
38
38
  readonly buttons?: Readonly<Record<string, string>>;
39
39
  },
40
40
  /** Buttons under a text, bound when given so a key without them keeps its binding. */
41
- buttons?: ChatButtonRows): string;
41
+ buttons?: ChatButtonRows,
42
+ /**
43
+ * Whom a reply to mail goes to beside its destination, bound when given so a key that names no
44
+ * one else keeps its binding.
45
+ */
46
+ recipients?: {
47
+ readonly to: ReadonlyArray<string>;
48
+ readonly cc: ReadonlyArray<string>;
49
+ }): string;
42
50
  export {};
@@ -22,7 +22,12 @@ export const deliveryKeyDigest = (idempotencyKey) => digest(JSON.stringify(idemp
22
22
  */
23
23
  export function deliveryFingerprint(preview, requester, template,
24
24
  /** Buttons under a text, bound when given so a key without them keeps its binding. */
25
- buttons) {
25
+ buttons,
26
+ /**
27
+ * Whom a reply to mail goes to beside its destination, bound when given so a key that names no
28
+ * one else keeps its binding.
29
+ */
30
+ recipients) {
26
31
  const sorted = (values) => Object.entries(values).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0));
27
32
  const media = template?.header?.media;
28
33
  return digest(JSON.stringify([
@@ -30,7 +35,12 @@ buttons) {
30
35
  preview.provider,
31
36
  preview.externalId,
32
37
  ...(template === undefined
33
- ? [preview.finalText, preview.text, ...(buttons === undefined ? [] : [{ buttons }])]
38
+ ? [
39
+ preview.finalText,
40
+ preview.text,
41
+ ...(buttons === undefined ? [] : [{ buttons }]),
42
+ ...(recipients === undefined ? [] : [{ to: recipients.to, cc: recipients.cc }]),
43
+ ]
34
44
  : [
35
45
  {
36
46
  template: template.name,
@@ -1,13 +1,14 @@
1
1
  import { Effect } from "effect";
2
2
  import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
3
3
  /**
4
- * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names. It
5
- * reads the thread's subject and its last message first, so the reply carries `Re:`, `In-Reply-To`
6
- * and `References` and the person's mail program shows it in the same conversation; then
7
- * `POST /users/me/messages/send` with the thread id, never retried. A reply sends no attribution
8
- * and names no sender, so it leaves from the mailbox's own address. It carries
9
- * `Auto-Submitted: auto-replied` and `X-SegmentStream-Reply: review-<review id>`, as the email
10
- * channel's replies carry their own keys. `sent` means Gmail accepted it.
4
+ * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
5
+ * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
6
+ * and its last message first, so the reply carries `Re:`, `In-Reply-To` and `References` and the
7
+ * person's mail program shows it in the same conversation; then `POST /users/me/messages/send`
8
+ * with the thread id, never retried. A reply sends no attribution and names no sender, so it
9
+ * leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
10
+ * `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
11
+ * keys. `sent` means Gmail accepted it; the payload keeps whom it went to.
11
12
  */
12
13
  export declare function sendEmail(input: ChatSend): Effect.Effect<ProviderOutcome>;
13
14
  /**
@@ -26,13 +26,14 @@ function headersOf(message) {
26
26
  return found;
27
27
  }
28
28
  /**
29
- * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names. It
30
- * reads the thread's subject and its last message first, so the reply carries `Re:`, `In-Reply-To`
31
- * and `References` and the person's mail program shows it in the same conversation; then
32
- * `POST /users/me/messages/send` with the thread id, never retried. A reply sends no attribution
33
- * and names no sender, so it leaves from the mailbox's own address. It carries
34
- * `Auto-Submitted: auto-replied` and `X-SegmentStream-Reply: review-<review id>`, as the email
35
- * channel's replies carry their own keys. `sent` means Gmail accepted it.
29
+ * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
30
+ * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
31
+ * and its last message first, so the reply carries `Re:`, `In-Reply-To` and `References` and the
32
+ * person's mail program shows it in the same conversation; then `POST /users/me/messages/send`
33
+ * with the thread id, never retried. A reply sends no attribution and names no sender, so it
34
+ * leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
35
+ * `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
36
+ * keys. `sent` means Gmail accepted it; the payload keeps whom it went to.
36
37
  */
37
38
  export function sendEmail(input) {
38
39
  return Effect.gen(function* () {
@@ -72,8 +73,11 @@ export function sendEmail(input) {
72
73
  // The agent's reply, as the email channel sends its own: marked as a program's, so no
73
74
  // autoresponder answers it, and named by its review, so the channel knows it for the agent's.
74
75
  const key = `review-${input.destination.id}`;
76
+ const to = input.recipients?.to ?? [input.destination.external_id];
77
+ const cc = input.recipients?.cc ?? [];
75
78
  const raw = emailReplyMessage({
76
- to: input.destination.external_id,
79
+ to,
80
+ ...(cc.length === 0 ? {} : { cc }),
77
81
  subject: first.get("subject") ?? null,
78
82
  inReplyTo: last.get("message-id") ?? null,
79
83
  references: last.get("references") ?? null,
@@ -82,7 +86,7 @@ export function sendEmail(input) {
82
86
  autoSubmitted: true,
83
87
  ...(/^[A-Za-z0-9_-]{1,128}$/.test(key) ? { replyKey: key } : {}),
84
88
  });
85
- const payload = { threadId, html: input.finalText, text: input.plainText };
89
+ const payload = { threadId, to, cc, html: input.finalText, text: input.plainText };
86
90
  const result = yield* input.transport
87
91
  .request({
88
92
  connection: input.connection,
@@ -60,6 +60,14 @@ export interface ChatSend {
60
60
  * a workspace channel's send receives it, others ignore it.
61
61
  */
62
62
  readonly chatId?: string;
63
+ /**
64
+ * Whom a reply to mail goes to, in `To` and `Cc`, in place of the destination alone; others
65
+ * ignore it.
66
+ */
67
+ readonly recipients?: {
68
+ readonly to: ReadonlyArray<string>;
69
+ readonly cc: ReadonlyArray<string>;
70
+ };
63
71
  }
64
72
  /**
65
73
  * A channel the platform posts exact chat messages to. Each provider names its own ids, renders
@@ -1,4 +1,5 @@
1
1
  import { Effect } from "effect";
2
+ import { type EmailRecipients } from "../../email.js";
2
3
  import type { ReviewSendInput } from "../../chat.js";
3
4
  import type { TelegramPreviewContext } from "../../telegram.js";
4
5
  import { ActionRejected, PermissionDenied } from "../../errors.js";
@@ -11,10 +12,11 @@ import type { AgentChannelTransport } from "./providers/provider.js";
11
12
  /**
12
13
  * Sends a reply the agent held for review, once a member approved it: the draft or the member's
13
14
  * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
14
- * as the agent and without attribution. The archive's delivery claim, keyed by the review and not by
15
- * the member, makes it at most once: a replay of the same approval returns the delivery, and a
16
- * different approval, by another member or with another text, is refused. A provider that refused
17
- * it consumes the claim: the reply is never sent again.
15
+ * as the agent and without attribution. A reply to mail goes to the review's `to` and `cc`, or the
16
+ * addresses the member names in their place. The archive's delivery claim, keyed by the review and
17
+ * not by the member, makes it at most once: a replay of the same approval returns the delivery, and
18
+ * a different approval, by another member, with another text or to other people, is refused. A
19
+ * provider that refused it consumes the claim: the reply is never sent again.
18
20
  */
19
21
  export declare function reviewSender(input: {
20
22
  readonly ontology: Ontology;
@@ -29,11 +31,13 @@ export declare function reviewSender(input: {
29
31
  readonly identityToken: string | undefined;
30
32
  readonly requestId: string;
31
33
  }): (send: ReviewSendInput) => Effect.Effect<{
34
+ recipients?: EmailRecipients | undefined;
32
35
  status: "sent" | "uncertain" | "failed";
33
36
  text: string;
34
37
  messageId: string | null;
35
38
  duplicate: true;
36
39
  } | {
40
+ recipients?: EmailRecipients | undefined;
37
41
  status: "sent" | "uncertain" | "failed";
38
42
  text: string;
39
43
  messageId: string | null;
@@ -1,18 +1,30 @@
1
1
  import { Effect } from "effect";
2
- import { AGENT_REVIEW_TEXT_LIMIT } from "../../agent-review.js";
2
+ import { addressesOfReview, AGENT_REVIEW_TEXT_LIMIT, participantsOfReview, } from "../../agent-review.js";
3
+ import { EMAIL_RECIPIENTS_LIMIT, emailRecipients } from "../../email.js";
3
4
  import { ActionRejected, PermissionDenied } from "../../errors.js";
4
5
  import { effectiveScope } from "../../permissions.js";
5
6
  import { describeChatError } from "./diagnostics.js";
6
7
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
7
8
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
8
9
  import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
10
+ /**
11
+ * Whether a reply to mail goes to the people a review records it went to: its `to`, else its
12
+ * recipient, and its `cc`, whatever their order and case.
13
+ */
14
+ function sameRecipients(recipients, review) {
15
+ const held = addressesOfReview(review.to);
16
+ const set = (list) => [...new Set(list.map((address) => address.toLowerCase()))].sort().join(",");
17
+ return (set(recipients.to) ===
18
+ set(held.length > 0 ? held : typeof review.recipient === "string" ? [review.recipient] : []) && set(recipients.cc) === set(addressesOfReview(review.cc)));
19
+ }
9
20
  /**
10
21
  * Sends a reply the agent held for review, once a member approved it: the draft or the member's
11
22
  * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
12
- * as the agent and without attribution. The archive's delivery claim, keyed by the review and not by
13
- * the member, makes it at most once: a replay of the same approval returns the delivery, and a
14
- * different approval, by another member or with another text, is refused. A provider that refused
15
- * it consumes the claim: the reply is never sent again.
23
+ * as the agent and without attribution. A reply to mail goes to the review's `to` and `cc`, or the
24
+ * addresses the member names in their place. The archive's delivery claim, keyed by the review and
25
+ * not by the member, makes it at most once: a replay of the same approval returns the delivery, and
26
+ * a different approval, by another member, with another text or to other people, is refused. A
27
+ * provider that refused it consumes the claim: the reply is never sent again.
16
28
  */
17
29
  export function reviewSender(input) {
18
30
  const { backend, principal } = input;
@@ -48,13 +60,44 @@ export function reviewSender(input) {
48
60
  const draft = String(review.draft ?? "");
49
61
  const text = send.text ?? draft;
50
62
  const status = String(review.status);
63
+ const email = String(review.provider) === "email";
64
+ // Only a reply to mail names whom it goes to beside its chat.
65
+ if (!email && (send.to !== undefined || send.cc !== undefined)) {
66
+ return yield* new ActionRejected({
67
+ message: "Only a reply to mail takes to and cc; this reply goes to its chat.",
68
+ });
69
+ }
70
+ // A reply to mail goes to the review's `to` and `cc`, the thread's people, unless the member
71
+ // names others; one held before replies named them goes to its recipient alone.
72
+ const held = addressesOfReview(review.to);
73
+ const recipients = email
74
+ ? yield* Effect.try({
75
+ try: () => emailRecipients({
76
+ to: send.to ??
77
+ (held.length > 0
78
+ ? held
79
+ : typeof review.recipient === "string"
80
+ ? [review.recipient]
81
+ : []),
82
+ cc: send.cc ?? addressesOfReview(review.cc),
83
+ }),
84
+ catch: (cause) => new ActionRejected({
85
+ message: `A reply to mail goes to 1 to ${EMAIL_RECIPIENTS_LIMIT} plain addresses ` +
86
+ "together, in to and cc; nothing was sent.",
87
+ cause,
88
+ }),
89
+ })
90
+ : undefined;
51
91
  if (status !== "pending") {
52
- if ((status === "sent" || status === "uncertain") && text === review.text) {
92
+ if ((status === "sent" || status === "uncertain") &&
93
+ text === review.text &&
94
+ (recipients === undefined || sameRecipients(recipients, review))) {
53
95
  return {
54
96
  status,
55
97
  text,
56
98
  messageId: typeof review.message_id === "string" ? review.message_id : null,
57
99
  duplicate: true,
100
+ ...(recipients === undefined ? {} : { recipients }),
58
101
  };
59
102
  }
60
103
  return yield* new ActionRejected({
@@ -140,7 +183,14 @@ export function reviewSender(input) {
140
183
  provider: providerName,
141
184
  external_id: externalId,
142
185
  kind,
143
- participantIds: person === null ? [] : [person],
186
+ // The reply is its person's and, in a chat several people share, such as an email thread,
187
+ // the members the agent named as its readers, as a reply it sent itself would be.
188
+ participantIds: [
189
+ ...new Set([
190
+ ...(person === null ? [] : [person]),
191
+ ...participantsOfReview(review.participants),
192
+ ]),
193
+ ],
144
194
  };
145
195
  const preview = {
146
196
  chatId: target.id,
@@ -159,7 +209,15 @@ export function reviewSender(input) {
159
209
  clientId: null,
160
210
  });
161
211
  const key = deliveryKeyDigest(`agent_review:${operationId}`);
162
- const fingerprint = deliveryFingerprint(preview, requester);
212
+ // A reply to mail that names anyone beside its person binds them, so another approval naming
213
+ // others is refused; one to its person alone keeps the binding it always had.
214
+ const bound = recipients !== undefined &&
215
+ !(recipients.cc.length === 0 &&
216
+ recipients.to.length === 1 &&
217
+ recipients.to[0] === externalId.toLowerCase())
218
+ ? recipients
219
+ : undefined;
220
+ const fingerprint = deliveryFingerprint(preview, requester, undefined, undefined, bound);
163
221
  const event = {
164
222
  eventId: `chat-delivery:${operationId}:reserve`,
165
223
  operationId,
@@ -212,8 +270,8 @@ export function reviewSender(input) {
212
270
  .pipe(Effect.tapError((error) => report("reserve", error)), Effect.mapError((cause) => new ActionRejected({
213
271
  cause,
214
272
  message: cause.diagnostic === "chat_archive_conflict"
215
- ? "The reply was already approved by another member or with another text; " +
216
- "it is never sent again."
273
+ ? "The reply was already approved by another member, with another text " +
274
+ "or to other people; it is never sent again."
217
275
  : "The delivery could not be reserved, and nothing was sent. Approve again.",
218
276
  })));
219
277
  if (!reserve.claimed) {
@@ -227,6 +285,7 @@ export function reviewSender(input) {
227
285
  text,
228
286
  messageId: reserve.messageId,
229
287
  duplicate: true,
288
+ ...(recipients === undefined ? {} : { recipients }),
230
289
  };
231
290
  }
232
291
  if (reserve.version !== 1 ||
@@ -251,6 +310,7 @@ export function reviewSender(input) {
251
310
  threadId,
252
311
  operationId,
253
312
  chatId,
313
+ ...(recipients === undefined ? {} : { recipients }),
254
314
  ...(input.agent === undefined ? {} : { agent: input.agent }),
255
315
  ...(input.previews === undefined ? {} : { previews: input.previews }),
256
316
  transport: input.connections({
@@ -287,6 +347,7 @@ export function reviewSender(input) {
287
347
  text,
288
348
  messageId: outcome.messageId,
289
349
  duplicate: false,
350
+ ...(recipients === undefined ? {} : { recipients }),
290
351
  };
291
352
  });
292
353
  }
@@ -664,9 +664,12 @@ export interface AgentStore {
664
664
  }) => Effect.Effect<SeenChat>;
665
665
  /**
666
666
  * Records a person's private chat with the agent for the inbox: creates the `agent_chat` of kind
667
- * `private`, with the person as its one member, or keeps its title, recipient and thread current,
667
+ * `private`, with the person as its one member (one of its members for a `shared` chat, such as
668
+ * an email thread several people write in), or keeps its title, recipient and thread current,
668
669
  * and records when it last had a message, as `seeChat` does. `undefined`, recording nothing,
669
- * unless the person is an active member holding a role of the ontology's `inbox`. Without
670
+ * unless the person is an active member holding a role of the ontology's `inbox`; in a `shared`
671
+ * chat recorded already, a member without one does not join it, and is answered whether staff
672
+ * hold it. Without
670
673
  * `memberId`, the chat is someone's who is no user: recorded without members, whose members it
671
674
  * leaves as they are, and only on a channel `inbox.channels` lists; no user is created. Absent
672
675
  * on stores that predate the inbox.
@@ -740,6 +743,15 @@ export interface HeldReplyInput {
740
743
  readonly chatId: string;
741
744
  /** Whom the provider sends the reply to: the chat's id, or the person's id where it differs. */
742
745
  readonly recipient: string;
746
+ /** A reply to mail: the addresses it goes to, in `To`; its recipient alone when absent. */
747
+ readonly to?: ReadonlyArray<string>;
748
+ /** A reply to mail: the addresses it copies, in `Cc`; none when absent. */
749
+ readonly cc?: ReadonlyArray<string>;
750
+ /**
751
+ * A reply in a chat several people share, such as an email thread: the members who read it in
752
+ * the chat's history, by user id; its member alone when absent.
753
+ */
754
+ readonly participants?: ReadonlyArray<string>;
743
755
  readonly threadId: string;
744
756
  readonly replyTo: string | null;
745
757
  readonly memberId: string;
@@ -770,6 +782,11 @@ export interface InboxChatInput {
770
782
  readonly recipient?: string;
771
783
  /** The thread a reply stays in. */
772
784
  readonly threadId?: string;
785
+ /**
786
+ * A private chat several people write in, such as an email thread: `memberId` joins its members
787
+ * and no member leaves it. Each message names who reads it.
788
+ */
789
+ readonly shared?: true;
773
790
  }
774
791
  /** The review a held reply became. */
775
792
  export interface HeldReview {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.153.1",
3
+ "version": "0.155.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",