@segmentstream/ontology 0.153.0 → 0.154.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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.154.0
4
+
5
+ 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.
6
+
7
+ 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`.
8
+
9
+ In the app, `useInboxChat`'s held replies carry `to` and `cc`, and `approve(reply, text?, { to, cc })` replaces them.
10
+
11
+ ## 0.153.1
12
+
13
+ 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.
14
+
3
15
  ## 0.153.0
4
16
 
5
17
  An email channel with `record: "all"` takes the mailbox's chats into the inbox. A verified sender's chat that has no member joins the inbox without members when the ontology's `inbox.channels` lists the channel, which may now name an email channel. Mail that failed DMARC never joins. Mail staff send from the mailbox is recorded in each recipient's chat, including a chat the agent has none of yet, when `recordQuery`, if any, finds it.
@@ -47,12 +47,18 @@ 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
+ /** Addresses as a review keeps them in `to` and `cc`: separated by commas. */
51
+ export declare function reviewAddresses(addresses: ReadonlyArray<string>): string;
52
+ /** The addresses a review keeps in `to` or `cc`; none for an empty value. */
53
+ export declare function addressesOfReview(value: unknown): ReadonlyArray<string>;
50
54
  export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
51
55
  readonly key: import("./property.js").Property<string, false, true>;
52
56
  readonly provider: import("./property.js").Property<string, false, false>;
53
57
  readonly channel: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
54
58
  readonly chatId: import("./property.js").Property<string, false, false>;
55
59
  readonly recipient: import("./property.js").Property<string, false, false>;
60
+ readonly to: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
61
+ readonly cc: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
56
62
  readonly chatKind: import("./property.js").Property<"private" | "group", false, false>;
57
63
  readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
58
64
  readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
@@ -78,7 +84,11 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
78
84
  readonly approve: import("./action.js").Action<Schema.Struct<{
79
85
  readonly review: Schema.Codec<string, string, never, never>;
80
86
  readonly text: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
87
+ readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
88
+ readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
81
89
  }>, {
90
+ to?: readonly string[] | undefined;
91
+ cc?: readonly string[] | undefined;
82
92
  review: string;
83
93
  status: "sent" | "uncertain" | "failed";
84
94
  message_id: string | null;
@@ -110,6 +120,8 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
110
120
  readonly channel: string | null;
111
121
  readonly chatId: string;
112
122
  readonly recipient: string;
123
+ readonly to: string | null;
124
+ readonly cc: string | null;
113
125
  readonly chatKind: "private" | "group";
114
126
  readonly threadId: string | null;
115
127
  readonly replyTo: string | null;
@@ -1,9 +1,10 @@
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";
7
8
  import { rel } from "./relationship.js";
8
9
  /**
9
10
  * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
@@ -45,6 +46,23 @@ export const AGENT_REVIEW_TEXT_LIMIT = 20_000;
45
46
  export const AGENT_REVIEW_REASON_LIMIT = 2_000;
46
47
  /** The longest note a member gives the agent for redrafting a reply. */
47
48
  export const AGENT_REVIEW_NOTE_LIMIT = 2_000;
49
+ /** The longest list of addresses a review keeps in `to` or `cc`: as many as a reply goes to. */
50
+ const AGENT_REVIEW_RECIPIENTS_LENGTH = EMAIL_RECIPIENTS_LIMIT * 256;
51
+ /** An address a member names for a reply to mail. */
52
+ const EmailAddress = Schema.String.check(Schema.isMaxLength(254), Schema.isPattern(EMAIL_PATTERN));
53
+ /** Addresses as a review keeps them in `to` and `cc`: separated by commas. */
54
+ export function reviewAddresses(addresses) {
55
+ return addresses.join(", ");
56
+ }
57
+ /** The addresses a review keeps in `to` or `cc`; none for an empty value. */
58
+ export function addressesOfReview(value) {
59
+ return typeof value !== "string"
60
+ ? []
61
+ : value
62
+ .split(",")
63
+ .map((address) => address.trim())
64
+ .filter((address) => address !== "");
65
+ }
48
66
  export const AgentReview = entity("agent_review", {
49
67
  id: "ent_agent_review",
50
68
  label: "Agent reply review",
@@ -77,6 +95,21 @@ export const AgentReview = entity("agent_review", {
77
95
  managed: true,
78
96
  description: "Whom the provider sends the reply to: the chat's id, or the person's number on WhatsApp.",
79
97
  }),
98
+ to: p.text({
99
+ optional: true,
100
+ managed: true,
101
+ maxLength: AGENT_REVIEW_RECIPIENTS_LENGTH,
102
+ description: "A reply to mail: the addresses it goes to, in To, separated by commas; once approved, " +
103
+ "those it was sent to. Empty on another channel, and on a reply held before replies " +
104
+ "named them, which goes to recipient.",
105
+ }),
106
+ cc: p.text({
107
+ optional: true,
108
+ managed: true,
109
+ maxLength: AGENT_REVIEW_RECIPIENTS_LENGTH,
110
+ description: "A reply to mail: the addresses it copies, in Cc, separated by commas, as the thread's " +
111
+ "other people; once approved, those it was sent to. Empty when it copies no one.",
112
+ }),
80
113
  chatKind: p.select([
81
114
  { value: "private", description: "The person's own chat with the agent." },
82
115
  { value: "group", description: "A group chat." },
@@ -201,8 +234,10 @@ export const AgentReview = entity("agent_review", {
201
234
  }).actions((self) => ({
202
235
  approve: action({
203
236
  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 " +
237
+ "text (Markdown), as the agent and without sender attribution. A reply to mail goes to " +
238
+ "the review's to and cc, the thread's people; to and cc, each a list of addresses, " +
239
+ "replace them. Confirm the final text and, for mail, its recipients with the member " +
240
+ "first. It is sent at most once: approving again with the same text and recipients " +
206
241
  "returns the delivery, and an approved or rejected review is refused otherwise. status " +
207
242
  "failed means the provider refused it and nothing was sent.",
208
243
  hints: { destructive: false, irreversible: true, idempotent: true },
@@ -212,6 +247,18 @@ export const AgentReview = entity("agent_review", {
212
247
  maxLength: AGENT_REVIEW_TEXT_LIMIT,
213
248
  description: "The member's edit of the reply; omit it to send the draft.",
214
249
  })),
250
+ to: Schema.optionalKey(Schema.Array(EmailAddress)
251
+ .check(Schema.isMinLength(1), Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT))
252
+ .annotate({
253
+ description: "A reply to mail: the addresses it goes to, in place of the review's to; omit it " +
254
+ "to keep them.",
255
+ })),
256
+ cc: Schema.optionalKey(Schema.Array(EmailAddress)
257
+ .check(Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT))
258
+ .annotate({
259
+ description: "A reply to mail: the addresses it copies, in place of the review's cc; [] copies " +
260
+ "no one, and omitting it keeps them.",
261
+ })),
215
262
  }),
216
263
  connections: [],
217
264
  prepare: ({ input }) => Effect.gen(function* () {
@@ -225,24 +272,34 @@ export const AgentReview = entity("agent_review", {
225
272
  return yield* send({
226
273
  review: String(input.review),
227
274
  ...(input.text === undefined ? {} : { text: input.text }),
275
+ ...(input.to === undefined ? {} : { to: input.to }),
276
+ ...(input.cc === undefined ? {} : { cc: input.cc }),
228
277
  });
229
278
  }),
230
279
  handler: ({ input, prepared, principal }) => Effect.gen(function* () {
231
280
  const review = yield* self.get(input.review, { forUpdate: true });
281
+ const recipients = prepared.recipients;
232
282
  // The delivery happened, or definitely did not: the record says what the provider did,
233
- // even when another member rejected the review meanwhile.
283
+ // and whom a reply to mail went to, even when another member rejected the review meanwhile.
234
284
  yield* self.update(review, {
235
285
  status: prepared.status,
236
286
  text: prepared.text,
237
287
  messageId: prepared.messageId,
238
288
  decidedAt: review.decidedAt ?? new Date().toISOString(),
239
289
  decidedBy: review.decidedById ?? principal.id,
290
+ ...(recipients === undefined
291
+ ? {}
292
+ : {
293
+ to: reviewAddresses(recipients.to),
294
+ cc: recipients.cc.length === 0 ? null : reviewAddresses(recipients.cc),
295
+ }),
240
296
  });
241
297
  return {
242
298
  review: review.id,
243
299
  status: prepared.status,
244
300
  message_id: prepared.messageId,
245
301
  duplicate: prepared.duplicate,
302
+ ...(recipients === undefined ? {} : { to: recipients.to, cc: recipients.cc }),
246
303
  };
247
304
  }),
248
305
  }),
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, reviewAddresses } 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,13 @@ 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
+ : {}),
224
231
  chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
225
232
  thread_id: input.threadId === "" ? null : input.threadId,
226
233
  reply_to: input.replyTo,
@@ -892,6 +899,10 @@ export function sqlAgentStore(ontology, sql) {
892
899
  channel: nullableText(previous.channel) ?? String(previous.provider),
893
900
  chatId: String(previous.chat_id),
894
901
  recipient: String(previous.recipient),
902
+ // A redraft goes to the people the reply it replaces goes to.
903
+ ...(addressesOfReview(previous.to).length === 0
904
+ ? {}
905
+ : { to: addressesOfReview(previous.to), cc: addressesOfReview(previous.cc) }),
895
906
  threadId: nullableText(previous.thread_id) ?? "",
896
907
  replyTo: nullableText(previous.reply_to),
897
908
  memberId: String(previous.person_id),
@@ -265,6 +265,26 @@ export function sqlChatMessageStore(sql) {
265
265
  `AND "message_id" = ${params.add(change.messageId)} ` +
266
266
  `AND "purged_at" IS NULL${guard.map((condition) => ` AND ${condition}`).join("")} ` +
267
267
  `RETURNING "id"`, params.values)).pipe(Effect.map((updated) => ({ applied: updated.length > 0 })));
268
+ /**
269
+ * Discards a chat's stored attachments, by their ids, that a message no longer holds: a channel
270
+ * that keeps files would otherwise keep them for as long as the chat's messages.
271
+ */
272
+ const discard = (ids, channel, chatId) => Effect.gen(function* () {
273
+ if (ids.length === 0) {
274
+ return;
275
+ }
276
+ const [storage] = yield* rows(`SELECT to_regclass('"${ATTACHMENTS_TABLE}"') IS NOT NULL AS "present"`);
277
+ if (storage?.present === true || storage?.present === "t") {
278
+ yield* rows(`UPDATE "${ATTACHMENTS_TABLE}" SET "state" = 'discarded', "expires_at" = now() ` +
279
+ `WHERE "id"::text = ANY($1::text[]) AND "conversation" = $2 ` +
280
+ `AND "state" IN ('received', 'ready')`, [ids, `${channel}:${chatId}`]);
281
+ }
282
+ });
283
+ /** The attachment ids a message's `files` names. */
284
+ const fileIds = (files) => jsonArray(files).flatMap((file) => {
285
+ const id = file.id;
286
+ return typeof id === "string" ? [id] : [];
287
+ });
268
288
  const revised = `"revision" = ${NEXT_REVISION}`;
269
289
  const sent = (change) => inChat(change.channel, change.chatId, Effect.gen(function* () {
270
290
  const [row] = yield* rows(`SELECT "id"::text AS "id", "status" FROM ${TABLE} ` +
@@ -349,18 +369,7 @@ export function sqlChatMessageStore(sql) {
349
369
  if (deleted === undefined) {
350
370
  return { applied: false };
351
371
  }
352
- const files = jsonArray(deleted.files).flatMap((file) => {
353
- const id = file.id;
354
- return typeof id === "string" ? [id] : [];
355
- });
356
- const [storage] = files.length === 0
357
- ? []
358
- : yield* rows(`SELECT to_regclass('"${ATTACHMENTS_TABLE}"') IS NOT NULL AS "present"`);
359
- if (storage?.present === true || storage?.present === "t") {
360
- yield* rows(`UPDATE "${ATTACHMENTS_TABLE}" SET "state" = 'discarded', "expires_at" = now() ` +
361
- `WHERE "id"::text = ANY($1::text[]) AND "conversation" = $2 ` +
362
- `AND "state" IN ('received', 'ready')`, [files, `${input.channel}:${input.chatId}`]);
363
- }
372
+ yield* discard(fileIds(deleted.files), input.channel, input.chatId);
364
373
  return { applied: true };
365
374
  }));
366
375
  const change = (input) => {
@@ -378,20 +387,45 @@ export function sqlChatMessageStore(sql) {
378
387
  : [
379
388
  `coalesce("meta", 'null'::jsonb) = ${params.add(JSON.stringify(input.expected ?? null), "jsonb")}`,
380
389
  ];
381
- // An edit older than the one applied, a late or retried delivery, changes nothing.
382
- return update(input, params, [
390
+ const assignments = [
383
391
  `"text" = ${edited}`,
384
392
  `"files" = ${files}`,
385
393
  `"meta" = ${meta}`,
386
394
  `"edited_at" = ${at}`,
387
395
  revised,
388
- ], [
396
+ ];
397
+ // An edit older than the one applied, a late or retried delivery, changes nothing.
398
+ const guard = [
389
399
  `"deleted_at" IS NULL`,
390
400
  `("text" IS DISTINCT FROM ${edited} OR "files" IS DISTINCT FROM ${files} ` +
391
401
  `OR "meta" IS DISTINCT FROM ${meta})`,
392
402
  `("edited_at" IS NULL OR "edited_at" <= ${at})`,
393
403
  ...guarded,
394
- ]);
404
+ ];
405
+ if (input.files === undefined) {
406
+ return update(input, params, assignments, guard);
407
+ }
408
+ const replaced = input.files;
409
+ const target = [
410
+ `"channel" = ${params.add(input.channel)}`,
411
+ `"chat_id" = ${params.add(input.chatId)}`,
412
+ `"message_id" = ${params.add(input.messageId)}`,
413
+ `"purged_at" IS NULL`,
414
+ ];
415
+ // The files an edit replaced are discarded, as a deleted message's are.
416
+ return inChat(input.channel, input.chatId, Effect.gen(function* () {
417
+ const [applied] = yield* rows(`WITH "before" AS (SELECT "id" AS "before_id", "files" AS "before_files" ` +
418
+ `FROM ${TABLE} WHERE ${target.join(" AND ")} FOR UPDATE) ` +
419
+ `UPDATE ${TABLE} SET ${assignments.join(", ")} FROM "before" ` +
420
+ `WHERE ${TABLE}."id" = "before"."before_id" AND ${guard.join(" AND ")} ` +
421
+ `RETURNING "before"."before_files"::text AS "files"`, params.values);
422
+ if (applied === undefined) {
423
+ return { applied: false };
424
+ }
425
+ const kept = new Set(replaced.map((file) => file.id));
426
+ yield* discard(fileIds(applied.files).filter((id) => !kept.has(id)), input.channel, input.chatId);
427
+ return { applied: true };
428
+ }));
395
429
  }
396
430
  case "delete":
397
431
  return remove(input);
@@ -147,6 +147,8 @@ export declare const ReviewRequest: Schema.Struct<{
147
147
  readonly channel: Schema.optionalKey<Schema.String>;
148
148
  readonly chat_id: Schema.String;
149
149
  readonly recipient: Schema.String;
150
+ readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
151
+ readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
150
152
  readonly thread_id: Schema.String;
151
153
  readonly reply_to: Schema.NullOr<Schema.String>;
152
154
  readonly member_id: Schema.String;
@@ -1,6 +1,8 @@
1
1
  import { randomInt } from "node:crypto";
2
2
  import { Schema } from "effect";
3
3
  import { ChatChannelName } from "../../chat-channel.js";
4
+ import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
5
+ import { EMAIL_PATTERN } from "../../property.js";
4
6
  import { GUEST_USD_CEILINGS, MAX_GUEST_USAGE_REPORT_USD } from "../../runtime/agent-counters.js";
5
7
  /** How long a member has to open the connect link, sign in and approve the pairing. */
6
8
  export const PAIRING_TTL_MS = 10 * 60 * 1000;
@@ -126,6 +128,8 @@ export const LimitNoticeRequest = Schema.Struct({
126
128
  notification_id: Schema.String.check(Schema.isUUID()),
127
129
  delivered: Schema.Boolean,
128
130
  });
131
+ /** An address a reply to mail goes to. */
132
+ const EmailAddress = Schema.String.check(Schema.isMaxLength(254), Schema.isPattern(EMAIL_PATTERN));
129
133
  /** A chat's id on the channel. */
130
134
  const ChatId = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH));
131
135
  /**
@@ -190,6 +194,14 @@ export const ReviewRequest = Schema.Struct({
190
194
  recipient: ChatId.annotate({
191
195
  description: "Whom the provider sends the reply to: the chat's id, or the person's number.",
192
196
  }),
197
+ to: Schema.optionalKey(Schema.Array(EmailAddress)
198
+ .check(Schema.isMinLength(1), Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT))
199
+ .annotate({
200
+ description: "A reply to mail: the addresses it goes to, in To; the recipient when absent.",
201
+ })),
202
+ cc: Schema.optionalKey(Schema.Array(EmailAddress).check(Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT)).annotate({
203
+ description: "A reply to mail: the addresses it copies, in Cc, the thread's other people.",
204
+ })),
193
205
  thread_id: Schema.String.check(Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH)).annotate({
194
206
  description: "The chat's thread or topic; empty without one.",
195
207
  }),
@@ -377,12 +377,20 @@ function holdReply(store) {
377
377
  { path: ["channel"], message: "A workspace channel's reply names its channel." },
378
378
  ]);
379
379
  }
380
+ // Only a reply to mail names whom it goes to beside its recipient.
381
+ if (body.provider !== "email" && (body.to !== undefined || body.cc !== undefined)) {
382
+ return invalidBody(requestId, [
383
+ { path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
384
+ ]);
385
+ }
380
386
  const review = yield* store.holdReply({
381
387
  key: body.key,
382
388
  provider: body.provider,
383
389
  channel: body.channel ?? body.provider,
384
390
  chatId: body.chat_id,
385
391
  recipient: body.recipient,
392
+ ...(body.to === undefined ? {} : { to: body.to.map((address) => address.toLowerCase()) }),
393
+ ...(body.cc === undefined ? {} : { cc: body.cc.map((address) => address.toLowerCase()) }),
386
394
  threadId: body.thread_id,
387
395
  replyTo: body.reply_to,
388
396
  memberId: body.member_id,
@@ -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 } 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({
@@ -159,7 +202,15 @@ export function reviewSender(input) {
159
202
  clientId: null,
160
203
  });
161
204
  const key = deliveryKeyDigest(`agent_review:${operationId}`);
162
- const fingerprint = deliveryFingerprint(preview, requester);
205
+ // A reply to mail that names anyone beside its person binds them, so another approval naming
206
+ // others is refused; one to its person alone keeps the binding it always had.
207
+ const bound = recipients !== undefined &&
208
+ !(recipients.cc.length === 0 &&
209
+ recipients.to.length === 1 &&
210
+ recipients.to[0] === externalId.toLowerCase())
211
+ ? recipients
212
+ : undefined;
213
+ const fingerprint = deliveryFingerprint(preview, requester, undefined, undefined, bound);
163
214
  const event = {
164
215
  eventId: `chat-delivery:${operationId}:reserve`,
165
216
  operationId,
@@ -212,8 +263,8 @@ export function reviewSender(input) {
212
263
  .pipe(Effect.tapError((error) => report("reserve", error)), Effect.mapError((cause) => new ActionRejected({
213
264
  cause,
214
265
  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."
266
+ ? "The reply was already approved by another member, with another text " +
267
+ "or to other people; it is never sent again."
217
268
  : "The delivery could not be reserved, and nothing was sent. Approve again.",
218
269
  })));
219
270
  if (!reserve.claimed) {
@@ -227,6 +278,7 @@ export function reviewSender(input) {
227
278
  text,
228
279
  messageId: reserve.messageId,
229
280
  duplicate: true,
281
+ ...(recipients === undefined ? {} : { recipients }),
230
282
  };
231
283
  }
232
284
  if (reserve.version !== 1 ||
@@ -251,6 +303,7 @@ export function reviewSender(input) {
251
303
  threadId,
252
304
  operationId,
253
305
  chatId,
306
+ ...(recipients === undefined ? {} : { recipients }),
254
307
  ...(input.agent === undefined ? {} : { agent: input.agent }),
255
308
  ...(input.previews === undefined ? {} : { previews: input.previews }),
256
309
  transport: input.connections({
@@ -287,6 +340,7 @@ export function reviewSender(input) {
287
340
  text,
288
341
  messageId: outcome.messageId,
289
342
  duplicate: false,
343
+ ...(recipients === undefined ? {} : { recipients }),
290
344
  };
291
345
  });
292
346
  }
@@ -740,6 +740,10 @@ export interface HeldReplyInput {
740
740
  readonly chatId: string;
741
741
  /** Whom the provider sends the reply to: the chat's id, or the person's id where it differs. */
742
742
  readonly recipient: string;
743
+ /** A reply to mail: the addresses it goes to, in `To`; its recipient alone when absent. */
744
+ readonly to?: ReadonlyArray<string>;
745
+ /** A reply to mail: the addresses it copies, in `Cc`; none when absent. */
746
+ readonly cc?: ReadonlyArray<string>;
743
747
  readonly threadId: string;
744
748
  readonly replyTo: string | null;
745
749
  readonly memberId: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.153.0",
3
+ "version": "0.154.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",