@segmentstream/agent 0.50.3 → 0.51.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -0
  3. package/dist/_chunks/{build-metadata-CUHPCFCT.mjs → build-metadata-BDr_toej.mjs} +1 -1
  4. package/dist/_chunks/{principal-D5Tualrk.mjs → principal-ie0lHCpn.mjs} +19 -2
  5. package/dist/extension/channels/email.d.ts +7 -0
  6. package/dist/extension/channels/email.mjs +20 -0
  7. package/dist/extension/config.d.ts +36 -0
  8. package/dist/extension/config.mjs +64 -3
  9. package/dist/extension/connections/ontology.mjs +1 -1
  10. package/dist/extension/hooks/authorization.mjs +1 -1
  11. package/dist/extension/instructions/persona.mjs +1 -1
  12. package/dist/extension/lib/actor.mjs +1 -1
  13. package/dist/extension/lib/attachment-tools.mjs +1 -1
  14. package/dist/extension/lib/attachments.d.ts +11 -1
  15. package/dist/extension/lib/attachments.mjs +1 -1
  16. package/dist/extension/lib/build-metadata.mjs +1 -1
  17. package/dist/extension/lib/chat-address.d.ts +1 -1
  18. package/dist/extension/lib/chat-address.mjs +1 -1
  19. package/dist/extension/lib/chat-context.mjs +1 -1
  20. package/dist/extension/lib/chat-recorder.mjs +9 -1
  21. package/dist/extension/lib/confirmations.mjs +1 -1
  22. package/dist/extension/lib/email/channel.d.ts +80 -0
  23. package/dist/extension/lib/email/channel.mjs +524 -0
  24. package/dist/extension/lib/email/gmail.d.ts +68 -0
  25. package/dist/extension/lib/email/gmail.mjs +188 -0
  26. package/dist/extension/lib/email/message.d.ts +44 -0
  27. package/dist/extension/lib/email/message.mjs +78 -0
  28. package/dist/extension/lib/identities.d.ts +5 -0
  29. package/dist/extension/lib/identities.mjs +3 -2
  30. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  31. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  32. package/dist/extension/lib/ontology-connection.mjs +1 -1
  33. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  34. package/dist/extension/lib/ontology-tools.mjs +1 -1
  35. package/dist/extension/lib/review/hold.d.ts +1 -1
  36. package/dist/extension/lib/review/hold.mjs +6 -2
  37. package/dist/extension/lib/review/reply.mjs +1 -1
  38. package/dist/extension/lib/role-skill.mjs +1 -1
  39. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  40. package/dist/extension/lib/sent-files.mjs +1 -1
  41. package/dist/extension/lib/slack/adapter.mjs +1 -1
  42. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  43. package/dist/extension/lib/stored-files.mjs +1 -1
  44. package/dist/extension/lib/telegram/adapter.mjs +3 -19
  45. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  46. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  47. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  48. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  49. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  50. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  51. package/dist/extension/lib/telegram/files.mjs +1 -1
  52. package/dist/extension/lib/telegram/health.mjs +1 -1
  53. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  54. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  55. package/dist/extension/lib/telegram/inbound.mjs +1 -1
  56. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  57. package/dist/extension/lib/telegram/principal.mjs +1 -1
  58. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  59. package/dist/extension/lib/telegram/silent.mjs +1 -1
  60. package/dist/extension/lib/telegram/structured.mjs +1 -1
  61. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  62. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  63. package/dist/extension/lib/web/auth.mjs +1 -1
  64. package/dist/extension/lib/web/channel.mjs +1 -1
  65. package/dist/extension/lib/whatsapp/adapter.mjs +1 -1
  66. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  67. package/dist/extension/lib/workspace-source.mjs +1 -1
  68. package/dist/extension/model.mjs +1 -1
  69. package/dist/extension/tools/attachments_discard.mjs +1 -1
  70. package/dist/extension/tools/attachments_list.mjs +1 -1
  71. package/dist/extension/tools/attachments_promote.mjs +1 -1
  72. package/dist/extension/tools/attachments_read.mjs +1 -1
  73. package/dist/extension/tools/attachments_send.mjs +1 -1
  74. package/dist/extension/tools/attachments_stage.mjs +1 -1
  75. package/dist/extension/tools/attachments_table.mjs +1 -1
  76. package/dist/extension/tools/questions_ask.mjs +1 -1
  77. package/dist/extension/tools/workspace_source.mjs +1 -1
  78. package/package.json +2 -2
@@ -0,0 +1,524 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { PUBSUB_TOPIC } from "../../config.mjs";
8
+ import { admitMessage, localizedText } from "../admission.mjs";
9
+ import { providerChat } from "../attachment-tools.mjs";
10
+ import { S as agentAttachments, d as prepareInboundMedia, i as memberIdOf, lt as withChatAddress, m as turnContent, st as chatAddressOf, w as fetchStoredAttachment } from "../../../_chunks/principal-ie0lHCpn.mjs";
11
+ import { chatEvent } from "../chat-archive.mjs";
12
+ import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
13
+ import { redactDiagnostic } from "../diagnostics.mjs";
14
+ import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
15
+ import { AgentIdentityError, agentIdentities } from "../identities.mjs";
16
+ import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
17
+ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
18
+ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
19
+ import { channelReview } from "../review/reply.mjs";
20
+ import { completionKind } from "../telegram/silent.mjs";
21
+ import { runtimeToken } from "../runtime-token.mjs";
22
+ import { GMAIL_ID, GmailError, gmail } from "./gmail.mjs";
23
+ import { inboundMail, parseMail } from "./message.mjs";
24
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
25
+ import { reply } from "eve/events";
26
+ import { POST, defineChannel } from "eve/channels";
27
+ const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
28
+ const EMAIL_AUTHENTICATOR = "segmentstream-email";
29
+ const MESSAGES_PER_WAKE = 20;
30
+ const WATCH_RENEW_MS = 864e5;
31
+ const RECOVERED_MESSAGES = 500;
32
+ const MAXIMUM_CURSOR_LENGTH = 16384;
33
+ const MAX_ATTEMPTS = 3;
34
+ const WAKE_WORK_MS = 2e4;
35
+ const MESSAGE_DEADLINE_MS = 6e4;
36
+ var MessageTimeout = class extends Error {
37
+ constructor() {
38
+ super("The message took longer than a wake allows.");
39
+ }
40
+ };
41
+ const REPLY_ATTEMPTS = 4;
42
+ const REPLY_RETRY_MS = 2e3;
43
+ var UnreadableMail = class extends Error {
44
+ name = "UnreadableMail";
45
+ };
46
+ function retryable(error) {
47
+ if (error instanceof UnreadableMail) return false;
48
+ if (error instanceof GmailError) return error.status === 408 || error.status === 429 || error.status >= 500;
49
+ if (error instanceof ConnectionProxyError) return error.code !== "too_large" && error.code !== "invalid_request";
50
+ if (error instanceof AgentIdentityError) return error.status === void 0 || error.status === 429 || error.status >= 500;
51
+ return true;
52
+ }
53
+ async function withDeadline(work) {
54
+ let timer;
55
+ try {
56
+ await Promise.race([work, new Promise((_resolve, reject) => {
57
+ timer = setTimeout(() => reject(new MessageTimeout()), MESSAGE_DEADLINE_MS);
58
+ })]);
59
+ } finally {
60
+ clearTimeout(timer);
61
+ }
62
+ }
63
+ function fileKind(contentType) {
64
+ const type = contentType.toLowerCase();
65
+ return type.startsWith("audio/") ? "audio" : type.startsWith("image/") ? "image" : type.startsWith("video/") ? "video" : "document";
66
+ }
67
+ const NOT_RECEIVED = new Set([
68
+ "SENT",
69
+ "DRAFT",
70
+ "SPAM",
71
+ "TRASH"
72
+ ]);
73
+ function decodeCursor(value) {
74
+ if (typeof value !== "string" || value === "") return;
75
+ try {
76
+ const cursor = JSON.parse(value);
77
+ return typeof cursor.h === "string" && /^\d{1,30}$/u.test(cursor.h) && typeof cursor.a === "string" && cursor.a.includes("@") ? {
78
+ h: cursor.h,
79
+ a: cursor.a,
80
+ ...typeof cursor.w === "number" && Number.isFinite(cursor.w) ? { w: cursor.w } : {},
81
+ ...typeof cursor.t === "string" && PUBSUB_TOPIC.test(cursor.t) ? { t: cursor.t } : {},
82
+ ...Array.isArray(cursor.p) && cursor.p.every((id) => typeof id === "string" && GMAIL_ID.test(id)) ? { p: cursor.p } : {},
83
+ ...typeof cursor.x?.id === "string" && GMAIL_ID.test(cursor.x.id) && Number.isInteger(cursor.x.n) && cursor.x.n > 0 ? { x: {
84
+ id: cursor.x.id,
85
+ n: cursor.x.n
86
+ } } : {}
87
+ } : void 0;
88
+ } catch {
89
+ return;
90
+ }
91
+ }
92
+ function emailChatId(threadId, sender) {
93
+ return `${threadId}:${sender}`;
94
+ }
95
+ function emailPrincipal(member, sender, threadId) {
96
+ return withChatAddress({
97
+ authenticator: EMAIL_AUTHENTICATOR,
98
+ issuer: "email",
99
+ principalId: `email:${sender}`,
100
+ principalType: "user",
101
+ subject: sender,
102
+ attributes: {
103
+ memberId: member.id,
104
+ identityProvider: "email",
105
+ roles: member.roles,
106
+ ...member.name === null ? {} : { memberName: member.name },
107
+ ...member.locale === void 0 ? {} : { locale: member.locale }
108
+ }
109
+ }, {
110
+ provider: "email",
111
+ chatId: emailChatId(threadId, sender),
112
+ threadId,
113
+ kind: "private",
114
+ peer: sender
115
+ });
116
+ }
117
+ function replyText(view, turnId) {
118
+ return reply(view, turnId).filter((part) => part.kind === "text" && part.interrupted !== true).flatMap((part) => typeof part.value === "string" ? [part.value] : []).join("\n").trim();
119
+ }
120
+ function turnText(mail) {
121
+ return [mail.subject === "" ? "" : `Subject: ${mail.subject}`, mail.text].filter((part) => part !== "").join("\n\n");
122
+ }
123
+ function signed(secret, body, signature) {
124
+ if (signature === null) return false;
125
+ const expected = `sha256=${createHmac("sha256", secret).update(body, "utf8").digest("hex")}`;
126
+ const given = signature.trim().toLowerCase();
127
+ return expected.length === given.length && timingSafeEqual(Buffer.from(expected), Buffer.from(given));
128
+ }
129
+ function replyKey(sessionId, turnId) {
130
+ return createHash("sha256").update(`${sessionId}:${turnId}`).digest("base64url").slice(0, 32);
131
+ }
132
+ function segmentstreamEmail(options) {
133
+ return defineChannel(emailChannelDefinition(options));
134
+ }
135
+ function emailChannelDefinition(options) {
136
+ const environment = options.environment ?? process.env;
137
+ const token = options.token ?? runtimeToken;
138
+ const log = options.log ?? ((message, detail) => console.error(message, detail));
139
+ const now = options.now ?? Date.now;
140
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
141
+ const proxies = new Map();
142
+ const transport = {
143
+ token,
144
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
145
+ };
146
+ let identities = options.identities;
147
+ let attachments = options.attachments;
148
+ let capabilities;
149
+ let reviewed;
150
+ const settings = () => options.settings();
151
+ const mailbox = () => options.gmail ?? gmail(() => {
152
+ const connection = settings()?.connection;
153
+ if (connection === void 0) throw new Error("The email channel is not configured in agent/segmentstream.json.");
154
+ let existing = proxies.get(connection);
155
+ if (existing === void 0) {
156
+ existing = connectionProxy({
157
+ environment: proxyEnvironment(environment),
158
+ connection,
159
+ ...transport
160
+ });
161
+ proxies.set(connection, existing);
162
+ }
163
+ return existing;
164
+ });
165
+ const people = () => identities ??= agentIdentities({
166
+ origin: appOrigin(environment),
167
+ ...transport
168
+ });
169
+ const files = () => attachments ??= agentAttachments({
170
+ origin: appOrigin(environment),
171
+ ...transport
172
+ });
173
+ const review = () => options.review === void 0 ? void 0 : reviewed ??= channelReview({
174
+ settings: options.review.settings,
175
+ decide: options.review.decide,
176
+ model: options.review.model,
177
+ ...options.review.archive === void 0 ? {} : { archive: options.review.archive },
178
+ ...options.review.hold === void 0 ? {} : { hold: options.review.hold }
179
+ }, {
180
+ environment,
181
+ ...transport
182
+ });
183
+ const answer = (threadId, to, text) => mailbox().reply({
184
+ threadId,
185
+ to,
186
+ text
187
+ });
188
+ async function deliver(threadId, to, text, key) {
189
+ for (let attempt = 1;; attempt++) try {
190
+ await mailbox().reply({
191
+ threadId,
192
+ to,
193
+ text,
194
+ key
195
+ });
196
+ return;
197
+ } catch (error) {
198
+ if (!retryable(error) || attempt >= REPLY_ATTEMPTS) throw error;
199
+ await sleep(REPLY_RETRY_MS * 4 ** (attempt - 1));
200
+ }
201
+ }
202
+ async function dispatch(added, mail, args) {
203
+ const admission = options.admission();
204
+ const resolution = await admitMessage({
205
+ identity: {
206
+ provider: "email",
207
+ externalId: mail.from,
208
+ chat: "private",
209
+ turn: true,
210
+ addressVerified: mail.verified,
211
+ ...mail.fromName === void 0 ? {} : { display: mail.fromName }
212
+ },
213
+ identities: people(),
214
+ settings: admission,
215
+ sendNotice: (text) => answer(added.threadId, mail.from, text),
216
+ noticeFailed: (error) => log("[segmentstream] email notice failed", { error: redactDiagnostic(error, new Set()) })
217
+ });
218
+ if (resolution.status === "limited") {
219
+ const replies = admission.replies;
220
+ const configured = resolution.scope === "workspaceTurnsPerDay" ? replies.workspaceLimited : resolution.scope === "newUsersPerHour" ? replies.registrationsLimited : replies.perSenderLimited;
221
+ const text = resolution.notify ? localizedText(configured ?? replies.limited) : void 0;
222
+ if (text !== void 0) {
223
+ let delivered = false;
224
+ try {
225
+ await answer(added.threadId, mail.from, text);
226
+ delivered = true;
227
+ } finally {
228
+ if (resolution.notificationId !== void 0) await people().completeLimitNotice({
229
+ notificationId: resolution.notificationId,
230
+ delivered
231
+ }).catch((error) => log("[segmentstream] email limit notice", { error }));
232
+ }
233
+ }
234
+ return;
235
+ }
236
+ if (resolution.status !== "existing" && resolution.status !== "created") return;
237
+ const auth = emailPrincipal(resolution.member, mail.from, added.threadId);
238
+ const memberId = memberIdOf(auth);
239
+ const inbound = mail.attachments.map((file, index) => ({
240
+ key: `${added.id}:${index}`,
241
+ kind: fileKind(file.contentType),
242
+ filename: file.filename,
243
+ contentType: file.contentType,
244
+ size: file.bytes.byteLength,
245
+ download: async (maxBytes) => {
246
+ if (file.bytes.byteLength > maxBytes) throw new Error("The attachment is larger than an attachment may be.");
247
+ return file.bytes;
248
+ }
249
+ }));
250
+ const models = options.models?.();
251
+ const report = (operation, error) => {
252
+ const reference = randomUUID();
253
+ log("[segmentstream] email attachment diagnostic", {
254
+ operation,
255
+ reference,
256
+ error: redactDiagnostic(error, new Set())
257
+ });
258
+ return reference;
259
+ };
260
+ const plan = inbound.length === 0 || models === void 0 ? void 0 : await turnMediaPlan({
261
+ models,
262
+ principal: auth,
263
+ capabilities: capabilities ??= options.modelCapabilities ?? gatewayMediaCapabilities(options.fetch, report),
264
+ environment,
265
+ report
266
+ });
267
+ const media = await prepareInboundMedia({
268
+ caption: turnText(mail),
269
+ files: inbound,
270
+ group: false,
271
+ sttModel: models?.stt ?? false,
272
+ transcribe: options.transcribe ?? gatewayTranscriber,
273
+ report,
274
+ ...plan === void 0 ? {} : { plan },
275
+ describeImage: options.describeImage ?? gatewayImageDescriber,
276
+ ...inbound.length === 0 ? {} : { store: {
277
+ attachments: files(),
278
+ memberId,
279
+ chat: providerChat("email", emailChatId(added.threadId, mail.from)),
280
+ source: "email",
281
+ sourceRef: (index) => `${added.threadId}:${added.id}:${index}`
282
+ } }
283
+ });
284
+ const keys = new Map();
285
+ const parts = mail.attachments.map((file, index) => {
286
+ const part = {
287
+ type: "file",
288
+ data: file.bytes,
289
+ mediaType: file.contentType,
290
+ filename: file.filename
291
+ };
292
+ keys.set(part, `${added.id}:${index}`);
293
+ return part;
294
+ });
295
+ const content = parts.length === 0 ? media.text : turnContent([{
296
+ type: "text",
297
+ text: media.text
298
+ }, ...parts], {
299
+ files: media.files,
300
+ keyOf: (part) => keys.get(part),
301
+ readStored: true,
302
+ spoken: {
303
+ keys: media.spoken.keys,
304
+ text: ""
305
+ }
306
+ });
307
+ await args.from(emailChatId(added.threadId, mail.from)).send(content, {
308
+ auth,
309
+ idempotencyKey: `email:${added.id}`,
310
+ ...media.context.length === 0 ? {} : { context: media.context }
311
+ });
312
+ }
313
+ async function handle(added, restarted, own, current, args) {
314
+ if (added.labelIds.some((label) => NOT_RECEIVED.has(label))) return;
315
+ const gmail = mailbox();
316
+ const raw = await gmail.raw(added.id);
317
+ if (raw.labelIds.some((label) => NOT_RECEIVED.has(label))) return;
318
+ let parsed;
319
+ try {
320
+ parsed = await parseMail(raw.bytes);
321
+ } catch (cause) {
322
+ throw new UnreadableMail("The message is not readable mail.", { cause });
323
+ }
324
+ const mail = inboundMail(parsed, own);
325
+ if (mail.skip !== void 0) return;
326
+ if (!restarted) {
327
+ if (mail.messageId === void 0) return;
328
+ if (!(await gmail.search(`(${current.query}) rfc822msgid:${mail.messageId.replace(/[<>"]/gu, "")}`, 5)).includes(added.id)) return;
329
+ }
330
+ await dispatch({
331
+ ...added,
332
+ threadId: raw.threadId
333
+ }, mail, args);
334
+ }
335
+ async function wake(request, args) {
336
+ const current = settings();
337
+ const secret = webhookSecret(environment);
338
+ if (!channelsEnabled(environment) || current === null || secret === void 0) return new Response(null, { status: 404 });
339
+ const body = await request.text();
340
+ if (!signed(secret, body, request.headers.get("x-hub-signature-256"))) return Response.json({ error: "invalid_signature" }, { status: 401 });
341
+ let requested;
342
+ try {
343
+ requested = JSON.parse(body).cursor;
344
+ } catch {
345
+ return Response.json({ error: "invalid_request" }, { status: 400 });
346
+ }
347
+ const gmail = mailbox();
348
+ try {
349
+ const known = decodeCursor(requested);
350
+ let watch = known?.w;
351
+ let watched = known?.t;
352
+ const renew = async () => {
353
+ if (current.push !== null && (watch === void 0 || watched !== current.push.topic || watch - now() < WATCH_RENEW_MS)) try {
354
+ watch = await gmail.watch(current.push.topic);
355
+ watched = current.push.topic;
356
+ } catch (error) {
357
+ log("[segmentstream] email push watch failed", { error: redactDiagnostic(error, new Set()) });
358
+ }
359
+ };
360
+ const answerCursor = (cursor, more) => {
361
+ const full = {
362
+ ...cursor,
363
+ ...watch === void 0 ? {} : { w: watch },
364
+ ...watch === void 0 || watched === void 0 ? {} : { t: watched }
365
+ };
366
+ let encoded = JSON.stringify(full);
367
+ if (encoded.length > 16384 && full.p !== void 0) {
368
+ const p = [...full.p];
369
+ while (p.length > 0 && JSON.stringify({
370
+ ...full,
371
+ p
372
+ }).length > 16384) p.pop();
373
+ log("[segmentstream] email recovery list shortened", { kept: p.length });
374
+ encoded = JSON.stringify({
375
+ ...full,
376
+ p
377
+ });
378
+ }
379
+ return Response.json({
380
+ cursor: encoded,
381
+ more
382
+ });
383
+ };
384
+ if (known === void 0) {
385
+ const profile = await gmail.profile();
386
+ await renew();
387
+ return answerCursor({
388
+ h: profile.historyId,
389
+ a: profile.address
390
+ }, false);
391
+ }
392
+ await renew();
393
+ const own = new Set([known.a]);
394
+ let h = known.h;
395
+ let pending = known.p ?? [];
396
+ let restarted = pending.length > 0;
397
+ let messages;
398
+ let more;
399
+ if (pending.length === 0) {
400
+ const read = await gmail.added(known.h, MESSAGES_PER_WAKE);
401
+ if (read === void 0) {
402
+ h = (await gmail.profile()).historyId;
403
+ pending = (await gmail.search(`(${current.query}) newer_than:2d`, RECOVERED_MESSAGES)).toReversed();
404
+ restarted = true;
405
+ } else {
406
+ messages = read.messages;
407
+ h = read.historyId;
408
+ more = read.more;
409
+ }
410
+ }
411
+ if (restarted) {
412
+ messages = pending.slice(0, MESSAGES_PER_WAKE).map((id) => ({
413
+ id,
414
+ threadId: "",
415
+ labelIds: [],
416
+ historyId: h
417
+ }));
418
+ pending = pending.slice(MESSAGES_PER_WAKE);
419
+ more = pending.length > 0;
420
+ }
421
+ let checkpoint = known.h;
422
+ const startedAt = now();
423
+ for (const [index, added] of messages.entries()) {
424
+ if (index > 0 && now() - startedAt >= WAKE_WORK_MS && (restarted || messages[index - 1].historyId !== added.historyId)) return answerCursor(restarted ? {
425
+ h,
426
+ a: known.a,
427
+ p: [...messages.slice(index).map((item) => item.id), ...pending]
428
+ } : {
429
+ h: checkpoint,
430
+ a: known.a
431
+ }, true);
432
+ try {
433
+ await withDeadline(handle(added, restarted, own, current, args));
434
+ } catch (error) {
435
+ const attempts = known.x?.id === added.id ? known.x.n + 1 : 1;
436
+ const permanent = !retryable(error) || attempts >= MAX_ATTEMPTS;
437
+ log("[segmentstream] email message failed", {
438
+ message: added.id,
439
+ attempts,
440
+ skipped: permanent,
441
+ error: redactDiagnostic(error, new Set())
442
+ });
443
+ if (!permanent) return answerCursor(restarted ? {
444
+ h,
445
+ a: known.a,
446
+ p: [...messages.slice(index).map((item) => item.id), ...pending],
447
+ x: {
448
+ id: added.id,
449
+ n: attempts
450
+ }
451
+ } : {
452
+ h: checkpoint,
453
+ a: known.a,
454
+ x: {
455
+ id: added.id,
456
+ n: attempts
457
+ }
458
+ }, false);
459
+ }
460
+ const next = messages[index + 1];
461
+ if (!restarted && next?.historyId !== added.historyId) checkpoint = added.historyId;
462
+ }
463
+ return answerCursor(restarted && pending.length > 0 ? {
464
+ h,
465
+ a: known.a,
466
+ p: pending
467
+ } : {
468
+ h,
469
+ a: known.a
470
+ }, more);
471
+ } catch (error) {
472
+ log("[segmentstream] email wake failed", { error: redactDiagnostic(error, new Set()) });
473
+ return Response.json({ error: "unavailable" }, { status: 503 });
474
+ }
475
+ }
476
+ return {
477
+ routes: [POST(EMAIL_ROUTE, wake)],
478
+ events: { async "turn.settled"(event, ctx) {
479
+ const { outcome, turnId } = event.data;
480
+ const principal = ctx.session.auth.current;
481
+ const chat = chatAddressOf(principal);
482
+ if (outcome !== "completed" || chat?.provider !== "email" || chat.peer === void 0) return;
483
+ const text = replyText(ctx.view, turnId);
484
+ if (completionKind(text) !== "reply") return;
485
+ const reviewing = review()?.review;
486
+ if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
487
+ principal,
488
+ sessionId: ctx.session.id,
489
+ turnId,
490
+ partId: turnId,
491
+ text
492
+ }))) return;
493
+ try {
494
+ await deliver(chat.threadId, chat.peer, text, replyKey(ctx.session.id, turnId));
495
+ const memberId = memberIdOf(principal);
496
+ await (reviewing?.reviewed(principal) === true ? review() : void 0)?.archive.append(chatEvent({
497
+ eventId: `email:reply:${ctx.session.id}:${turnId}`,
498
+ provider: "email",
499
+ chatId: chat.chatId,
500
+ threadId: chat.threadId === "" ? null : chat.threadId,
501
+ chatType: "private",
502
+ participantIds: memberId === void 0 ? [] : [memberId],
503
+ sessionId: ctx.session.id,
504
+ turnId,
505
+ kind: "outbound",
506
+ text,
507
+ senderId: "agent",
508
+ senderIsBot: true,
509
+ status: "completed"
510
+ })).catch((error) => log("[segmentstream] email reply archive failed", {
511
+ sessionId: ctx.session.id,
512
+ error: redactDiagnostic(error, new Set())
513
+ }));
514
+ } catch (error) {
515
+ log("[segmentstream] email reply failed", {
516
+ sessionId: ctx.session.id,
517
+ error: redactDiagnostic(error, new Set())
518
+ });
519
+ }
520
+ } },
521
+ fetchFile: (url, context) => fetchStoredAttachment(files(), url, context)
522
+ };
523
+ }
524
+ export { EMAIL_AUTHENTICATOR, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailPrincipal, segmentstreamEmail };
@@ -0,0 +1,68 @@
1
+ import type { ConnectionProxy } from "../connection-proxy.js";
2
+ /**
3
+ * The mailbox of a `GmailConnection`, through SegmentStream's connection proxy: the calls the email
4
+ * channel makes, each one Gmail API request on `users/me`.
5
+ */
6
+ /** A Gmail id, of a thread, a message or a history record. */
7
+ export declare const GMAIL_ID: RegExp;
8
+ /**
9
+ * Gmail answered with a status the channel does not continue from. `detail` keeps Google's own
10
+ * explanation, such as a topic Gmail may not publish to or a missing scope, for operators; the
11
+ * channel redacts it where it logs.
12
+ */
13
+ export declare class GmailError extends Error {
14
+ readonly operation: string;
15
+ readonly status: number;
16
+ readonly detail?: string | undefined;
17
+ readonly name = "GmailError";
18
+ constructor(operation: string, status: number, detail?: string | undefined);
19
+ }
20
+ /** A message the mailbox received since the cursor, as its history names it. */
21
+ export interface AddedMessage {
22
+ readonly id: string;
23
+ readonly threadId: string;
24
+ readonly labelIds: ReadonlyArray<string>;
25
+ /** The history record that added it: once it is handled, the cursor may move past it. */
26
+ readonly historyId: string;
27
+ }
28
+ export interface Gmail {
29
+ /** The mailbox's address and its current history id. */
30
+ profile(): Promise<{
31
+ readonly address: string;
32
+ readonly historyId: string;
33
+ }>;
34
+ /**
35
+ * The messages added after `startHistoryId`, oldest first, up to `limit`; `undefined` when
36
+ * Gmail no longer keeps history that old.
37
+ */
38
+ added(startHistoryId: string, limit: number): Promise<{
39
+ readonly messages: ReadonlyArray<AddedMessage>;
40
+ readonly historyId: string;
41
+ readonly more: boolean;
42
+ } | undefined>;
43
+ /** The ids of messages the search finds, newest first, up to `limit`. */
44
+ search(query: string, limit: number): Promise<ReadonlyArray<string>>;
45
+ /** The message as RFC 5322 bytes, with its thread and labels. */
46
+ raw(id: string): Promise<{
47
+ readonly bytes: Uint8Array;
48
+ readonly threadId: string;
49
+ readonly labelIds: ReadonlyArray<string>;
50
+ }>;
51
+ /** Asks Gmail to push the mailbox's changes to `topic`; resolves the watch's expiry. */
52
+ watch(topic: string): Promise<number>;
53
+ /**
54
+ * Replies in `threadId` to `to`, under the thread's last message, with the reply's Markdown as
55
+ * HTML and as plain text. Resolves the sent message's id.
56
+ */
57
+ /**
58
+ * Sends `text` in the thread, unless a message there already carries `key`: then that is the
59
+ * reply, sent by an earlier attempt whose answer was lost, and its id is returned.
60
+ */
61
+ reply(input: {
62
+ readonly threadId: string;
63
+ readonly to: string;
64
+ readonly text: string;
65
+ readonly key?: string;
66
+ }): Promise<string>;
67
+ }
68
+ export declare function gmail(proxy: () => ConnectionProxy): Gmail;