@segmentstream/ontology 0.105.0 → 0.106.1

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.
@@ -49,6 +49,10 @@ export const ResolveIdentityRequest = Schema.Struct({
49
49
  username: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(MAX_DISPLAY_LENGTH))),
50
50
  notice_version: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(200))),
51
51
  notice_sha256: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/))),
52
+ address_verified: Schema.optionalKey(Schema.Boolean).annotate({
53
+ description: "Whether the receiving server proved the sender's address, as DMARC does for mail. An " +
54
+ "email account is admitted only when it is.",
55
+ }),
52
56
  limits: Schema.optionalKey(Schema.Struct({
53
57
  perSender: Schema.optionalKey(Schema.Struct({
54
58
  turnsPerMinute: Schema.optionalKey(PositiveLimit),
@@ -182,12 +182,13 @@ function resolveChannelIdentity(store) {
182
182
  if (Result.isFailure(decoded)) {
183
183
  return invalidBody(requestId, schemaIssues(decoded.failure));
184
184
  }
185
- const { external_id: externalId, notice_version, notice_sha256, ...input } = decoded.success;
185
+ const { external_id: externalId, notice_version, notice_sha256, address_verified, ...input } = decoded.success;
186
186
  const resolution = yield* store.resolveIdentity({
187
187
  ...input,
188
188
  externalId,
189
189
  ...(notice_version === undefined ? {} : { noticeVersion: notice_version }),
190
190
  ...(notice_sha256 === undefined ? {} : { noticeSha256: notice_sha256 }),
191
+ ...(address_verified === undefined ? {} : { addressVerified: address_verified }),
191
192
  });
192
193
  switch (resolution.status) {
193
194
  case "existing":
@@ -0,0 +1,15 @@
1
+ import { Effect } from "effect";
2
+ import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
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. `sent` means Gmail accepted it.
9
+ */
10
+ export declare function sendEmail(input: ChatSend): Effect.Effect<ProviderOutcome>;
11
+ /**
12
+ * Email through a connected mailbox. It only sends replies the agent held for review, in the
13
+ * person's thread: an exact chat post never goes to an inbox.
14
+ */
15
+ export declare const emailProvider: ChatProvider;
@@ -0,0 +1,133 @@
1
+ import { Effect } from "effect";
2
+ import { base64Url, EMAIL_MESSAGE_LIMIT, emailReplyMessage, renderEmailHtml, } from "../../../email.js";
3
+ import { EMAIL_PATTERN } from "../../../property.js";
4
+ import { record, transportFailure, } from "./provider.js";
5
+ /** A Gmail id, of a thread or a message. */
6
+ const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
7
+ const decoder = new TextDecoder();
8
+ function parse(body) {
9
+ try {
10
+ return record(JSON.parse(decoder.decode(body)));
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ }
16
+ /** The headers of a thread's message, by lower-case name; the first of each wins. */
17
+ function headersOf(message) {
18
+ const headers = record(record(message).payload).headers;
19
+ const found = new Map();
20
+ for (const header of Array.isArray(headers) ? headers : []) {
21
+ const { name, value } = record(header);
22
+ if (typeof name === "string" && typeof value === "string" && !found.has(name.toLowerCase())) {
23
+ found.set(name.toLowerCase(), value);
24
+ }
25
+ }
26
+ return found;
27
+ }
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. `sent` means Gmail accepted it.
34
+ */
35
+ export function sendEmail(input) {
36
+ return Effect.gen(function* () {
37
+ const threadId = input.threadId ?? null;
38
+ const failed = (cause, payload = {}) => ({
39
+ payload,
40
+ status: "failed",
41
+ messageId: null,
42
+ url: null,
43
+ cause,
44
+ });
45
+ if (threadId === null || !GMAIL_ID.test(threadId)) {
46
+ return failed(new Error("An email reply needs the Gmail thread it answers."));
47
+ }
48
+ const thread = yield* input.transport
49
+ .request({
50
+ connection: input.connection,
51
+ api: "gmail",
52
+ method: "GET",
53
+ // Every header of every message, without bodies. The connection proxy refuses a
54
+ // repeated query parameter, so the headers are not named one `metadataHeaders` each.
55
+ path: `/users/me/threads/${threadId}?format=metadata&fields=messages(payload/headers)`,
56
+ headers: [],
57
+ body: new Uint8Array(),
58
+ })
59
+ .pipe(Effect.exit);
60
+ // Reading the thread sends nothing: any failure here is definite.
61
+ if (thread._tag === "Failure" || thread.value.status >= 300) {
62
+ return failed(thread._tag === "Failure"
63
+ ? thread.cause
64
+ : new Error(`Gmail answered the thread read with status ${thread.value.status}.`));
65
+ }
66
+ const messages = record(parse(thread.value.body)).messages;
67
+ const list = Array.isArray(messages) ? messages : [];
68
+ const first = headersOf(list[0]);
69
+ const last = headersOf(list.at(-1));
70
+ const raw = emailReplyMessage({
71
+ to: input.destination.external_id,
72
+ subject: first.get("subject") ?? null,
73
+ inReplyTo: last.get("message-id") ?? null,
74
+ references: last.get("references") ?? null,
75
+ text: input.plainText,
76
+ html: input.finalText,
77
+ });
78
+ const payload = { threadId, html: input.finalText, text: input.plainText };
79
+ const result = yield* input.transport
80
+ .request({
81
+ connection: input.connection,
82
+ api: "gmail",
83
+ method: "POST",
84
+ path: "/users/me/messages/send",
85
+ headers: [["content-type", "application/json"]],
86
+ body: new TextEncoder().encode(JSON.stringify({ raw: base64Url(raw), threadId })),
87
+ })
88
+ .pipe(Effect.exit);
89
+ if (result._tag === "Failure") {
90
+ return transportFailure(payload, result);
91
+ }
92
+ const { status } = result.value;
93
+ if (status >= 500 || status === 408 || status === 429) {
94
+ return {
95
+ payload,
96
+ status: "uncertain",
97
+ messageId: null,
98
+ url: null,
99
+ cause: new Error(`Gmail answered with status ${status}.`),
100
+ };
101
+ }
102
+ if (status >= 300) {
103
+ return failed(new Error(`Gmail refused the reply with status ${status}.`), payload);
104
+ }
105
+ const id = parse(result.value.body)?.id;
106
+ return typeof id === "string" && GMAIL_ID.test(id)
107
+ ? { payload, status: "sent", messageId: id, url: null }
108
+ : {
109
+ payload,
110
+ status: "uncertain",
111
+ messageId: null,
112
+ url: null,
113
+ cause: new Error("Gmail accepted the reply without its id."),
114
+ };
115
+ });
116
+ }
117
+ /**
118
+ * Email through a connected mailbox. It only sends replies the agent held for review, in the
119
+ * person's thread: an exact chat post never goes to an inbox.
120
+ */
121
+ export const emailProvider = {
122
+ provider: "email",
123
+ limit: EMAIL_MESSAGE_LIMIT,
124
+ posts: false,
125
+ isTargetId: (externalId, kind) => kind === "private" && EMAIL_PATTERN.test(externalId),
126
+ isReplyId: () => false,
127
+ render: (markdown, attribution, separator) => {
128
+ const text = attribution === "" ? markdown : `${markdown}${separator}${attribution}`;
129
+ return { finalText: renderEmailHtml(text), plainText: text };
130
+ },
131
+ payload: (finalText) => ({ html: finalText }),
132
+ send: sendEmail,
133
+ };
@@ -1,11 +1,15 @@
1
1
  import type { OntologyManifest } from "../../../manifest.js";
2
2
  import type { ChatProvider } from "./provider.js";
3
3
  export type { ChatProvider, ChatSend, ProviderOutcome } from "./provider.js";
4
- /** Every provider the platform posts exact chat messages to, by the name the `chat` config uses. */
4
+ /**
5
+ * Every provider the platform sends to, by the name the `chat` config uses: exact chat posts and
6
+ * reviewed replies, or, for one whose `posts` is `false`, reviewed replies only.
7
+ */
5
8
  export declare const CHAT_PROVIDERS: {
6
9
  readonly telegram: ChatProvider;
7
10
  readonly slack: ChatProvider;
8
11
  readonly whatsapp: ChatProvider;
12
+ readonly email: ChatProvider;
9
13
  };
10
14
  export type ChatProviderName = keyof typeof CHAT_PROVIDERS;
11
15
  /** The provider a destination's chat is on, when the platform posts to it. */
@@ -1,11 +1,16 @@
1
+ import { emailProvider } from "./email.js";
1
2
  import { slackProvider } from "./slack.js";
2
3
  import { telegramProvider } from "./telegram.js";
3
4
  import { whatsappProvider } from "./whatsapp.js";
4
- /** Every provider the platform posts exact chat messages to, by the name the `chat` config uses. */
5
+ /**
6
+ * Every provider the platform sends to, by the name the `chat` config uses: exact chat posts and
7
+ * reviewed replies, or, for one whose `posts` is `false`, reviewed replies only.
8
+ */
5
9
  export const CHAT_PROVIDERS = {
6
10
  telegram: telegramProvider,
7
11
  slack: slackProvider,
8
12
  whatsapp: whatsappProvider,
13
+ email: emailProvider,
9
14
  };
10
15
  const NAMES = Object.keys(CHAT_PROVIDERS);
11
16
  const isChatProvider = (name) => Object.hasOwn(CHAT_PROVIDERS, name);
@@ -19,7 +24,7 @@ export function chatConnection(chat, provider) {
19
24
  }
20
25
  /** The providers the ontology declares a posting connection for: the destinations it posts to. */
21
26
  export function declaredChatProviders(chat) {
22
- return NAMES.filter((name) => chat?.[name] !== undefined);
27
+ return NAMES.filter((name) => chat?.[name] !== undefined && CHAT_PROVIDERS[name].posts !== false);
23
28
  }
24
29
  /**
25
30
  * The providers whose chats the chat tools list, read and resolve: Telegram's, whose chats the
@@ -38,6 +38,11 @@ export interface ChatProvider {
38
38
  readonly provider: string;
39
39
  /** The most characters the provider accepts in one message, for the rendered and plain text. */
40
40
  readonly limit: number;
41
+ /**
42
+ * Whether exact chat posts and the chat tools reach the provider's chats. `false` for one that
43
+ * only sends replies the agent held for review, such as email. Omitted, it is `true`.
44
+ */
45
+ readonly posts?: boolean;
41
46
  /** Whether an id names a chat of this kind on the provider. */
42
47
  readonly isTargetId: (externalId: string, kind: Destination["kind"]) => boolean;
43
48
  /** Whether an id names a message on the provider that a post may reply to. */
@@ -314,6 +314,11 @@ export interface ResolveIdentityInput {
314
314
  readonly username?: string;
315
315
  readonly noticeVersion?: string;
316
316
  readonly noticeSha256?: string;
317
+ /**
318
+ * Whether the receiving server proved the sender's address, as DMARC with alignment does for
319
+ * mail. An `email` account is admitted, created or linked only when it is.
320
+ */
321
+ readonly addressVerified?: boolean;
317
322
  readonly limits?: {
318
323
  readonly perSender?: Partial<AgentLimits["perSender"]>;
319
324
  readonly newUsersPerHour?: number;
@@ -465,6 +465,9 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
465
465
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
466
466
  readonly connection: Schema.String;
467
467
  }>>;
468
+ readonly email: Schema.optionalKey<Schema.Struct<{
469
+ readonly connection: Schema.String;
470
+ }>>;
468
471
  readonly attribution: Schema.optionalKey<Schema.Struct<{
469
472
  readonly template: Schema.optionalKey<Schema.String>;
470
473
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -738,6 +741,9 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
738
741
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
739
742
  readonly connection: Schema.String;
740
743
  }>>;
744
+ readonly email: Schema.optionalKey<Schema.Struct<{
745
+ readonly connection: Schema.String;
746
+ }>>;
741
747
  readonly attribution: Schema.optionalKey<Schema.Struct<{
742
748
  readonly template: Schema.optionalKey<Schema.String>;
743
749
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -6,7 +6,7 @@ export declare const ATTACHMENTS_TABLE = "_agent_attachments";
6
6
  * Where an attachment comes from: a chat message on a channel, or a file the agent produced in its
7
7
  * sandbox and stores so that an action can keep it.
8
8
  */
9
- export declare const ATTACHMENT_SOURCES: readonly ["telegram", "slack", "whatsapp", "sandbox"];
9
+ export declare const ATTACHMENT_SOURCES: readonly ["telegram", "slack", "whatsapp", "email", "sandbox"];
10
10
  /** The check that limits `source` to {@link ATTACHMENT_SOURCES}; its name is PostgreSQL's default. */
11
11
  export declare const ATTACHMENT_SOURCE_CHECK = "_agent_attachments_source_check";
12
12
  /**
@@ -59,7 +59,7 @@ export const ATTACHMENTS_TABLE = "_agent_attachments";
59
59
  * Where an attachment comes from: a chat message on a channel, or a file the agent produced in its
60
60
  * sandbox and stores so that an action can keep it.
61
61
  */
62
- export const ATTACHMENT_SOURCES = ["telegram", "slack", "whatsapp", "sandbox"];
62
+ export const ATTACHMENT_SOURCES = ["telegram", "slack", "whatsapp", "email", "sandbox"];
63
63
  /** The check that limits `source` to {@link ATTACHMENT_SOURCES}; its name is PostgreSQL's default. */
64
64
  export const ATTACHMENT_SOURCE_CHECK = `${ATTACHMENTS_TABLE}_source_check`;
65
65
  const SOURCE_CHECK = `CHECK ("source" IN (${ATTACHMENT_SOURCES.map((source) => `'${source}'`).join(", ")}))`;
@@ -3,9 +3,11 @@ export declare const USER_IDENTITY_ORIGINS: readonly ["invite", "sign_in", "link
3
3
  export type UserIdentityOrigin = (typeof USER_IDENTITY_ORIGINS)[number];
4
4
  /**
5
5
  * The chat providers whose accounts an administrator may attach to a member with
6
- * `user_identity.attach`: the providers the app's agent talks on.
6
+ * `user_identity.attach`: the providers the app's agent talks on. An `email` account is the
7
+ * address a member writes to the agent's mailbox from, which the agent never links to a member
8
+ * by itself.
7
9
  */
8
- export declare const ATTACHABLE_IDENTITY_PROVIDERS: readonly ["telegram", "whatsapp", "slack"];
10
+ export declare const ATTACHABLE_IDENTITY_PROVIDERS: readonly ["telegram", "whatsapp", "slack", "email"];
9
11
  export type AttachableIdentityProvider = (typeof ATTACHABLE_IDENTITY_PROVIDERS)[number];
10
12
  /**
11
13
  * The built-in record of every external account a member signs in or talks with: their Neon Auth
@@ -12,9 +12,11 @@ export const USER_IDENTITY_ORIGINS = [
12
12
  ];
13
13
  /**
14
14
  * The chat providers whose accounts an administrator may attach to a member with
15
- * `user_identity.attach`: the providers the app's agent talks on.
15
+ * `user_identity.attach`: the providers the app's agent talks on. An `email` account is the
16
+ * address a member writes to the agent's mailbox from, which the agent never links to a member
17
+ * by itself.
16
18
  */
17
- export const ATTACHABLE_IDENTITY_PROVIDERS = ["telegram", "whatsapp", "slack"];
19
+ export const ATTACHABLE_IDENTITY_PROVIDERS = ["telegram", "whatsapp", "slack", "email"];
18
20
  /**
19
21
  * The built-in record of every external account a member signs in or talks with: their Neon Auth
20
22
  * account, their SegmentStream (OIDC) accounts and their channel accounts, such as Telegram. Every