@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.168.0
4
+
5
+ A mailbox in `chat` takes `signature: true` beside its connection: the ontology's replies to mail,
6
+ a draft a member approves and a staff reply from the inbox, end their HTML with the mailbox's own
7
+ signature, as its owner set it in Gmail for its address. The signature is read through the
8
+ connection with `users.settings.sendAs` and kept for 10 minutes per mailbox; a reply whose
9
+ signature Gmail refuses to read goes unsigned. Off when absent; `check` refuses it on a channel
10
+ that is no mailbox.
11
+
12
+ `@segmentstream/ontology/email` exports the reader the agent shares, `mailboxSignature` (and
13
+ `mailboxSignatures` for a reader with its own clock), and `withEmailSignature`.
14
+
15
+ ## 0.167.0
16
+
17
+ Staff answer an email thread's chat (`chats: "thread"`) from the inbox. `agent_chat.postMessage`,
18
+ and `send` as the agent, into a thread's chat reply to the thread's latest mail, to everyone in it,
19
+ as the agent's reply does: to its sender, copying the other people of its `To` and `Cc` without the
20
+ mailbox's own address, or, under the mailbox's own mail, to whom that mail went; in the same
21
+ thread, with `Re:` and the thread's subject, `In-Reply-To` and `References`, from the mailbox. The
22
+ reply is read in the chat by the members among the people it went to. A thread the mailbox cannot
23
+ read is refused before anything is reserved or sent, and a replay of the key returns the first
24
+ delivery without reading the thread again. Before, such a post was refused as having no person to
25
+ answer.
26
+
27
+ A reply to mail never threads under a draft of the mailbox's: it goes under the thread's last
28
+ message anyone received. A staff reply in a person's email chat is named by its own post
29
+ (`X-SegmentStream-Reply: post-…`) rather than by the chat, as the agent's replies are named by
30
+ theirs.
31
+
3
32
  ## 0.166.1
4
33
 
5
34
  In an app preview that runs the agent, the agent's tools and recall now act for an eval session's
package/dist/analyze.d.ts CHANGED
@@ -273,6 +273,12 @@ export interface ChatChannelConfig {
273
273
  * long as the chat's messages (`retentionDays`); otherwise it expires 24 hours after it arrives.
274
274
  */
275
275
  readonly files?: ChatFilesConfig;
276
+ /**
277
+ * On a mailbox (`kind` `email`) only: whether the ontology's replies to mail, a draft a member
278
+ * approves and staff's replies from the inbox, end with the mailbox's own signature, as the
279
+ * mailbox's owner set it in Gmail. Off when absent.
280
+ */
281
+ readonly signature?: boolean;
276
282
  }
277
283
  /** `files` of a chat channel: whether its chats keep their files with their messages. */
278
284
  export interface ChatFilesConfig {
@@ -298,6 +304,8 @@ export interface ChatConfig {
298
304
  readonly email?: {
299
305
  readonly connection: AnyConnectionHandle;
300
306
  readonly files?: ChatFilesConfig;
307
+ /** Whether replies to mail end with the mailbox's own signature; see {@link ChatChannelConfig}. */
308
+ readonly signature?: boolean;
301
309
  };
302
310
  readonly attribution?: ChatAttributionSettings;
303
311
  /**
package/dist/analyze.js CHANGED
@@ -192,7 +192,10 @@ export function analyze(config, options = {}) {
192
192
  const malformed = entries.find(([name, value]) => {
193
193
  const named = !CHAT_PROVIDER_KEYS.includes(name);
194
194
  return (!isPlainObject(value) ||
195
- Object.keys(value).some((key) => key !== "connection" && key !== "kind" && key !== "files") ||
195
+ Object.keys(value).some((key) => key !== "connection" && key !== "kind" && key !== "files" && key !== "signature") ||
196
+ // Only a mailbox has a signature of its own.
197
+ (value.signature !== undefined &&
198
+ (typeof value.signature !== "boolean" || (named ? value.kind : name) !== "email")) ||
196
199
  (value.files !== undefined &&
197
200
  (!isPlainObject(value.files) ||
198
201
  Object.keys(value.files).some((key) => key !== "keep") ||
@@ -213,11 +216,14 @@ export function analyze(config, options = {}) {
213
216
  entry.connection,
214
217
  entry.kind ?? name,
215
218
  entry.files?.keep === true,
219
+ entry.signature === true,
216
220
  ];
217
221
  })
218
222
  : [];
219
223
  // Written only for a channel that keeps its files: older readers keep none.
220
224
  const keptFiles = (keep) => (keep ? { files: { keep: true } } : {});
225
+ // Written only for a mailbox that signs its replies: older readers sign none.
226
+ const signed = (signature) => (signature ? { signature: true } : {});
221
227
  const handles = channels.flatMap(([name, handle, kind]) => handle === undefined ? [] : [[name, handle, kind]]);
222
228
  const unlisted = handles.find(([, handle]) => !(config.connections ?? []).includes(handle));
223
229
  const shared = handles.find(([, handle], index) => handles.findIndex(([, other]) => other === handle) !== index);
@@ -230,7 +236,7 @@ export function analyze(config, options = {}) {
230
236
  report("invalid-connection", "chat", `chat.${malformed}.connection must reference a declared connection handle, and a ` +
231
237
  `channel not named after its kind needs kind: ${CHAT_KINDS.join(", ")}; a ` +
232
238
  `${WORKSPACE_CHANNEL_KIND} channel takes none, as the agent sends through it. ` +
233
- `files takes keep, true or false.`);
239
+ `files takes keep, true or false, and a mailbox (email) takes signature, true or false.`);
234
240
  }
235
241
  else if (unlisted !== undefined) {
236
242
  report("invalid-connection", `chat.${unlisted[0]}.connection`, "The chat channel connection must be listed in connections.");
@@ -243,16 +249,19 @@ export function analyze(config, options = {}) {
243
249
  chat = {
244
250
  ...Object.fromEntries(channels
245
251
  .filter(([name]) => CHAT_PROVIDER_KEYS.includes(name))
246
- .flatMap(([name, handle, , keep]) => handle === undefined ? [] : [[name, { connection: handle.key, ...keptFiles(keep) }]])),
252
+ .flatMap(([name, handle, , keep, signature]) => handle === undefined
253
+ ? []
254
+ : [[name, { connection: handle.key, ...keptFiles(keep), ...signed(signature) }]])),
247
255
  ...(named.length === 0
248
256
  ? {}
249
257
  : {
250
- channels: Object.fromEntries(named.map(([name, handle, kind, keep]) => [
258
+ channels: Object.fromEntries(named.map(([name, handle, kind, keep, signature]) => [
251
259
  name,
252
260
  {
253
261
  kind,
254
262
  ...(handle === undefined ? {} : { connection: handle.key }),
255
263
  ...keptFiles(keep),
264
+ ...signed(signature),
256
265
  },
257
266
  ])),
258
267
  }),
package/dist/email.d.ts CHANGED
@@ -18,6 +18,26 @@ export declare function emailRecipients(input: {
18
18
  readonly to: string | ReadonlyArray<string>;
19
19
  readonly cc?: ReadonlyArray<string>;
20
20
  }): EmailRecipients;
21
+ /**
22
+ * The plain addresses an address header lists (`To`, `Cc`, `From`), in lower case and once each:
23
+ * `Name <a@example.com>` and a bare `a@example.com` alike, a group's members for a group, and
24
+ * nothing a quoted name or a comment holds. Anything that is no plain address is left out.
25
+ */
26
+ export declare function headerAddresses(value: string | null | undefined): ReadonlyArray<string>;
27
+ /** The people of one message, as its `From`, `To` and `Cc` headers name them. */
28
+ export interface EmailParties {
29
+ readonly from: string | null | undefined;
30
+ readonly to: string | null | undefined;
31
+ readonly cc: string | null | undefined;
32
+ }
33
+ /**
34
+ * Whom a reply to all of a message goes to, as the email channel's agent replies to all: the
35
+ * message's sender in `To`, and the other addresses of its `To` and `Cc` in `Cc`, without the
36
+ * mailbox's own addresses. A reply to the mailbox's own message goes to whom that message went to,
37
+ * its `To`, and copies its `Cc`. At most {@link EMAIL_RECIPIENTS_LIMIT} together; `undefined` when
38
+ * the message names no one else.
39
+ */
40
+ export declare function replyAllRecipients(message: EmailParties, own: ReadonlyArray<string>): EmailRecipients | undefined;
21
41
  /**
22
42
  * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
23
43
  * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
@@ -28,6 +48,11 @@ export declare const EMAIL_ATTACHMENTS_LIMIT = 25000000;
28
48
  * carry no markup, image or script the platform did not render from Markdown itself.
29
49
  */
30
50
  export declare function renderEmailHtml(text: string): string;
51
+ /**
52
+ * A reply's HTML ending with the mailbox's own signature, as the mailbox's owner wrote it in their
53
+ * mail program: the platform adds no words, separator or quoted mail of its own.
54
+ */
55
+ export declare function withEmailSignature(html: string, signature: string | undefined): string;
31
56
  /** The subject a reply in a thread carries: the thread's own, prefixed `Re:` once. */
32
57
  export declare function replySubject(subject: string | null | undefined): string;
33
58
  /** A file a reply carries. */
@@ -78,4 +103,4 @@ export declare function emailReplyMessage(reply: EmailReply): string;
78
103
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
79
104
  export declare function base64Url(text: string): string;
80
105
  export type { ChannelCall, ChannelReply, ChannelRequest } from "./channel-files.js";
81
- export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, sendGmailMessage, } from "./gmail-send.js";
106
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, mailboxSignature, mailboxSignatures, MAILBOX_SIGNATURE_LIFETIME_MS, sendGmailMessage, } from "./gmail-send.js";
package/dist/email.js CHANGED
@@ -37,6 +37,98 @@ export function emailRecipients(input) {
37
37
  }
38
38
  return { to, cc };
39
39
  }
40
+ /**
41
+ * The plain addresses an address header lists (`To`, `Cc`, `From`), in lower case and once each:
42
+ * `Name <a@example.com>` and a bare `a@example.com` alike, a group's members for a group, and
43
+ * nothing a quoted name or a comment holds. Anything that is no plain address is left out.
44
+ */
45
+ export function headerAddresses(value) {
46
+ const items = [];
47
+ let current = "";
48
+ let quoted = false;
49
+ let comment = 0;
50
+ let angle = false;
51
+ for (let index = 0; index < (value ?? "").length; index++) {
52
+ const character = value[index];
53
+ if (quoted) {
54
+ if (character === "\\") {
55
+ index++;
56
+ }
57
+ else if (character === '"') {
58
+ quoted = false;
59
+ }
60
+ continue;
61
+ }
62
+ if (comment > 0) {
63
+ if (character === "\\") {
64
+ index++;
65
+ }
66
+ else if (character === "(") {
67
+ comment++;
68
+ }
69
+ else if (character === ")") {
70
+ comment--;
71
+ }
72
+ continue;
73
+ }
74
+ if (character === '"') {
75
+ quoted = true;
76
+ }
77
+ else if (character === "(") {
78
+ comment = 1;
79
+ }
80
+ else if (character === "<") {
81
+ angle = true;
82
+ // Only what the brackets hold names the address: the name before them is dropped.
83
+ current = "<";
84
+ }
85
+ else if (character === ">") {
86
+ angle = false;
87
+ current += ">";
88
+ }
89
+ else if (!angle && (character === "," || character === ";")) {
90
+ items.push(current);
91
+ current = "";
92
+ }
93
+ else if (!angle && character === ":") {
94
+ // A group's name: its members follow.
95
+ current = "";
96
+ }
97
+ else {
98
+ current += character;
99
+ }
100
+ }
101
+ items.push(current);
102
+ const addresses = items.flatMap((item) => {
103
+ const bracketed = /<([^<>]*)>/.exec(item)?.[1];
104
+ const address = (bracketed ?? item).trim().toLowerCase();
105
+ return isEmailAddress(address) ? [address] : [];
106
+ });
107
+ return [...new Set(addresses)];
108
+ }
109
+ /**
110
+ * Whom a reply to all of a message goes to, as the email channel's agent replies to all: the
111
+ * message's sender in `To`, and the other addresses of its `To` and `Cc` in `Cc`, without the
112
+ * mailbox's own addresses. A reply to the mailbox's own message goes to whom that message went to,
113
+ * its `To`, and copies its `Cc`. At most {@link EMAIL_RECIPIENTS_LIMIT} together; `undefined` when
114
+ * the message names no one else.
115
+ */
116
+ export function replyAllRecipients(message, own) {
117
+ const mailbox = new Set(own.map((address) => address.trim().toLowerCase()));
118
+ const others = (list) => list.filter((address) => !mailbox.has(address));
119
+ const from = headerAddresses(message.from)[0];
120
+ const sender = from !== undefined && !mailbox.has(from) ? from : undefined;
121
+ const to = headerAddresses(message.to);
122
+ const cc = headerAddresses(message.cc);
123
+ const primary = sender === undefined ? others(to) : [sender];
124
+ const copies = others(sender === undefined ? cc : [...to, ...cc]).filter((address) => !primary.includes(address));
125
+ // A message of the mailbox's that went to no one in `To` is answered to its first copy.
126
+ const all = [...primary, ...copies].slice(0, EMAIL_RECIPIENTS_LIMIT);
127
+ const named = Math.max(Math.min(primary.length, all.length), Math.min(all.length, 1));
128
+ return all.length === 0
129
+ ? undefined
130
+ : emailRecipients({ to: all.slice(0, named), cc: all.slice(named) });
131
+ }
40
132
  /**
41
133
  * An address header, folded so that no line runs much past 78 characters however many addresses it
42
134
  * lists: each line after the first starts with a space, as RFC 5322 folds a header.
@@ -86,6 +178,18 @@ export function renderEmailHtml(text) {
86
178
  const body = markdown.parse(text);
87
179
  return `<!doctype html><html><body>${body}</body></html>`;
88
180
  }
181
+ /**
182
+ * A reply's HTML ending with the mailbox's own signature, as the mailbox's owner wrote it in their
183
+ * mail program: the platform adds no words, separator or quoted mail of its own.
184
+ */
185
+ export function withEmailSignature(html, signature) {
186
+ if (signature === undefined || signature.trim() === "") {
187
+ return html;
188
+ }
189
+ const block = `<br><div>${signature}</div>`;
190
+ const end = html.lastIndexOf("</body>");
191
+ return end === -1 ? `${html}${block}` : `${html.slice(0, end)}${block}${html.slice(end)}`;
192
+ }
89
193
  /** The subject a reply in a thread carries: the thread's own, prefixed `Re:` once. */
90
194
  export function replySubject(subject) {
91
195
  const flat = (subject ?? "").replace(/[\r\n]+/g, " ").trim();
@@ -210,4 +314,4 @@ export function emailReplyMessage(reply) {
210
314
  export function base64Url(text) {
211
315
  return Buffer.from(text, "utf8").toString("base64url");
212
316
  }
213
- export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, sendGmailMessage, } from "./gmail-send.js";
317
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, mailboxSignature, mailboxSignatures, MAILBOX_SIGNATURE_LIFETIME_MS, sendGmailMessage, } from "./gmail-send.js";
@@ -47,3 +47,23 @@ export declare function sendGmailMessage(options: {
47
47
  readonly message: Uint8Array;
48
48
  readonly threadId: string;
49
49
  }): Promise<Record<string, unknown>>;
50
+ /** How long a mailbox's signature is kept before it is read from Gmail again. */
51
+ export declare const MAILBOX_SIGNATURE_LIFETIME_MS: number;
52
+ /**
53
+ * A reader of mailboxes' own signatures, each kept for {@link MAILBOX_SIGNATURE_LIFETIME_MS} by its
54
+ * `mailbox` key, such as the connection's name. It reads the mailbox's send-as addresses
55
+ * (`users.settings.sendAs.list`, which `gmail.readonly` and `gmail.settings.basic` both cover) and
56
+ * resolves the signature of its own address, the primary one replies leave from, or `undefined`
57
+ * when it has none. Throws {@link GmailError} when Gmail refuses the read; a failed read is not kept.
58
+ */
59
+ export declare function mailboxSignatures(options?: {
60
+ readonly now?: () => number;
61
+ }): (input: {
62
+ readonly request: ChannelRequest;
63
+ readonly mailbox: string;
64
+ }) => Promise<string | undefined>;
65
+ /** The process's reader of mailboxes' signatures, which the agent's and the ontology's mail share. */
66
+ export declare const mailboxSignature: (input: {
67
+ readonly request: ChannelRequest;
68
+ readonly mailbox: string;
69
+ }) => Promise<string | undefined>;
@@ -199,3 +199,48 @@ export async function sendGmailMessage(options) {
199
199
  offset = held === undefined ? 0 : Number(held) + 1;
200
200
  }
201
201
  }
202
+ /** How long a mailbox's signature is kept before it is read from Gmail again. */
203
+ export const MAILBOX_SIGNATURE_LIFETIME_MS = 10 * 60 * 1000;
204
+ /** How many mailboxes' signatures one process keeps; the oldest read is forgotten first. */
205
+ const MAILBOX_SIGNATURES_KEPT = 100;
206
+ /**
207
+ * A reader of mailboxes' own signatures, each kept for {@link MAILBOX_SIGNATURE_LIFETIME_MS} by its
208
+ * `mailbox` key, such as the connection's name. It reads the mailbox's send-as addresses
209
+ * (`users.settings.sendAs.list`, which `gmail.readonly` and `gmail.settings.basic` both cover) and
210
+ * resolves the signature of its own address, the primary one replies leave from, or `undefined`
211
+ * when it has none. Throws {@link GmailError} when Gmail refuses the read; a failed read is not kept.
212
+ */
213
+ export function mailboxSignatures(options = {}) {
214
+ const now = options.now ?? Date.now;
215
+ const kept = new Map();
216
+ return async (input) => {
217
+ const found = kept.get(input.mailbox);
218
+ if (found !== undefined && found.until > now()) {
219
+ return found.signature;
220
+ }
221
+ const reply = await input.request({
222
+ api: "gmail",
223
+ method: "GET",
224
+ path: "/users/me/settings/sendAs",
225
+ headers: [],
226
+ body: new Uint8Array(),
227
+ });
228
+ if (reply.status < 200 || reply.status >= 300) {
229
+ throw new GmailError("settings.sendAs.list", reply.status, gmailExplanation(reply));
230
+ }
231
+ const addresses = gmailJson(reply).sendAs;
232
+ const own = (Array.isArray(addresses) ? addresses : []).find((address) => address?.isPrimary === true);
233
+ const signature = typeof own?.signature === "string" && own.signature.trim() !== "" ? own.signature : undefined;
234
+ kept.delete(input.mailbox);
235
+ kept.set(input.mailbox, { signature, until: now() + MAILBOX_SIGNATURE_LIFETIME_MS });
236
+ for (const mailbox of kept.keys()) {
237
+ if (kept.size <= MAILBOX_SIGNATURES_KEPT) {
238
+ break;
239
+ }
240
+ kept.delete(mailbox);
241
+ }
242
+ return signature;
243
+ };
244
+ }
245
+ /** The process's reader of mailboxes' signatures, which the agent's and the ontology's mail share. */
246
+ export const mailboxSignature = mailboxSignatures();