@segmentstream/ontology 0.154.0 → 0.156.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,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.156.0
4
+
5
+ Staff sends live in the workspace chat store. Once `_chat_messages` holds a message, which means the
6
+ agent records its chats there, `agent_chat.postMessage`, `agent_chat.send` and the delivery of an
7
+ approved `agent_review` reserve their idempotency key on the message's own row, `pending` before the
8
+ provider is called, and record its receipt on the same row: `sent` with the provider's message id,
9
+ `uncertain` or `failed` with the refusal. Nothing is written to the chat archive in Cloud, so the
10
+ chat's history, the inbox and the agent's next session read the message at once, rather than after
11
+ the daily copy of the archive. The delivery works as before: a replay of the key with the same
12
+ request sends nothing and answers the recorded receipt, the same key with another request is
13
+ refused, a lost receipt leaves the delivery `uncertain` and never sends it again, and retention
14
+ keeps a send's key and outcome. A member's own reply in the inbox is a person's message (`human`),
15
+ with the member as its sender; anything sent as the agent is the agent's. A provider's echo of the
16
+ message recorded before its receipt leaves one message, the send's. A reservation whose receipt was
17
+ lost is never listed among a channel's sends still to deliver (`messages/read` with `pending`), so
18
+ it never takes the place of a reply the email channel still has to send. Until the store holds a
19
+ message, deliveries reserve in Cloud's archive as before.
20
+
21
+ `chat_search` without a chat searches every chat in the workspace chat store once it holds a
22
+ message, so it finds the agent's messages and staff sends, which live only there, with each row read
23
+ as `chat_history` reads it: a group's messages for its members and every group for `agent_chat:read`,
24
+ a private chat's for the people it names, and the chats the ontology checked for a service.
25
+
26
+ ## 0.155.0
27
+
28
+ 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.
29
+
30
+ `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.
31
+
3
32
  ## 0.154.0
4
33
 
5
34
  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.
@@ -47,10 +47,16 @@ 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;
50
52
  /** Addresses as a review keeps them in `to` and `cc`: separated by commas. */
51
53
  export declare function reviewAddresses(addresses: ReadonlyArray<string>): string;
52
54
  /** The addresses a review keeps in `to` or `cc`; none for an empty value. */
53
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>;
54
60
  export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
55
61
  readonly key: import("./property.js").Property<string, false, true>;
56
62
  readonly provider: import("./property.js").Property<string, false, false>;
@@ -59,6 +65,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
59
65
  readonly recipient: import("./property.js").Property<string, false, false>;
60
66
  readonly to: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
61
67
  readonly cc: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
68
+ readonly participants: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
62
69
  readonly chatKind: import("./property.js").Property<"private" | "group", false, false>;
63
70
  readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
64
71
  readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
@@ -122,6 +129,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
122
129
  readonly recipient: string;
123
130
  readonly to: string | null;
124
131
  readonly cc: string | null;
132
+ readonly participants: string | null;
125
133
  readonly chatKind: "private" | "group";
126
134
  readonly threadId: string | null;
127
135
  readonly replyTo: string | null;
@@ -5,6 +5,7 @@ import { EMAIL_RECIPIENTS_LIMIT } from "./email.js";
5
5
  import { entity } from "./entity.js";
6
6
  import { ActionRejected } from "./errors.js";
7
7
  import { EMAIL_PATTERN, p } from "./property.js";
8
+ import { isUuid } from "./query.js";
8
9
  import { rel } from "./relationship.js";
9
10
  /**
10
11
  * A reply the workspace's agent held for review. `agent/segmentstream.json` says, per role of the
@@ -48,6 +49,10 @@ export const AGENT_REVIEW_REASON_LIMIT = 2_000;
48
49
  export const AGENT_REVIEW_NOTE_LIMIT = 2_000;
49
50
  /** The longest list of addresses a review keeps in `to` or `cc`: as many as a reply goes to. */
50
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;
51
56
  /** An address a member names for a reply to mail. */
52
57
  const EmailAddress = Schema.String.check(Schema.isMaxLength(254), Schema.isPattern(EMAIL_PATTERN));
53
58
  /** Addresses as a review keeps them in `to` and `cc`: separated by commas. */
@@ -63,6 +68,18 @@ export function addressesOfReview(value) {
63
68
  .map((address) => address.trim())
64
69
  .filter((address) => address !== "");
65
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
+ }
66
83
  export const AgentReview = entity("agent_review", {
67
84
  id: "ent_agent_review",
68
85
  label: "Agent reply review",
@@ -110,6 +127,14 @@ export const AgentReview = entity("agent_review", {
110
127
  description: "A reply to mail: the addresses it copies, in Cc, separated by commas, as the thread's " +
111
128
  "other people; once approved, those it was sent to. Empty when it copies no one.",
112
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
+ }),
113
138
  chatKind: p.select([
114
139
  { value: "private", description: "The person's own chat with the agent." },
115
140
  { value: "group", description: "A group chat." },
@@ -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 { addressesOfReview, AgentReview, reviewAddresses } 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";
@@ -228,6 +228,10 @@ export function sqlAgentStore(ontology, sql) {
228
228
  cc: (input.cc ?? []).length === 0 ? null : reviewAddresses(input.cc ?? []),
229
229
  }
230
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 ?? []),
231
235
  chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
232
236
  thread_id: input.threadId === "" ? null : input.threadId,
233
237
  reply_to: input.replyTo,
@@ -656,6 +660,9 @@ export function sqlAgentStore(ontology, sql) {
656
660
  .pipe(Effect.orDie),
657
661
  seeInboxChat: (input) => Effect.gen(function* () {
658
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;
659
666
  if (memberId === undefined) {
660
667
  // A chat with someone who is no user joins only on a channel the inbox lists, without
661
668
  // members: nobody is created for them, and staff read it within their scope.
@@ -667,9 +674,15 @@ export function sqlAgentStore(ontology, sql) {
667
674
  const roles = inboxRolesOf(ontology.manifest);
668
675
  const member = isRecordId(memberId) ? yield* store.member(memberId) : undefined;
669
676
  // Only the private chats of people whose roles the inbox takes are recorded.
670
- if (member === undefined || !member.principal.roles.some((role) => roles.has(role))) {
677
+ if (member === undefined) {
671
678
  return undefined;
672
679
  }
680
+ if (!member.principal.roles.some((role) => roles.has(role))) {
681
+ if (input.shared !== true) {
682
+ return undefined;
683
+ }
684
+ outsider = true;
685
+ }
673
686
  }
674
687
  return yield* sql.withTransaction(Effect.gen(function* () {
675
688
  yield* beginReplicationWrite(sql);
@@ -691,7 +704,8 @@ export function sqlAgentStore(ontology, sql) {
691
704
  },
692
705
  });
693
706
  // A group chat's id is never a person's private chat.
694
- if (found !== undefined && found.kind !== "private") {
707
+ if ((found !== undefined && found.kind !== "private") ||
708
+ (outsider && found === undefined)) {
695
709
  return undefined;
696
710
  }
697
711
  const now = new Date();
@@ -724,9 +738,11 @@ export function sqlAgentStore(ontology, sql) {
724
738
  values: changes,
725
739
  });
726
740
  // A private chat has one member, its person now: an account paired with someone else
727
- // since leaves the earlier person out. A link already there changes nothing. A report
728
- // without a person leaves the members as they are.
729
- 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) {
730
746
  const members = yield* runtime.related({
731
747
  entity: AgentChat.name,
732
748
  id: String(chat.id),
@@ -734,7 +750,7 @@ export function sqlAgentStore(ontology, sql) {
734
750
  query: { limit: MAX_QUERY_LIMIT },
735
751
  });
736
752
  for (const member of members.items) {
737
- if (String(member.id) !== memberId) {
753
+ if (input.shared !== true && String(member.id) !== memberId) {
738
754
  yield* runtime.unlink({
739
755
  entity: AgentChat.name,
740
756
  relationship: "members",
@@ -899,10 +915,14 @@ export function sqlAgentStore(ontology, sql) {
899
915
  channel: nullableText(previous.channel) ?? String(previous.provider),
900
916
  chatId: String(previous.chat_id),
901
917
  recipient: String(previous.recipient),
902
- // A redraft goes to the people the reply it replaces goes to.
918
+ // A redraft goes to the people the reply it replaces goes to, and is read by the
919
+ // members who read that one.
903
920
  ...(addressesOfReview(previous.to).length === 0
904
921
  ? {}
905
922
  : { to: addressesOfReview(previous.to), cc: addressesOfReview(previous.cc) }),
923
+ ...(participantsOfReview(previous.participants).length === 0
924
+ ? {}
925
+ : { participants: participantsOfReview(previous.participants) }),
906
926
  threadId: nullableText(previous.thread_id) ?? "",
907
927
  replyTo: nullableText(previous.reply_to),
908
928
  memberId: String(previous.person_id),
@@ -15,6 +15,13 @@ export type ChatDirection = (typeof CHAT_DIRECTIONS)[number];
15
15
  export type ChatMessageAuthor = (typeof CHAT_MESSAGE_AUTHORS)[number];
16
16
  export type ChatMessageStatus = (typeof CHAT_MESSAGE_STATUSES)[number];
17
17
  export type ChatDisposition = (typeof CHAT_DISPOSITIONS)[number];
18
+ /**
19
+ * The start of a delivery's key, the `operation` of a staff post, a send as the agent or an
20
+ * approved review the ontology service reserves (docs/agent-chat-storage.md, "Staff sends"). No
21
+ * channel sends such a row: the service sends it once, and a reservation whose receipt was lost
22
+ * stays `pending` without ever being sent again.
23
+ */
24
+ export declare const DELIVERY_OPERATION_PREFIX = "delivery:";
18
25
  /** How long a claim on an inbound message holds: an abandoned one is taken again after it. */
19
26
  export declare const CHAT_CLAIM_MINUTES = 10;
20
27
  /** The most rows one purge batch deletes or scrubs, and the most batches one purge runs. */
@@ -152,6 +159,11 @@ export type ChatMessageChange =
152
159
  readonly status: "sent" | "failed" | "uncertain";
153
160
  readonly providerMessageId?: string;
154
161
  readonly failure?: string;
162
+ /**
163
+ * The send's channel state as it went, in place of what its request held, in the receipt's
164
+ * own write; the service's deliveries alone give it, the runtime routes never take it.
165
+ */
166
+ readonly meta?: unknown;
155
167
  }
156
168
  /** A claim given up before its message was dispatched: the message is unclaimed again. */
157
169
  | (Target & {
@@ -201,7 +213,10 @@ export interface ChatMessageQuery {
201
213
  readonly after?: string;
202
214
  readonly before?: ChatCursor;
203
215
  readonly messageId?: string;
204
- /** Outbound messages still `pending`: sends still to deliver. */
216
+ /**
217
+ * Outbound messages still `pending`: sends still to deliver. A delivery the service reserved
218
+ * (`operation` under {@link DELIVERY_OPERATION_PREFIX}) is never one of them.
219
+ */
205
220
  readonly pending?: boolean;
206
221
  /** With `pending`, only the sends requested no later than this time (ISO 8601). */
207
222
  readonly pendingBefore?: string;
@@ -209,10 +224,13 @@ export interface ChatMessageQuery {
209
224
  readonly senderId?: string;
210
225
  readonly limit: number;
211
226
  }
212
- /** A reader's search of one chat, as `chat_history` and `chat_search` ask it. */
227
+ /**
228
+ * A reader's search, as `chat_history` and `chat_search` ask it: of one chat, or, without `chatId`
229
+ * or without `channel`, of every chat they leave open, newest first.
230
+ */
213
231
  export interface ChatMessageSearch {
214
- readonly channel: string;
215
- readonly chatId: string;
232
+ readonly channel?: string;
233
+ readonly chatId?: string;
216
234
  readonly threadId?: string;
217
235
  readonly q?: string;
218
236
  readonly senderId?: string;
@@ -226,18 +244,37 @@ export interface ChatMessageSearch {
226
244
  * Who reads, as the chat archive's reader rule takes it: every group message (`groups`, from
227
245
  * `agent_chat:read` or membership of the chat), this exact chat's messages, never its internal
228
246
  * rows nor sends still unsent (`chat`, a chat the ontology checked the reader may read), and the
229
- * private messages whose `participants` hold `participantId`, row by row.
247
+ * private messages whose `participants` hold `participantId`, row by row. A search of several
248
+ * chats names, by `<channel>:<chat id>`, the groups the reader is in (`groupChats`), read as
249
+ * `groups` reads every group, and the chats the ontology checked (`chats`), each read as `chat`
250
+ * reads the one searched.
230
251
  */
231
252
  export interface ChatMessageReader {
232
253
  readonly participantId: string | null;
233
254
  readonly groups: boolean;
234
255
  readonly chat: boolean;
256
+ readonly groupChats?: ReadonlyArray<string>;
257
+ readonly chats?: ReadonlyArray<string>;
235
258
  }
236
259
  export interface ChatMessagePage {
237
260
  readonly messages: ReadonlyArray<ChatMessage>;
238
261
  /** `after` mode: the revision to read after next; otherwise the cursor of the next page. */
239
262
  readonly nextCursor: string | null;
240
263
  }
264
+ /** A send as its `operation` finds it, its tombstone included. Times are ISO 8601. */
265
+ export interface ChatSend {
266
+ readonly id: string;
267
+ readonly channel: string;
268
+ readonly chatId: string;
269
+ readonly status: ChatMessageStatus | null;
270
+ readonly messageId: string | null;
271
+ readonly failure: string | null;
272
+ readonly fingerprint: string | null;
273
+ readonly meta: unknown;
274
+ readonly at: string;
275
+ /** Retention scrubbed it to its tombstone: its key, fingerprint and outcome stay. */
276
+ readonly purged: boolean;
277
+ }
241
278
  declare const ChatMessageConflict_base: Schema.Class<ChatMessageConflict, Schema.TaggedStruct<"ChatMessageConflict", {
242
279
  readonly code: Schema.Literals<readonly ["operation_conflict", "message_conflict"]>;
243
280
  }>, import("effect/Cause").YieldableError>;
@@ -260,6 +297,8 @@ export interface ChatMessageStore {
260
297
  readonly channel: string;
261
298
  readonly chatId: string;
262
299
  }) => Effect.Effect<boolean>;
300
+ /** The send an `operation` keys, its tombstone included; `undefined` when the key has none. */
301
+ readonly findSend: (operation: string) => Effect.Effect<ChatSend | undefined>;
263
302
  /** One chat's messages as a reader may read them, row by row. */
264
303
  readonly search: (search: ChatMessageSearch, reader: ChatMessageReader) => Effect.Effect<ChatMessagePage>;
265
304
  /**
@@ -19,6 +19,13 @@ export const CHAT_MESSAGE_STATUSES = [
19
19
  "uncertain",
20
20
  ];
21
21
  export const CHAT_DISPOSITIONS = ["claimed", "turn", "skipped"];
22
+ /**
23
+ * The start of a delivery's key, the `operation` of a staff post, a send as the agent or an
24
+ * approved review the ontology service reserves (docs/agent-chat-storage.md, "Staff sends"). No
25
+ * channel sends such a row: the service sends it once, and a reservation whose receipt was lost
26
+ * stays `pending` without ever being sent again.
27
+ */
28
+ export const DELIVERY_OPERATION_PREFIX = "delivery:";
22
29
  /** How long a claim on an inbound message holds: an abandoned one is taken again after it. */
23
30
  export const CHAT_CLAIM_MINUTES = 10;
24
31
  /** The most rows one purge batch deletes or scrubs, and the most batches one purge runs. */
@@ -335,7 +342,7 @@ export function sqlChatMessageStore(sql) {
335
342
  `"deleted_at" = coalesce($6::timestamptz, "deleted_at"), ` +
336
343
  `"parts" = CASE WHEN ${deleted} THEN '[]' ELSE "parts" END, ` +
337
344
  `"files" = CASE WHEN ${deleted} THEN '[]' ELSE "files" END, ` +
338
- `"meta" = CASE WHEN ${deleted} THEN NULL ELSE "meta" END, ` +
345
+ `"meta" = CASE WHEN ${deleted} THEN NULL ELSE coalesce($9::jsonb, "meta") END, ` +
339
346
  `"reactions" = CASE WHEN ${deleted} THEN '[]' ` +
340
347
  `WHEN coalesce($8::jsonb, '[]') <> '[]' THEN $8::jsonb ELSE "reactions" END, ` +
341
348
  `${revised} WHERE "id" = $1::uuid`, [
@@ -347,6 +354,7 @@ export function sqlChatMessageStore(sql) {
347
354
  echo?.deleted_at ?? null,
348
355
  echo?.text ?? null,
349
356
  echo?.reactions ?? null,
357
+ change.meta === undefined ? null : JSON.stringify(change.meta),
350
358
  ]);
351
359
  return { applied: true };
352
360
  }));
@@ -535,7 +543,10 @@ export function sqlChatMessageStore(sql) {
535
543
  conditions.push(`"message_id" = ${params.add(input.messageId)}`);
536
544
  }
537
545
  if (input.pending === true) {
538
- conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`);
546
+ conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`,
547
+ // A delivery the service reserved is never a channel's to send: one whose receipt was
548
+ // lost stays pending, and must not take the place of a send still due.
549
+ `("operation" IS NULL OR "operation" NOT LIKE ${params.add(`${DELIVERY_OPERATION_PREFIX}%`)})`);
539
550
  // Before the limit, so newer sends never fill a page ahead of older ones due.
540
551
  if (input.pendingBefore !== undefined) {
541
552
  conditions.push(`"at" <= ${params.add(input.pendingBefore, "timestamptz")}`);
@@ -548,9 +559,11 @@ export function sqlChatMessageStore(sql) {
548
559
  };
549
560
  const search = (input, reader) => {
550
561
  const params = parameters();
562
+ // Only the filters the search names, never `$1 IS NULL OR …`, which no plan turns into an
563
+ // index condition: one chat is read along its own index, several along the time's.
551
564
  const conditions = [
552
- `"channel" = ${params.add(input.channel)}`,
553
- `"chat_id" = ${params.add(input.chatId)}`,
565
+ ...(input.channel === undefined ? [] : [`"channel" = ${params.add(input.channel)}`]),
566
+ ...(input.chatId === undefined ? [] : [`"chat_id" = ${params.add(input.chatId)}`]),
554
567
  `"purged_at" IS NULL`,
555
568
  ];
556
569
  if (input.threadId !== undefined) {
@@ -570,19 +583,26 @@ export function sqlChatMessageStore(sql) {
570
583
  if (input.q !== undefined && input.q.trim() !== "") {
571
584
  conditions.push(`to_tsvector('simple', coalesce("text", '')) @@ plainto_tsquery('simple', ${params.add(input.q, "text")})`);
572
585
  }
586
+ // An exact chat reads what reached the provider: never a send still unsent, nor one that
587
+ // failed before the provider took it. One it took and later failed stays, `failed`, so a
588
+ // reader polling after a revision sees the same chat as one reading it whole.
589
+ const shown = `("direction" = 'inbound' OR ("direction" = 'outbound' AND ` +
590
+ `("status" IS NULL OR "status" IN ('sent', 'delivered', 'read') OR ` +
591
+ `("status" = 'failed' AND "message_id" IS NOT NULL))))`;
592
+ // A row's chat as the reader's lists name it.
593
+ const chatKey = `("channel" || ':' || "chat_id")`;
594
+ const groupChats = reader.groupChats ?? [];
595
+ const chats = reader.chats ?? [];
573
596
  // The archive's reader rule, row by row: a private message by its own participants.
574
597
  const rules = [
575
598
  ...(reader.groups ? [`"chat_type" <> 'private'`] : []),
576
- // An exact chat reads what reached the provider: never a send still unsent, nor one that
577
- // failed before the provider took it. One it took and later failed stays, `failed`, so a
578
- // reader polling after a revision sees the same chat as one reading it whole.
579
- ...(reader.chat
580
- ? [
581
- `("direction" = 'inbound' OR ("direction" = 'outbound' AND ` +
582
- `("status" IS NULL OR "status" IN ('sent', 'delivered', 'read') OR ` +
583
- `("status" = 'failed' AND "message_id" IS NOT NULL))))`,
584
- ]
585
- : []),
599
+ ...(groupChats.length === 0
600
+ ? []
601
+ : [`("chat_type" <> 'private' AND ${chatKey} = ANY(${params.add(groupChats, "text[]")}))`]),
602
+ ...(reader.chat ? [shown] : []),
603
+ ...(chats.length === 0
604
+ ? []
605
+ : [`(${chatKey} = ANY(${params.add(chats, "text[]")}) AND ${shown})`]),
586
606
  ...(reader.participantId === null
587
607
  ? []
588
608
  : [
@@ -599,6 +619,22 @@ export function sqlChatMessageStore(sql) {
599
619
  const holds = (chat) => rows(chat === undefined
600
620
  ? `SELECT EXISTS (SELECT 1 FROM ${TABLE}) AS "holds"`
601
621
  : `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE "channel" = $1 AND "chat_id" = $2) AS "holds"`, chat === undefined ? [] : [chat.channel, chat.chatId]).pipe(Effect.map(([row]) => row?.holds === true || row?.holds === "t"));
622
+ const findSend = (operation) => rows(`SELECT "id"::text AS "id", "channel", "chat_id", "status", "message_id", "failure", ` +
623
+ `"fingerprint", "meta"::text AS "meta", ${epochMs(`"at"`)} AS "at", ` +
624
+ `"purged_at" IS NOT NULL AS "purged" FROM ${TABLE} WHERE "operation" = $1 LIMIT 1`, [operation]).pipe(Effect.map(([row]) => row === undefined
625
+ ? undefined
626
+ : {
627
+ id: String(row.id),
628
+ channel: String(row.channel),
629
+ chatId: String(row.chat_id),
630
+ status: (row.status ?? null),
631
+ messageId: text(row.message_id),
632
+ failure: text(row.failure),
633
+ fingerprint: text(row.fingerprint),
634
+ meta: row.meta === null || row.meta === undefined ? null : json(row.meta),
635
+ at: instant(row.at),
636
+ purged: row.purged === true || row.purged === "t",
637
+ }));
602
638
  const purge = ({ retentionDays }) => Effect.gen(function* () {
603
639
  let deleted = 0;
604
640
  let scrubbed = 0;
@@ -633,5 +669,5 @@ export function sqlChatMessageStore(sql) {
633
669
  }
634
670
  return { deleted, scrubbed, more };
635
671
  });
636
- return { record, change, read, holds, search, purge };
672
+ return { record, change, read, holds, findSend, search, purge };
637
673
  }
@@ -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,
@@ -149,6 +150,7 @@ export declare const ReviewRequest: Schema.Struct<{
149
150
  readonly recipient: Schema.String;
150
151
  readonly to: Schema.optionalKey<Schema.$Array<Schema.String>>;
151
152
  readonly cc: Schema.optionalKey<Schema.$Array<Schema.String>>;
153
+ readonly participants: Schema.optionalKey<Schema.$Array<Schema.String>>;
152
154
  readonly thread_id: Schema.String;
153
155
  readonly reply_to: Schema.NullOr<Schema.String>;
154
156
  readonly member_id: Schema.String;
@@ -1,5 +1,6 @@
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";
4
5
  import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
5
6
  import { EMAIL_PATTERN } from "../../property.js";
@@ -164,6 +165,10 @@ export const ChatSeenRequest = Schema.Struct({
164
165
  description: "Whom a reply in the private chat is sent to, where it differs from externalId.",
165
166
  })),
166
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
+ })),
167
172
  });
168
173
  /**
169
174
  * `POST /api/ontology/agent/chats/handoff`: the agent hands a person's private chat over to staff,
@@ -202,6 +207,12 @@ export const ReviewRequest = Schema.Struct({
202
207
  cc: Schema.optionalKey(Schema.Array(EmailAddress).check(Schema.isMaxLength(EMAIL_RECIPIENTS_LIMIT)).annotate({
203
208
  description: "A reply to mail: the addresses it copies, in Cc, the thread's other people.",
204
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
+ })),
205
216
  thread_id: Schema.String.check(Schema.isMaxLength(MAX_EXTERNAL_ID_LENGTH)).annotate({
206
217
  description: "The chat's thread or topic; empty without one.",
207
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."));
@@ -391,6 +392,9 @@ function holdReply(store) {
391
392
  recipient: body.recipient,
392
393
  ...(body.to === undefined ? {} : { to: body.to.map((address) => address.toLowerCase()) }),
393
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()))] }),
394
398
  threadId: body.thread_id,
395
399
  replyTo: body.reply_to,
396
400
  memberId: body.member_id,
@@ -67,6 +67,12 @@ export type DeliveryFinder = (input: {
67
67
  readonly delivery: Pick<DeliveryCommand, "scope" | "key" | "fingerprint">;
68
68
  readonly identityToken: string | undefined;
69
69
  }) => Effect.Effect<DeliveryReceipt | undefined, DeliveryArchiveError>;
70
+ /**
71
+ * Where an exact delivery reserves its key before the provider is called, and records its receipt
72
+ * after: the workspace chat store once it holds a message (`storeDeliveryArchive`), the chat
73
+ * archive in Cloud before it (`platformDeliveryArchive`). Only a `claimed` reservation grants one
74
+ * provider attempt.
75
+ */
70
76
  export type DeliveryArchive = ((input: {
71
77
  readonly event: DeliveryEvent;
72
78
  readonly delivery: DeliveryCommand;
@@ -75,6 +81,11 @@ export type DeliveryArchive = ((input: {
75
81
  /** Finds a key's receipt before a message that is read when it is sent, such as a template. */
76
82
  readonly find?: DeliveryFinder;
77
83
  };
78
- /** One append attempt only. A response without the v1 claim protocol cannot authorize a send. */
84
+ /**
85
+ * The chat archive in Cloud, which reserves and receipts a delivery while the workspace chat store
86
+ * holds no message. One append attempt only. A response without the v1 claim protocol cannot
87
+ * authorize a send.
88
+ * @legacy agent.cloud-chat-archive
89
+ */
79
90
  export declare function platformDeliveryArchive(environment: OntologyEnvironment, fetchImpl?: typeof fetch): DeliveryArchive;
80
91
  export {};
@@ -16,7 +16,12 @@ export class DeliveryArchiveError extends Schema.TaggedError()("DeliveryArchiveE
16
16
  cause: Schema.optionalKey(Schema.Unknown),
17
17
  }) {
18
18
  }
19
- /** One append attempt only. A response without the v1 claim protocol cannot authorize a send. */
19
+ /**
20
+ * The chat archive in Cloud, which reserves and receipts a delivery while the workspace chat store
21
+ * holds no message. One append attempt only. A response without the v1 claim protocol cannot
22
+ * authorize a send.
23
+ * @legacy agent.cloud-chat-archive
24
+ */
20
25
  export function platformDeliveryArchive(environment, fetchImpl = fetch) {
21
26
  const call = (path, body, identityToken, failure, answer) => Effect.tryPromise({
22
27
  try: async (signal) => {
@@ -25,7 +25,13 @@ export type ChatDeliveryFactory = (input: {
25
25
  * private source matches a private destination on the same provider by its `peer`.
26
26
  */
27
27
  export declare function sameChat(source: NonNullable<RuntimeChatEnvelope["source"]>, target: Pick<Destination, "provider" | "external_id" | "kind">): boolean;
28
- export declare function makeChatDelivery(ontology: Ontology, connections: ConnectionTransportFactory, archive: DeliveryArchive, previews?: TelegramPreviewContext,
28
+ export declare function makeChatDelivery(ontology: Ontology, connections: ConnectionTransportFactory,
29
+ /**
30
+ * The chat archive in Cloud, where a delivery reserves its key while the workspace chat store
31
+ * holds no message; on the store after that.
32
+ * @legacy agent.cloud-chat-archive
33
+ */
34
+ cloud: DeliveryArchive, previews?: TelegramPreviewContext,
29
35
  /**
30
36
  * The app's agent at the deployment's production origin, which sends through a workspace
31
37
  * channel; `fetch` by default. Without an origin nothing goes through one.