@segmentstream/ontology 0.166.1 → 0.168.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.
@@ -1,7 +1,10 @@
1
1
  import { Effect } from "effect";
2
2
  import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
3
- import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, GmailMaybeSent, renderEmailHtml, sendGmailMessage, } from "../../../email.js";
3
+ import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
4
+ import { mailboxSignature } from "../../../gmail-send.js";
5
+ import { ActionRejected } from "../../../errors.js";
4
6
  import { EMAIL_PATTERN } from "../../../property.js";
7
+ import { describeChatError } from "../diagnostics.js";
5
8
  import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportFailure, } from "./provider.js";
6
9
  /** A Gmail id, of a thread or a message. */
7
10
  const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
@@ -26,6 +29,82 @@ function headersOf(message) {
26
29
  }
27
30
  return found;
28
31
  }
32
+ /** A message's `labelIds`, which Gmail lists on each message of a thread. */
33
+ function labelsOf(message) {
34
+ const labels = record(message).labelIds;
35
+ return Array.isArray(labels) ? labels : [];
36
+ }
37
+ /**
38
+ * One GET on the mailbox's Gmail API, as JSON. It fails with the connection's own failure, or a
39
+ * {@link GmailError} that keeps Gmail's explanation of a refusal, for operators' diagnostics.
40
+ */
41
+ function readGmail(transport, connection, operation, path) {
42
+ return transport
43
+ .request({ connection, api: "gmail", method: "GET", path, headers: [], body: new Uint8Array() })
44
+ .pipe(Effect.flatMap((reply) => reply.status >= 300
45
+ ? Effect.fail(new GmailError(operation, reply.status, gmailExplanation(reply)))
46
+ : Effect.succeed(parse(reply.body) ?? {})));
47
+ }
48
+ /**
49
+ * Whom a reply to all in a Gmail thread goes to, as the email channel's agent replies to all: the
50
+ * thread's latest mail, a draft never, answered to its sender and copying the other people of its
51
+ * `To` and `Cc`, without the mailbox's own address, which its profile names. A reply under the
52
+ * mailbox's own latest message goes to whom that message went to. It reads the thread and the
53
+ * profile and sends nothing: a failure is refused before anything is reserved or sent.
54
+ */
55
+ export function emailThreadRecipients(input) {
56
+ return Effect.gen(function* () {
57
+ // The rejection the caller sees is sanitized; its cause keeps the original failure.
58
+ const unread = (cause) => new ActionRejected({
59
+ message: "The mail thread could not be read, so whom to answer is unknown. Nothing was sent.",
60
+ cause,
61
+ });
62
+ if (!GMAIL_ID.test(input.threadId)) {
63
+ return yield* unread(new Error("The chat names no Gmail thread."));
64
+ }
65
+ const read = (operation, path) => readGmail(input.transport, input.connection, operation, path).pipe(Effect.mapError(unread));
66
+ const profile = yield* read("profile", "/users/me/profile");
67
+ const thread = yield* read("threads.get", `/users/me/threads/${input.threadId}?format=metadata&fields=messages(labelIds,payload/headers)`);
68
+ const own = profile.emailAddress;
69
+ const messages = thread.messages;
70
+ if (typeof own !== "string" || !Array.isArray(messages)) {
71
+ return yield* unread(new Error("Gmail answered without the mailbox's address or messages."));
72
+ }
73
+ const received = messages.filter((message) => !labelsOf(message).includes("DRAFT"));
74
+ const headers = headersOf(received.at(-1));
75
+ const recipients = replyAllRecipients({ from: headers.get("from"), to: headers.get("to"), cc: headers.get("cc") }, [own]);
76
+ return recipients === undefined
77
+ ? yield* new ActionRejected({
78
+ message: "The thread's latest mail names no one to answer. Nothing was sent.",
79
+ })
80
+ : { ...recipients, thread: threadHeaders(received) };
81
+ });
82
+ }
83
+ /** The thread's subject, from its first message, and the ids of the last one a reply answers. */
84
+ function threadHeaders(received) {
85
+ const first = headersOf(received[0]);
86
+ const last = headersOf(received.at(-1));
87
+ return {
88
+ subject: first.get("subject") ?? null,
89
+ inReplyTo: last.get("message-id") ?? null,
90
+ references: last.get("references") ?? null,
91
+ };
92
+ }
93
+ /**
94
+ * The mailbox's own signature, read through the connection and kept a while per mailbox, as the
95
+ * agent's replies read it; `undefined` when it has none or Gmail refused the read, which is logged
96
+ * and sends the reply unsigned rather than not at all.
97
+ */
98
+ function signatureOf(input) {
99
+ return Effect.tryPromise({
100
+ try: () => mailboxSignature({
101
+ mailbox: input.connection,
102
+ request: (call) => Effect.runPromise(input.transport.request({ connection: input.connection, ...call })),
103
+ }),
104
+ // The original failure, Gmail's explanation or the connection's, with its causes and stack.
105
+ catch: (cause) => cause,
106
+ }).pipe(Effect.catch((cause) => Effect.logWarning("ontology.chat.email_signature_unavailable").pipe(Effect.annotateLogs({ error: describeChatError(cause, (text) => text) }), Effect.as(undefined))));
107
+ }
29
108
  /**
30
109
  * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
31
110
  * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
@@ -34,8 +113,9 @@ function headersOf(message) {
34
113
  * with the thread id, never retried. A reply sends no attribution and names no sender, so it
35
114
  * leaves from the mailbox's own address. It carries `Auto-Submitted: auto-replied` and
36
115
  * `X-SegmentStream-Reply: review-<review id>`, as the email channel's replies carry their own
37
- * keys. Files go after the text in the same message, uploaded in chunks when one request cannot
38
- * carry it (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
116
+ * keys; a post into the inbox's chat carries `post-<its operation>` instead. Files go after the
117
+ * text in the same message, uploaded in chunks when one request cannot carry it
118
+ * (`sendGmailMessage`). `sent` means Gmail accepted it; the payload keeps whom it went to.
39
119
  */
40
120
  export function sendEmail(input) {
41
121
  return Effect.gen(function* () {
@@ -50,42 +130,54 @@ export function sendEmail(input) {
50
130
  if (threadId === null || !GMAIL_ID.test(threadId)) {
51
131
  return failed(new Error("An email reply needs the Gmail thread it answers."));
52
132
  }
53
- const thread = yield* input.transport
54
- .request({
55
- connection: input.connection,
56
- api: "gmail",
57
- method: "GET",
58
- // Every header of every message, without bodies. The connection proxy refuses a
59
- // repeated query parameter, so the headers are not named one `metadataHeaders` each.
60
- path: `/users/me/threads/${threadId}?format=metadata&fields=messages(payload/headers)`,
61
- headers: [],
62
- body: new Uint8Array(),
63
- })
64
- .pipe(Effect.exit);
133
+ // The headers read with the reply's people, or else the thread as it is now.
134
+ const thread = input.thread !== undefined
135
+ ? undefined
136
+ : yield* input.transport
137
+ .request({
138
+ connection: input.connection,
139
+ api: "gmail",
140
+ method: "GET",
141
+ // Every header of every message, without bodies. The connection proxy refuses a
142
+ // repeated query parameter, so the headers are not named one `metadataHeaders` each.
143
+ path: `/users/me/threads/${threadId}?format=metadata&fields=messages(labelIds,payload/headers)`,
144
+ headers: [],
145
+ body: new Uint8Array(),
146
+ })
147
+ .pipe(Effect.exit);
65
148
  // Reading the thread sends nothing: any failure here is definite.
66
- if (thread._tag === "Failure" || thread.value.status >= 300) {
149
+ if (thread !== undefined && (thread._tag === "Failure" || thread.value.status >= 300)) {
67
150
  return failed(thread._tag === "Failure"
68
151
  ? thread.cause
69
152
  : new Error(`Gmail answered the thread read with status ${thread.value.status}.`));
70
153
  }
71
- const messages = record(parse(thread.value.body)).messages;
72
- const list = Array.isArray(messages) ? messages : [];
73
- const first = headersOf(list[0]);
74
- const last = headersOf(list.at(-1));
154
+ // A draft in the thread is no mail anyone received: the reply goes under the last that is.
155
+ const answered = input.thread ??
156
+ threadHeaders((() => {
157
+ const messages = thread?._tag === "Success" ? record(parse(thread.value.body)).messages : [];
158
+ return (Array.isArray(messages) ? messages : []).filter((message) => !labelsOf(message).includes("DRAFT"));
159
+ })());
75
160
  // The agent's reply, as the email channel sends its own: marked as a program's, so no
76
- // autoresponder answers it, and named by its review, so the channel knows it for the agent's.
77
- const key = `review-${input.destination.id}`;
161
+ // autoresponder answers it, and named by its review, or by the post's own operation, so the
162
+ // channel knows it for the workspace's and never records it again as staff's mail.
163
+ const key = input.operationId !== undefined && input.operationId !== input.destination.id
164
+ ? `post-${input.operationId}`
165
+ : `review-${input.destination.id}`;
166
+ // With the channel's `signature`, the HTML ends with the mailbox's own signature.
167
+ const html = input.signature === true
168
+ ? withEmailSignature(input.finalText, yield* signatureOf(input))
169
+ : input.finalText;
78
170
  const to = input.recipients?.to ?? [input.destination.external_id];
79
171
  const cc = input.recipients?.cc ?? [];
80
172
  const files = input.files ?? [];
81
173
  const raw = emailReplyMessage({
82
174
  to,
83
175
  ...(cc.length === 0 ? {} : { cc }),
84
- subject: first.get("subject") ?? null,
85
- inReplyTo: last.get("message-id") ?? null,
86
- references: last.get("references") ?? null,
176
+ subject: answered.subject,
177
+ inReplyTo: answered.inReplyTo,
178
+ references: answered.references,
87
179
  text: input.plainText,
88
- html: input.finalText,
180
+ html,
89
181
  autoSubmitted: true,
90
182
  ...(/^[A-Za-z0-9_-]{1,128}$/.test(key) ? { replyKey: key } : {}),
91
183
  ...(files.length === 0 ? {} : { attachments: filesWithBytes(files) }),
@@ -94,7 +186,7 @@ export function sendEmail(input) {
94
186
  threadId,
95
187
  to,
96
188
  cc,
97
- html: input.finalText,
189
+ html,
98
190
  text: input.plainText,
99
191
  ...(files.length === 0 ? {} : { files: files.map((file) => file.filename) }),
100
192
  };
@@ -170,8 +262,8 @@ export function sendEmail(input) {
170
262
  });
171
263
  }
172
264
  /**
173
- * Email through a connected mailbox. It only sends replies the agent held for review, in the
174
- * person's thread: an exact chat post never goes to an inbox.
265
+ * Email through a connected mailbox. It sends replies the agent held for review and staff's replies
266
+ * from the inbox, in the chat's thread: no chat post or tool reaches a mailbox otherwise.
175
267
  */
176
268
  export const emailProvider = {
177
269
  provider: "email",
@@ -187,4 +279,5 @@ export const emailProvider = {
187
279
  // The files go in the reply's one message, under the bound every email sender keeps.
188
280
  files: { count: AGENT_DRAFT_FILES_LIMIT, bytes: EMAIL_FILES_BYTES },
189
281
  send: sendEmail,
282
+ threadRecipients: emailThreadRecipients,
190
283
  };
@@ -6,6 +6,12 @@ import { ConnectionError, type ConnectionReply, type ConnectionTransport } from
6
6
  import type { ActionRejected } from "../../../errors.js";
7
7
  import type { Destination } from "../resolve.js";
8
8
  import type { ResolvedTemplate, StoredFileLink, StoredFileReference, TemplateRequest } from "./whatsapp-template.js";
9
+ /** What a reply in a mail thread answers: the thread's subject and its latest mail's ids. */
10
+ export interface ThreadHeaders {
11
+ readonly subject: string | null;
12
+ readonly inReplyTo: string | null;
13
+ readonly references: string | null;
14
+ }
9
15
  /** One delivery attempt's result. A `failed` attempt definitely sent nothing; `uncertain` may have. */
10
16
  export interface ProviderOutcome {
11
17
  /** The text and its format as the provider received them, for the delivery's history. */
@@ -115,6 +121,13 @@ export interface ChatSend {
115
121
  readonly to: ReadonlyArray<string>;
116
122
  readonly cc: ReadonlyArray<string>;
117
123
  };
124
+ /**
125
+ * The thread's headers a reply to mail answers, read with its `recipients` from one snapshot of
126
+ * the thread; without them the provider reads the thread itself. Others ignore them.
127
+ */
128
+ readonly thread?: ThreadHeaders;
129
+ /** Whether a reply to mail ends with the mailbox's own signature; others ignore it. */
130
+ readonly signature?: boolean;
118
131
  }
119
132
  /**
120
133
  * A channel the platform posts exact chat messages to. Each provider names its own ids, renders
@@ -128,7 +141,8 @@ export interface ChatProvider {
128
141
  readonly limit: number;
129
142
  /**
130
143
  * Whether exact chat posts and the chat tools reach the provider's chats. `false` for one that
131
- * only sends replies the agent held for review, such as email. Omitted, it is `true`.
144
+ * only sends replies the agent held for review and staff's replies in the inbox, such as email.
145
+ * Omitted, it is `true`.
132
146
  */
133
147
  readonly posts?: boolean;
134
148
  /**
@@ -173,6 +187,21 @@ export interface ChatProvider {
173
187
  }>) => ChatFilesRefusal | undefined;
174
188
  /** One attempt: `sent` only when the provider's answer proves it. */
175
189
  readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
190
+ /**
191
+ * Whom a reply in a thread several people share goes to, read from the provider before anything
192
+ * is reserved or sent, for a provider whose chat can be such a thread, such as a mailbox's: the
193
+ * people of the thread's latest message, as a reply to all.
194
+ */
195
+ readonly threadRecipients?: (input: {
196
+ readonly transport: ConnectionTransport["Service"];
197
+ readonly connection: string;
198
+ readonly threadId: string;
199
+ }) => Effect.Effect<{
200
+ readonly to: ReadonlyArray<string>;
201
+ readonly cc: ReadonlyArray<string>;
202
+ /** The headers of the same snapshot of the thread, which the reply answers. */
203
+ readonly thread: ThreadHeaders;
204
+ }, ActionRejected>;
176
205
  /**
177
206
  * The provider's approved template, read and rendered before anything is sent, for a provider
178
207
  * that takes templates, such as WhatsApp; others take text alone.
@@ -6,7 +6,7 @@ import { effectiveScope } from "../../permissions.js";
6
6
  import { describeChatError } from "./diagnostics.js";
7
7
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
8
8
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
9
- import { chatRetentionDaysOf } from "../../manifest.js";
9
+ import { chatRetentionDaysOf, signsMail } from "../../manifest.js";
10
10
  import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
11
11
  import { storeDeliveryArchive } from "./store-delivery.js";
12
12
  import { readDraftFiles, refuseChatFiles } from "./draft-files.js";
@@ -468,6 +468,7 @@ export function reviewSender(input) {
468
468
  ...(sendFiles.length === 0 ? {} : { files: sendFiles }),
469
469
  ...(recipients === undefined ? {} : { recipients }),
470
470
  ...(input.agent === undefined ? {} : { agent: input.agent }),
471
+ ...(signsMail(input.ontology.manifest, providerName) ? { signature: true } : {}),
471
472
  ...(input.previews === undefined ? {} : { previews: input.previews }),
472
473
  transport: input.connections({
473
474
  identityToken: input.identityToken,
@@ -533,24 +533,28 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
533
533
  readonly files: Schema.optionalKey<Schema.Struct<{
534
534
  readonly keep: Schema.Boolean;
535
535
  }>>;
536
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
536
537
  }>>;
537
538
  readonly slack: Schema.optionalKey<Schema.Struct<{
538
539
  readonly connection: Schema.String;
539
540
  readonly files: Schema.optionalKey<Schema.Struct<{
540
541
  readonly keep: Schema.Boolean;
541
542
  }>>;
543
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
542
544
  }>>;
543
545
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
544
546
  readonly connection: Schema.String;
545
547
  readonly files: Schema.optionalKey<Schema.Struct<{
546
548
  readonly keep: Schema.Boolean;
547
549
  }>>;
550
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
548
551
  }>>;
549
552
  readonly email: Schema.optionalKey<Schema.Struct<{
550
553
  readonly connection: Schema.String;
551
554
  readonly files: Schema.optionalKey<Schema.Struct<{
552
555
  readonly keep: Schema.Boolean;
553
556
  }>>;
557
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
554
558
  }>>;
555
559
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
556
560
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
@@ -558,6 +562,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
558
562
  readonly files: Schema.optionalKey<Schema.Struct<{
559
563
  readonly keep: Schema.Boolean;
560
564
  }>>;
565
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
561
566
  }>>>;
562
567
  readonly attribution: Schema.optionalKey<Schema.Struct<{
563
568
  readonly template: Schema.optionalKey<Schema.String>;
@@ -917,24 +922,28 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
917
922
  readonly files: Schema.optionalKey<Schema.Struct<{
918
923
  readonly keep: Schema.Boolean;
919
924
  }>>;
925
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
920
926
  }>>;
921
927
  readonly slack: Schema.optionalKey<Schema.Struct<{
922
928
  readonly connection: Schema.String;
923
929
  readonly files: Schema.optionalKey<Schema.Struct<{
924
930
  readonly keep: Schema.Boolean;
925
931
  }>>;
932
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
926
933
  }>>;
927
934
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
928
935
  readonly connection: Schema.String;
929
936
  readonly files: Schema.optionalKey<Schema.Struct<{
930
937
  readonly keep: Schema.Boolean;
931
938
  }>>;
939
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
932
940
  }>>;
933
941
  readonly email: Schema.optionalKey<Schema.Struct<{
934
942
  readonly connection: Schema.String;
935
943
  readonly files: Schema.optionalKey<Schema.Struct<{
936
944
  readonly keep: Schema.Boolean;
937
945
  }>>;
946
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
938
947
  }>>;
939
948
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
940
949
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
@@ -942,6 +951,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
942
951
  readonly files: Schema.optionalKey<Schema.Struct<{
943
952
  readonly keep: Schema.Boolean;
944
953
  }>>;
954
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
945
955
  }>>>;
946
956
  readonly attribution: Schema.optionalKey<Schema.Struct<{
947
957
  readonly template: Schema.optionalKey<Schema.String>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.166.1",
3
+ "version": "0.168.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",