@segmentstream/ontology 0.175.0 → 0.176.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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.176.0
4
+
5
+ The ontology's replies to mail, a draft a member approves and a staff reply from the inbox, are
6
+ handed to the agent's email channel of the chat's name, which sends them as its own replies: in the
7
+ thread, from the mailbox, keyed so a lost answer is never sent twice, and signed and quoted by the
8
+ channel's `signature` and `quote`, so every reply from the mailbox looks the same. The reply's files
9
+ go by short-lived links to the workspace's file storage, checked against the revision the draft
10
+ holds before anything is reserved; the channel refuses a file whose size differs and sends nothing.
11
+ The channel serves this at `POST /eve/segmentstream/v1/email/<name>/deliver`, for the deployment's
12
+ own functions only.
13
+
14
+ An agent from before the route answers 404, and the ontology sends the reply from the mailbox
15
+ itself, as before: signed by `signature` on its `chat` entry and never quoted.
16
+
17
+ Action required: upgrade `@segmentstream/agent` together with `@segmentstream/ontology`, and set
18
+ `signature` (and `quote`, if wanted) on `channels.email` in `agent/segmentstream.json`. The
19
+ ontology's `chat.email.signature` now signs only replies sent for an agent from before the route; it
20
+ is deprecated and stops working on 2027-05-27.
21
+
3
22
  ## 0.175.0
4
23
 
5
24
  Allow workspace operators to enable bounded, tool-free answers to unlinked senders in individual Telegram and Slack group chats. Dedicated connections can use a verified inviter's existing permission to open a newly joined group.
package/dist/email.d.ts CHANGED
@@ -95,6 +95,40 @@ export interface EmailReply {
95
95
  }
96
96
  /** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
97
97
  export declare const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
98
+ /** A reply's key, as {@link EmailReply.replyKey} takes it. */
99
+ export declare const REPLY_KEY: RegExp;
100
+ /**
101
+ * Where the agent's email channel `name` delivers a reply the ontology sends from its mailbox: a
102
+ * draft a member approved or a staff reply from the inbox. The agent renders and sends it as its
103
+ * own replies, with the mailbox's signature and quote, and only the deployment's own functions may
104
+ * call it.
105
+ */
106
+ export declare function emailDeliverRoute(name: string): string;
107
+ /** One reply for the agent's email channel to send in a thread (`POST` {@link emailDeliverRoute}). */
108
+ export interface EmailDeliver {
109
+ readonly thread_id: string;
110
+ /** Whom the reply goes to, and copies; plain addresses. */
111
+ readonly to: ReadonlyArray<string>;
112
+ readonly cc: ReadonlyArray<string>;
113
+ /** The exact reply, Markdown with the attribution the ontology added. */
114
+ readonly text: string;
115
+ /** The reply's key (`X-SegmentStream-Reply`), so a send after a lost answer is found, not repeated. */
116
+ readonly key: string;
117
+ /** The reply's files, each by a short-lived link to the workspace's file storage. */
118
+ readonly files?: ReadonlyArray<{
119
+ readonly filename: string;
120
+ readonly content_type: string;
121
+ readonly size: number;
122
+ readonly url: string;
123
+ }>;
124
+ }
125
+ /**
126
+ * The agent's answer: `200 { message_id }` once Gmail took the reply. A `4xx` with `{ error }` sent
127
+ * nothing (`404` alone: an agent without the route); anything else may have sent it.
128
+ */
129
+ export interface EmailDelivered {
130
+ readonly message_id: string | null;
131
+ }
98
132
  /**
99
133
  * The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
100
134
  * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
package/dist/email.js CHANGED
@@ -235,6 +235,17 @@ function fileNameParameter(parameter, filename) {
235
235
  }
236
236
  /** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
237
237
  export const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
238
+ /** A reply's key, as {@link EmailReply.replyKey} takes it. */
239
+ export const REPLY_KEY = /^[A-Za-z0-9_-]{1,128}$/;
240
+ /**
241
+ * Where the agent's email channel `name` delivers a reply the ontology sends from its mailbox: a
242
+ * draft a member approved or a staff reply from the inbox. The agent renders and sends it as its
243
+ * own replies, with the mailbox's signature and quote, and only the deployment's own functions may
244
+ * call it.
245
+ */
246
+ export function emailDeliverRoute(name) {
247
+ return `/eve/segmentstream/v1/email/${name}/deliver`;
248
+ }
238
249
  /**
239
250
  * The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
240
251
  * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
@@ -159,6 +159,9 @@ export function readDraftFiles(input) {
159
159
  contentType: file.contentType,
160
160
  size: file.size,
161
161
  bytes,
162
+ // The bytes are checked against the revision before anything is reserved; a provider that
163
+ // has another sender read them, as mail through the agent's channel, grants it a link.
164
+ link: () => Effect.runPromise(blobs.download(file.entity, file.id, file.property, { revisionId: file.revisionId }, member.principal)).then(({ url }) => url),
162
165
  });
163
166
  }
164
167
  return read;
@@ -1,6 +1,6 @@
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, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
3
+ import { base64Url, emailDeliverRoute, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
4
4
  import { mailboxSignature } from "../../../gmail-send.js";
5
5
  import { ActionRejected } from "../../../errors.js";
6
6
  import { EMAIL_PATTERN } from "../../../property.js";
@@ -105,6 +105,97 @@ function signatureOf(input) {
105
105
  catch: (cause) => cause,
106
106
  }).pipe(Effect.catch((cause) => Effect.logWarning("ontology.chat.email_signature_unavailable").pipe(Effect.annotateLogs({ error: describeChatError(cause, (text) => text) }), Effect.as(undefined))));
107
107
  }
108
+ /** How long the agent's email channel has to send one reply, files uploaded in chunks included. */
109
+ const AGENT_DELIVER_TIMEOUT_MS = 90_000;
110
+ /**
111
+ * One reply through the agent's email channel (`POST` {@link emailDeliverRoute} on the
112
+ * deployment's production origin, with the service's Vercel OIDC token), never retried: the agent
113
+ * renders it as its own replies, with the mailbox's signature and quote, reads each file by its
114
+ * link and sends it in the thread. Undefined when the agent has no such route (`404`), so the
115
+ * ontology sends it itself. The agent's other `4xx` sent nothing; a timeout, a `5xx` or an answer
116
+ * without its shape may have, and is uncertain.
117
+ */
118
+ function deliverThroughAgent(input, reply) {
119
+ return Effect.gen(function* () {
120
+ const agent = input.agent;
121
+ const payload = {
122
+ threadId: reply.threadId,
123
+ to: reply.to,
124
+ cc: reply.cc,
125
+ text: input.plainText,
126
+ ...(reply.files.length === 0 ? {} : { files: reply.files.map((file) => file.filename) }),
127
+ };
128
+ const failed = (cause) => ({
129
+ payload,
130
+ status: "failed",
131
+ messageId: null,
132
+ url: null,
133
+ cause,
134
+ });
135
+ // Each link is granted just before the reply goes, as the person may still read its file.
136
+ const links = yield* Effect.tryPromise(() => Promise.all(reply.files.map(async (file) => {
137
+ if (file.link === undefined) {
138
+ throw new Error("A file of the reply has no link to read it by.");
139
+ }
140
+ return {
141
+ filename: file.filename,
142
+ content_type: file.contentType,
143
+ size: file.size,
144
+ url: await file.link(),
145
+ };
146
+ }))).pipe(Effect.exit);
147
+ if (links._tag === "Failure") {
148
+ return failed(links.cause);
149
+ }
150
+ const body = {
151
+ thread_id: reply.threadId,
152
+ to: reply.to,
153
+ cc: reply.cc,
154
+ text: input.plainText,
155
+ key: reply.key,
156
+ ...(links.value.length === 0 ? {} : { files: links.value }),
157
+ };
158
+ const answered = yield* Effect.tryPromise(async () => {
159
+ const response = await agent.fetch(new Request(new URL(emailDeliverRoute(input.destination.provider), agent.origin), {
160
+ method: "POST",
161
+ headers: {
162
+ authorization: `Bearer ${agent.identityToken}`,
163
+ "content-type": "application/json",
164
+ },
165
+ body: JSON.stringify(body),
166
+ signal: AbortSignal.timeout(AGENT_DELIVER_TIMEOUT_MS),
167
+ }));
168
+ return { status: response.status, text: await response.text() };
169
+ }).pipe(Effect.exit);
170
+ if (answered._tag === "Failure") {
171
+ return { payload, status: "uncertain", messageId: null, url: null, cause: answered.cause };
172
+ }
173
+ const { status, text } = answered.value;
174
+ if (status === 404) {
175
+ return undefined;
176
+ }
177
+ let answer = {};
178
+ try {
179
+ answer = record(JSON.parse(text));
180
+ }
181
+ catch {
182
+ // The status still says what happened; the body only adds the message's id.
183
+ }
184
+ if (status >= 400 && status < 500) {
185
+ return failed(new Error(`The agent's email channel refused the reply (${typeof answer.error === "string" ? answer.error : `status ${status}`}).`));
186
+ }
187
+ const id = answer.message_id;
188
+ return status >= 200 && status < 300 && typeof id === "string" && GMAIL_ID.test(id)
189
+ ? { payload, status: "sent", messageId: id, url: null }
190
+ : {
191
+ payload,
192
+ status: "uncertain",
193
+ messageId: null,
194
+ url: null,
195
+ cause: new Error(`The agent's email channel answered with status ${status}.`),
196
+ };
197
+ });
198
+ }
108
199
  /**
109
200
  * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
110
201
  * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
@@ -130,6 +221,33 @@ export function sendEmail(input) {
130
221
  if (threadId === null || !GMAIL_ID.test(threadId)) {
131
222
  return failed(new Error("An email reply needs the Gmail thread it answers."));
132
223
  }
224
+ // The agent's reply, as the email channel sends its own: marked as a program's, so no
225
+ // autoresponder answers it, and named by its review, or by the post's own operation, so the
226
+ // channel knows it for the workspace's and never records it again as staff's mail.
227
+ const key = input.operationId !== undefined && input.operationId !== input.destination.id
228
+ ? `post-${input.operationId}`
229
+ : `review-${input.destination.id}`;
230
+ const to = input.recipients?.to ?? [input.destination.external_id];
231
+ const cc = input.recipients?.cc ?? [];
232
+ const sendFiles = input.files ?? [];
233
+ // The agent's email channel renders and sends it as its own replies, signature and quote
234
+ // included; an agent from before its deliver route answers 404, and the mailbox is used here.
235
+ if (input.agent?.origin !== undefined && input.agent.identityToken !== undefined) {
236
+ const delivered = yield* deliverThroughAgent(input, {
237
+ threadId,
238
+ to,
239
+ cc,
240
+ key,
241
+ files: sendFiles,
242
+ });
243
+ if (delivered !== undefined) {
244
+ return delivered;
245
+ }
246
+ }
247
+ // @legacy ontology.email-own-sender The ontology's own mail sender, for an agent without the
248
+ // email channel's deliver route: the files' bytes, read and checked before the reply was
249
+ // reserved, go in its message.
250
+ const files = sendFiles;
133
251
  // The headers read with the reply's people, or else the thread as it is now.
134
252
  const thread = input.thread !== undefined
135
253
  ? undefined
@@ -157,19 +275,10 @@ export function sendEmail(input) {
157
275
  const messages = thread?._tag === "Success" ? record(parse(thread.value.body)).messages : [];
158
276
  return (Array.isArray(messages) ? messages : []).filter((message) => !labelsOf(message).includes("DRAFT"));
159
277
  })());
160
- // The agent's reply, as the email channel sends its own: marked as a program's, so no
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
278
  // With the channel's `signature`, the HTML ends with the mailbox's own signature.
167
279
  const html = input.signature === true
168
280
  ? withEmailSignature(input.finalText, yield* signatureOf(input))
169
281
  : input.finalText;
170
- const to = input.recipients?.to ?? [input.destination.external_id];
171
- const cc = input.recipients?.cc ?? [];
172
- const files = input.files ?? [];
173
282
  const raw = emailReplyMessage({
174
283
  to,
175
284
  ...(cc.length === 0 ? {} : { cc }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.175.0",
3
+ "version": "0.176.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",