@segmentstream/agent 0.79.0 → 0.80.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 (91) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/_chunks/{build-metadata-BrWGOlRd.mjs → build-metadata-BuTCjnNS.mjs} +1 -1
  4. package/dist/_chunks/{chat-archive-BEk40gWe.mjs → chat-archive-BBd_iZ1d.mjs} +1 -1
  5. package/dist/_chunks/{principal-C7aAjyt4.mjs → principal-CVV9C_nO.mjs} +8 -1
  6. package/dist/extension/config.d.ts +8 -0
  7. package/dist/extension/config.mjs +14 -3
  8. package/dist/extension/connections/ontology.mjs +1 -1
  9. package/dist/extension/hooks/authorization.mjs +1 -1
  10. package/dist/extension/instructions/persona.mjs +1 -1
  11. package/dist/extension/lib/actor.mjs +1 -1
  12. package/dist/extension/lib/admission.d.ts +7 -0
  13. package/dist/extension/lib/admission.mjs +8 -6
  14. package/dist/extension/lib/attachment-tools.mjs +1 -1
  15. package/dist/extension/lib/attachments-send.mjs +1 -1
  16. package/dist/extension/lib/attachments.mjs +1 -1
  17. package/dist/extension/lib/build-metadata.mjs +1 -1
  18. package/dist/extension/lib/chat-address.d.ts +11 -0
  19. package/dist/extension/lib/chat-address.mjs +1 -1
  20. package/dist/extension/lib/chat-context.d.ts +7 -0
  21. package/dist/extension/lib/chat-context.mjs +1 -1
  22. package/dist/extension/lib/chat-messages.d.ts +9 -1
  23. package/dist/extension/lib/chat-messages.mjs +4 -4
  24. package/dist/extension/lib/chat-recorder.d.ts +12 -4
  25. package/dist/extension/lib/chat-recorder.mjs +2 -2
  26. package/dist/extension/lib/chat-store.d.ts +6 -0
  27. package/dist/extension/lib/confirmations.mjs +1 -1
  28. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  29. package/dist/extension/lib/email/channel.d.ts +19 -5
  30. package/dist/extension/lib/email/channel.mjs +209 -22
  31. package/dist/extension/lib/email/gmail.d.ts +5 -0
  32. package/dist/extension/lib/email/gmail.mjs +11 -0
  33. package/dist/extension/lib/guest-usage.mjs +1 -1
  34. package/dist/extension/lib/identities.d.ts +2 -0
  35. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  36. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  37. package/dist/extension/lib/ontology-connection.mjs +1 -1
  38. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  39. package/dist/extension/lib/ontology-tools.mjs +1 -1
  40. package/dist/extension/lib/review/client.mjs +24 -12
  41. package/dist/extension/lib/review/hold.d.ts +7 -0
  42. package/dist/extension/lib/review/hold.mjs +3 -1
  43. package/dist/extension/lib/review/reply.mjs +1 -1
  44. package/dist/extension/lib/role-skill.mjs +1 -1
  45. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  46. package/dist/extension/lib/sent-files.mjs +1 -1
  47. package/dist/extension/lib/slack/adapter.mjs +1 -1
  48. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  49. package/dist/extension/lib/slack/callbacks.mjs +1 -1
  50. package/dist/extension/lib/stored-files.mjs +1 -1
  51. package/dist/extension/lib/telegram/adapter.mjs +3 -3
  52. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  53. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  54. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  55. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  56. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  57. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  58. package/dist/extension/lib/telegram/files.mjs +1 -1
  59. package/dist/extension/lib/telegram/health.mjs +1 -1
  60. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  61. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  62. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  63. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  64. package/dist/extension/lib/telegram/principal.mjs +1 -1
  65. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  66. package/dist/extension/lib/telegram/silent.mjs +1 -1
  67. package/dist/extension/lib/telegram/store-capture.mjs +1 -1
  68. package/dist/extension/lib/telegram/structured.mjs +1 -1
  69. package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
  70. package/dist/extension/lib/web/auth.mjs +1 -1
  71. package/dist/extension/lib/web/channel.mjs +1 -1
  72. package/dist/extension/lib/whatsapp/adapter.mjs +1 -1
  73. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  74. package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
  75. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  76. package/dist/extension/lib/workspace-action.mjs +1 -1
  77. package/dist/extension/lib/workspace-channel/attachments-send.mjs +1 -1
  78. package/dist/extension/lib/workspace-channel/channel.mjs +1 -1
  79. package/dist/extension/lib/workspace-source.mjs +1 -1
  80. package/dist/extension/model.mjs +1 -1
  81. package/dist/extension/tools/attachments_discard.mjs +1 -1
  82. package/dist/extension/tools/attachments_list.mjs +1 -1
  83. package/dist/extension/tools/attachments_promote.mjs +1 -1
  84. package/dist/extension/tools/attachments_read.mjs +1 -1
  85. package/dist/extension/tools/attachments_send.mjs +1 -1
  86. package/dist/extension/tools/attachments_stage.mjs +1 -1
  87. package/dist/extension/tools/attachments_table.mjs +1 -1
  88. package/dist/extension/tools/handoff.mjs +1 -1
  89. package/dist/extension/tools/questions_ask.mjs +1 -1
  90. package/dist/extension/tools/workspace_source.mjs +1 -1
  91. package/package.json +2 -2
@@ -8,9 +8,10 @@ import { PUBSUB_TOPIC } from "../../config.mjs";
8
8
  import { admitMessage, localizedText, reportUnadmittedChat } from "../admission.mjs";
9
9
  import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
11
- import { Pt as chatAddressOf, S as fetchStoredAttachment, b as agentAttachments, d as prepareInboundMedia, i as memberIdOf, m as turnContent, zt as withChatAddress } from "../../../_chunks/principal-C7aAjyt4.mjs";
11
+ import { Bt as participantsOf, Ft as chatAddressOf, Mt as PARTICIPANTS_ATTRIBUTE, S as fetchStoredAttachment, Vt as withChatAddress, b as agentAttachments, d as prepareInboundMedia, i as memberIdOf, m as turnContent } from "../../../_chunks/principal-CVV9C_nO.mjs";
12
12
  import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
13
- import { d as replyRecipients, g as UNVERIFIED, l as replyEvent, p as storeOf, r as chatArchive } from "../../../_chunks/chat-archive-DavfKJDI.mjs";
13
+ import { a as chatEvent, b as messageInput, d as replyRecipients, g as UNVERIFIED, l as replyEvent, p as storeOf, r as chatArchive, t as AGENT_SENDER } from "../../../_chunks/chat-archive-DavfKJDI.mjs";
14
+ import { ChatStoreError } from "../chat-store.mjs";
14
15
  import { recordChatMessage, recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
15
16
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
16
17
  import { redactDiagnostic } from "../diagnostics.mjs";
@@ -55,6 +56,7 @@ const DISCARDED = new Set([
55
56
  "SPAM",
56
57
  "TRASH"
57
58
  ]);
59
+ const THREADS_REMEMBERED = 1e3;
58
60
  function waitingReply(event) {
59
61
  const key = event.operationId?.startsWith("reply:") ? event.operationId.slice(6) : void 0;
60
62
  const threadId = event.threadId;
@@ -133,13 +135,17 @@ function decodeCursor(value) {
133
135
  function emailChatId(threadId, sender) {
134
136
  return `${threadId}:${sender}`;
135
137
  }
138
+ function emailChatOf(settings, threadId, sender) {
139
+ return settings?.chats === "thread" ? threadId : emailChatId(threadId, sender);
140
+ }
136
141
  const EMAIL_OTHERS_ATTRIBUTE = "segmentstreamEmailOthers";
137
142
  function replyCopies(principal, settings) {
138
143
  const others = principal?.attributes[EMAIL_OTHERS_ATTRIBUTE];
139
144
  return settings?.reply !== "all" || !Array.isArray(others) ? [] : others.filter(isEmailAddress).slice(0, EMAIL_RECIPIENTS_LIMIT - 1);
140
145
  }
141
- function emailPrincipal(member, sender, threadId, others = []) {
146
+ function emailPrincipal(member, sender, threadId, options = {}) {
142
147
  const channel = currentChannel("email");
148
+ const others = options.others ?? [];
143
149
  return withChatAddress({
144
150
  authenticator: EMAIL_AUTHENTICATOR,
145
151
  issuer: "email",
@@ -154,12 +160,13 @@ function emailPrincipal(member, sender, threadId, others = []) {
154
160
  ...member.name === null ? {} : { memberName: member.name },
155
161
  ...member.locale === void 0 ? {} : { locale: member.locale },
156
162
  ...channelAttributes("email", channel),
157
- ...others.length === 0 ? {} : { [EMAIL_OTHERS_ATTRIBUTE]: others.slice(0, EMAIL_RECIPIENTS_LIMIT - 1) }
163
+ ...others.length === 0 ? {} : { [EMAIL_OTHERS_ATTRIBUTE]: others.slice(0, EMAIL_RECIPIENTS_LIMIT - 1) },
164
+ ...options.participants === void 0 ? {} : { [PARTICIPANTS_ATTRIBUTE]: options.participants }
158
165
  }
159
166
  }, {
160
167
  provider: "email",
161
168
  ...channel === "email" ? {} : { channel },
162
- chatId: emailChatId(threadId, sender),
169
+ chatId: options.chatId ?? emailChatId(threadId, sender),
163
170
  threadId,
164
171
  kind: "private",
165
172
  peer: sender
@@ -339,7 +346,143 @@ function emailChannelDefinition(options) {
339
346
  }
340
347
  return resolved && page.nextCursor !== null;
341
348
  }
342
- async function dispatch(added, mail, args, skipped) {
349
+ async function membersOf(addresses, known = new Map()) {
350
+ const unique = [...new Set(addresses)].slice(0, EMAIL_RECIPIENTS_LIMIT);
351
+ await Promise.all(unique.filter((address) => !known.has(address)).map(async (address) => {
352
+ const found = await people().lookup({
353
+ provider: "email",
354
+ externalId: address
355
+ });
356
+ known.set(address, found.status === "paired" ? found.member.id : null);
357
+ }));
358
+ return [...new Set(unique.flatMap((address) => {
359
+ const id = known.get(address);
360
+ return id === null || id === void 0 ? [] : [id];
361
+ }))];
362
+ }
363
+ const histories = new Set();
364
+ async function threadHistory(threadId, before, own) {
365
+ const channel = currentChannel("email");
366
+ const key = `${channel}:${threadId}`;
367
+ const remember = () => {
368
+ histories.add(key);
369
+ if (histories.size > THREADS_REMEMBERED) histories.delete(histories.values().next().value);
370
+ };
371
+ if (histories.has(key)) return;
372
+ const store = await storeOf(archive());
373
+ if (store === void 0) return;
374
+ const [newest] = (await store.read({
375
+ channel,
376
+ chatId: threadId,
377
+ limit: 1
378
+ })).messages;
379
+ if (newest !== void 0 && (newest.importedAt ?? null) === null) {
380
+ remember();
381
+ return;
382
+ }
383
+ const gmail = mailbox();
384
+ const listed = await gmail.thread(threadId);
385
+ const index = listed.findIndex((message) => message.id === before);
386
+ const earlier = (index < 0 ? [] : listed.slice(0, index)).filter((message) => !message.labelIds.some((label) => DISCARDED.has(label))).slice(-20);
387
+ const known = new Map();
388
+ for (const { id, labelIds } of earlier) {
389
+ let raw;
390
+ let parsed;
391
+ try {
392
+ raw = await gmail.raw(id);
393
+ } catch (error) {
394
+ if (retryable(error)) throw error;
395
+ log("[segmentstream] email thread history message skipped", {
396
+ message: id,
397
+ error: redactDiagnostic(error, new Set())
398
+ });
399
+ continue;
400
+ }
401
+ if (raw.labelIds.some((label) => DISCARDED.has(label))) continue;
402
+ try {
403
+ parsed = await parseMail(raw.bytes);
404
+ } catch (error) {
405
+ log("[segmentstream] email thread history message skipped", {
406
+ message: id,
407
+ error: redactDiagnostic(error, new Set())
408
+ });
409
+ continue;
410
+ }
411
+ const at = Date.parse(parsed.date ?? "");
412
+ if (!Number.isFinite(at)) continue;
413
+ const sent = labelIds.includes("SENT") || raw.labelIds.includes("SENT");
414
+ const eventId = `email:history:${id}`;
415
+ let event;
416
+ if (sent) {
417
+ const mail = sentMail(parsed, own);
418
+ const agent = parsed.headers.some((header) => header.key === REPLY_KEY_HEADER.toLowerCase());
419
+ if (mail.text === "" && mail.attachments.length === 0) continue;
420
+ event = chatEvent({
421
+ eventId,
422
+ provider: channel,
423
+ chatId: threadId,
424
+ chatType: "private",
425
+ threadId,
426
+ participantIds: await membersOf(mail.recipients, known),
427
+ senderId: agent ? AGENT_SENDER : mail.fromAddress ?? null,
428
+ senderName: agent ? null : mail.fromName ?? null,
429
+ senderIsBot: agent || mail.automated,
430
+ kind: "outbound",
431
+ messageId: id,
432
+ text: mail.text,
433
+ status: "sent",
434
+ at: new Date(at).toISOString(),
435
+ attachments: mail.attachments.map((file, position) => ({
436
+ id: `${eventId}:file:${position}`,
437
+ kind: "file",
438
+ filename: file.filename,
439
+ contentType: file.contentType,
440
+ size: file.size
441
+ }))
442
+ });
443
+ } else {
444
+ const mail = inboundMail(parsed, own);
445
+ if (!mail.verified || mail.skip !== void 0) continue;
446
+ event = chatEvent({
447
+ eventId,
448
+ provider: channel,
449
+ chatId: threadId,
450
+ chatType: "private",
451
+ threadId,
452
+ participantIds: await membersOf([mail.from, ...mail.others], known),
453
+ senderId: mail.from,
454
+ senderName: mail.fromName ?? null,
455
+ kind: "inbound",
456
+ messageId: id,
457
+ text: turnText(mail),
458
+ at: new Date(at).toISOString(),
459
+ attachments: mail.attachments.map((file, position) => ({
460
+ id: `${eventId}:file:${position}`,
461
+ kind: "file",
462
+ filename: file.filename,
463
+ contentType: file.contentType,
464
+ size: file.bytes.byteLength
465
+ }))
466
+ });
467
+ }
468
+ try {
469
+ await store.record({
470
+ ...messageInput(event),
471
+ imported: true
472
+ });
473
+ } catch (error) {
474
+ if (error instanceof ChatStoreError && error.status === 400) {
475
+ log("[segmentstream] email thread history not imported", { error: redactDiagnostic(error, new Set()) });
476
+ break;
477
+ }
478
+ throw error;
479
+ }
480
+ }
481
+ remember();
482
+ }
483
+ async function dispatch(added, mail, args, skipped, current, own) {
484
+ const thread = current.chats === "thread";
485
+ const chatId = emailChatOf(current, added.threadId, mail.from);
343
486
  const admission = options.admission();
344
487
  const resolution = await admitMessage({
345
488
  identity: {
@@ -354,9 +497,15 @@ function emailChannelDefinition(options) {
354
497
  settings: admission,
355
498
  sendNotice: (text) => answer(added.threadId, mail.from, text),
356
499
  noticeFailed: (error) => log("[segmentstream] email notice failed", { error: redactDiagnostic(error, new Set()) }),
357
- chat: {
500
+ chat: thread ? {
358
501
  channel: currentChannel("email"),
359
- chatId: emailChatId(added.threadId, mail.from),
502
+ chatId,
503
+ threadId: added.threadId,
504
+ shared: true,
505
+ ...mail.subject === "" ? {} : { title: mail.subject }
506
+ } : {
507
+ channel: currentChannel("email"),
508
+ chatId,
360
509
  threadId: added.threadId,
361
510
  recipient: mail.from
362
511
  },
@@ -381,14 +530,17 @@ function emailChannelDefinition(options) {
381
530
  return skipped("limited");
382
531
  }
383
532
  if (resolution.status !== "existing" && resolution.status !== "created") return skipped(resolution.status === "refused" ? "refused" : "identity_unknown");
533
+ const participants = thread ? await membersOf([mail.from, ...mail.others], new Map([[mail.from, resolution.member.id]])) : void 0;
534
+ if (thread) await threadHistory(added.threadId, added.id, own);
384
535
  if (resolution.handled === true) {
385
536
  await recordHandledMessage(archive(), {
386
537
  chat: {
387
538
  channel: currentChannel("email"),
388
- chatId: emailChatId(added.threadId, mail.from),
539
+ chatId,
389
540
  threadId: added.threadId
390
541
  },
391
542
  memberId: resolution.member.id,
543
+ ...participants === void 0 ? {} : { participantIds: participants },
392
544
  senderId: mail.from,
393
545
  senderName: mail.fromName ?? null,
394
546
  messageId: added.id,
@@ -401,7 +553,11 @@ function emailChannelDefinition(options) {
401
553
  });
402
554
  return;
403
555
  }
404
- const auth = emailPrincipal(resolution.member, mail.from, added.threadId, mail.others);
556
+ const auth = emailPrincipal(resolution.member, mail.from, added.threadId, {
557
+ others: mail.others,
558
+ chatId,
559
+ ...participants === void 0 ? {} : { participants }
560
+ });
405
561
  const memberId = memberIdOf(auth);
406
562
  const inbound = mail.attachments.map((file, index) => ({
407
563
  key: `${added.id}:${index}`,
@@ -443,7 +599,7 @@ function emailChannelDefinition(options) {
443
599
  ...inbound.length === 0 ? {} : { store: {
444
600
  attachments: files(),
445
601
  memberId,
446
- chat: providerChat(currentChannel("email"), emailChatId(added.threadId, mail.from)),
602
+ chat: providerChat(currentChannel("email"), chatId),
447
603
  source: "email",
448
604
  sourceRef: (index) => `${added.threadId}:${added.id}:${index}`
449
605
  } }
@@ -471,7 +627,7 @@ function emailChannelDefinition(options) {
471
627
  text: ""
472
628
  }
473
629
  });
474
- await args.from(emailChatId(added.threadId, mail.from)).send(content, {
630
+ await args.from(chatId).send(content, {
475
631
  auth,
476
632
  idempotencyKey: currentKey("email", `email:${added.id}`),
477
633
  ...media.context.length === 0 ? {} : { context: media.context }
@@ -496,6 +652,27 @@ function emailChannelDefinition(options) {
496
652
  const mail = sentMail(parsed, own);
497
653
  if (mail.automated || parsed.headers.some((header) => header.key === REPLY_KEY_HEADER.toLowerCase()) || threadId === void 0 || mail.text === "" && mail.attachments.length === 0) return;
498
654
  const record = current.record === "all" && (current.recordQuery === void 0 || await finds(current.recordQuery, id, parsed.messageId)) ? "all" : "agent";
655
+ if (current.chats === "thread") {
656
+ if (record === "all") await threadHistory(threadId, id, own);
657
+ await recordSentOutside(archive(), {
658
+ provider: currentChannel("email"),
659
+ chatId: threadId,
660
+ threadId,
661
+ eventId: currentKey("email", `email:staff:${id}`),
662
+ participantIds: await membersOf(mail.recipients),
663
+ by: "human",
664
+ senderId: mail.fromAddress ?? null,
665
+ senderName: mail.fromName ?? null,
666
+ messageId: id,
667
+ text: mail.text,
668
+ files: mail.attachments.map((file) => ({
669
+ name: file.filename,
670
+ mimeType: file.contentType,
671
+ size: file.size
672
+ }))
673
+ }, { record });
674
+ return;
675
+ }
499
676
  for (const recipient of mail.recipients) await recordSentOutside(archive(), {
500
677
  provider: currentChannel("email"),
501
678
  chatId: emailChatId(threadId, recipient),
@@ -517,27 +694,30 @@ function emailChannelDefinition(options) {
517
694
  if (messageId === void 0) return false;
518
695
  return (await mailbox().search(`(${query}) rfc822msgid:${messageId.replace(/[<>"]/gu, "")}`, 5)).includes(id);
519
696
  }
520
- async function recordSkipped(current, message, mail, reason) {
697
+ async function recordSkipped(current, message, mail, reason, own) {
521
698
  if (current.record !== "all") return;
522
699
  const store = await storeOf(archive());
523
700
  if (store === void 0 || current.recordQuery !== void 0 && !await finds(current.recordQuery, message.id, mail.messageId)) return;
701
+ const thread = current.chats === "thread";
524
702
  const chat = {
525
703
  channel: currentChannel("email"),
526
- chatId: emailChatId(message.threadId, mail.from),
704
+ chatId: emailChatOf(current, message.threadId, mail.from),
527
705
  messageId: message.id
528
706
  };
529
707
  const unverified = reason === UNVERIFIED;
530
- const [latest] = unverified ? [] : (await archive().context({
708
+ const [latest] = unverified || thread ? [] : (await archive().context({
531
709
  provider: chat.channel,
532
710
  chatId: chat.chatId,
533
711
  threadId: message.threadId,
534
712
  limit: 1
535
713
  })).events;
714
+ const participants = unverified ? [] : thread ? await membersOf([mail.from, ...mail.others]) : latest?.participantIds ?? [];
715
+ if (thread) await threadHistory(message.threadId, message.id, own);
536
716
  await recordChatMessage(archive(), {
537
717
  provider: chat.channel,
538
718
  chatId: chat.chatId,
539
719
  threadId: message.threadId,
540
- participantIds: latest?.participantIds ?? [],
720
+ participantIds: participants,
541
721
  eventId: currentKey("email", `email:recorded:${message.id}`),
542
722
  direction: "inbound",
543
723
  by: reason === "automated" || reason === "bounce" ? "bot" : "human",
@@ -558,7 +738,7 @@ function emailChannelDefinition(options) {
558
738
  disposition: "skipped",
559
739
  reason
560
740
  });
561
- if (!unverified && (latest === void 0 || latest.participantIds.length === 0)) await reportUnadmittedChat({
741
+ if (!unverified && (thread || participants.length === 0)) await reportUnadmittedChat({
562
742
  identity: {
563
743
  provider: "email",
564
744
  externalId: mail.from,
@@ -568,7 +748,13 @@ function emailChannelDefinition(options) {
568
748
  ...mail.fromName === void 0 ? {} : { display: mail.fromName }
569
749
  },
570
750
  identities: people(),
571
- chat: {
751
+ chat: thread ? {
752
+ channel: chat.channel,
753
+ chatId: chat.chatId,
754
+ threadId: message.threadId,
755
+ shared: true,
756
+ ...mail.subject === "" ? {} : { title: mail.subject }
757
+ } : {
572
758
  channel: chat.channel,
573
759
  chatId: chat.chatId,
574
760
  threadId: message.threadId,
@@ -594,12 +780,12 @@ function emailChannelDefinition(options) {
594
780
  ...added,
595
781
  threadId: raw.threadId
596
782
  };
597
- const skipped = (reason) => recordSkipped(current, message, mail, reason);
783
+ const skipped = (reason) => recordSkipped(current, message, mail, reason, own);
598
784
  if (mail.skip === "no_sender" || mail.skip === "own_address") return;
599
785
  if (!mail.verified) return skipped(UNVERIFIED);
600
786
  if (mail.skip !== void 0) return skipped(mail.skip);
601
787
  if (!restarted && !await finds(current.query, added.id, mail.messageId)) return skipped("not_addressed");
602
- await dispatch(message, mail, args, skipped);
788
+ await dispatch(message, mail, args, skipped, current, own);
603
789
  }
604
790
  async function wake(request, args) {
605
791
  const current = settings();
@@ -776,6 +962,7 @@ function emailChannelDefinition(options) {
776
962
  }
777
963
  }))) return;
778
964
  const memberId = memberIdOf(principal);
965
+ const participantIds = participantsOf(principal) ?? (memberId === void 0 ? [] : [memberId]);
779
966
  const reply = {
780
967
  key: replyKeyOf(ctx.session.id, turnId),
781
968
  chatId: chat.chatId,
@@ -783,7 +970,7 @@ function emailChannelDefinition(options) {
783
970
  to: chat.peer,
784
971
  cc,
785
972
  text,
786
- participantIds: memberId === void 0 ? [] : [memberId],
973
+ participantIds,
787
974
  sessionId: ctx.session.id,
788
975
  turnId,
789
976
  at: new Date(now()).toISOString()
@@ -799,4 +986,4 @@ function emailChannelDefinition(options) {
799
986
  fetchFile: (url, context) => fetchStoredAttachment(files(), url, context)
800
987
  };
801
988
  }
802
- export { EMAIL_AUTHENTICATOR, EMAIL_OTHERS_ATTRIBUTE, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailPrincipal, replyCopies, segmentstreamEmail };
989
+ export { EMAIL_AUTHENTICATOR, EMAIL_OTHERS_ATTRIBUTE, EMAIL_ROUTE, MAXIMUM_CURSOR_LENGTH, emailChannelDefinition, emailChatId, emailChatOf, emailPrincipal, replyCopies, segmentstreamEmail };
@@ -64,6 +64,11 @@ export interface Gmail {
64
64
  readonly labelIds: ReadonlyArray<string>;
65
65
  readonly headers: ReadonlyMap<string, string>;
66
66
  }>;
67
+ /** A thread's messages, oldest first, by id with their labels, without headers or bodies. */
68
+ thread(threadId: string): Promise<ReadonlyArray<{
69
+ readonly id: string;
70
+ readonly labelIds: ReadonlyArray<string>;
71
+ }>>;
67
72
  /** Asks Gmail to push the mailbox's changes to `topic`; resolves the watch's expiry. */
68
73
  watch(topic: string): Promise<number>;
69
74
  /**
@@ -167,6 +167,17 @@ function gmail(proxy) {
167
167
  headers: found
168
168
  };
169
169
  },
170
+ async thread(threadId) {
171
+ if (!GMAIL_ID.test(threadId)) throw new GmailError("threads.get", 400);
172
+ const body = await ok("threads.get", "GET", `/threads/${threadId}?format=minimal&fields=messages(id,labelIds)`);
173
+ return (Array.isArray(body.messages) ? body.messages : []).flatMap((message) => {
174
+ const id = text(message.id);
175
+ return id === void 0 || !GMAIL_ID.test(id) ? [] : [{
176
+ id,
177
+ labelIds: Array.isArray(message.labelIds) ? message.labelIds.filter((label) => typeof label === "string") : []
178
+ }];
179
+ });
180
+ },
170
181
  async watch(topic) {
171
182
  const body = await ok("watch", "POST", "/watch", {
172
183
  topicName: topic,
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { appOrigin } from "./environment.mjs";
8
8
  import { runtimeToken } from "./runtime-token.mjs";
9
- import { ot as guestIdOf } from "../../_chunks/principal-C7aAjyt4.mjs";
9
+ import { ot as guestIdOf } from "../../_chunks/principal-CVV9C_nO.mjs";
10
10
  const GUEST_USAGE_PATH = "/api/ontology/agent/guests/usage";
11
11
  const REPORT_TIMEOUT_MS = 5e3;
12
12
  function ontologyGuestUsage(options = {}) {
@@ -148,6 +148,8 @@ export interface AgentIdentities {
148
148
  readonly kind?: "private";
149
149
  readonly recipient?: string;
150
150
  readonly threadId?: string;
151
+ /** A private chat several people write in, such as an email thread: no member leaves it. */
152
+ readonly shared?: true;
151
153
  }): Promise<AgentChat>;
152
154
  /**
153
155
  * Hands a person's private chat over to the workspace's staff, saying what they need. Undefined
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { f as attachmentsContext, p as storeFiles, m as turnContent } from "../../../_chunks/principal-C7aAjyt4.mjs";
7
+ export { f as attachmentsContext, p as storeFiles, m as turnContent } from "../../../_chunks/principal-CVV9C_nO.mjs";
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { f as attachmentsContext, d as prepareInboundMedia, p as storeFiles, m as turnContent } from "../../../_chunks/principal-C7aAjyt4.mjs";
7
+ export { f as attachmentsContext, d as prepareInboundMedia, p as storeFiles, m as turnContent } from "../../../_chunks/principal-CVV9C_nO.mjs";
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { R as ACT_AS_HEADER, w as actAsHeaders, T as ontologyConnection } from "../../_chunks/principal-C7aAjyt4.mjs";
7
+ export { R as ACT_AS_HEADER, w as actAsHeaders, T as ontologyConnection } from "../../_chunks/principal-CVV9C_nO.mjs";
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { F as confirmations, H as actorOf, I as inputHash, Ot as runtimeEnvelope, P as actionApproval, V as actorKey, j as ontologyTools } from "../../_chunks/principal-C7aAjyt4.mjs";
7
+ import { F as confirmations, H as actorOf, I as inputHash, Ot as runtimeEnvelope, P as actionApproval, V as actorKey, j as ontologyTools } from "../../_chunks/principal-CVV9C_nO.mjs";
8
8
  import { isChatPost } from "./chat-post-confirmation.mjs";
9
9
  import { sandboxFile } from "./sandbox-session.mjs";
10
10
  import { saveOntologyResult } from "./ontology-result-file.mjs";
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { E as OntologyActionNotPermitted, D as OntologyFileUnavailable, O as OntologyToolRejected, k as actionToolName, A as ontologyToolLabels, j as ontologyTools, M as promotionTarget } from "../../_chunks/principal-C7aAjyt4.mjs";
7
+ export { E as OntologyActionNotPermitted, D as OntologyFileUnavailable, O as OntologyToolRejected, k as actionToolName, A as ontologyToolLabels, j as ontologyTools, M as promotionTarget } from "../../_chunks/principal-CVV9C_nO.mjs";
@@ -15,6 +15,7 @@ function agentReviews(input) {
15
15
  to: reply.to,
16
16
  cc: reply.cc ?? []
17
17
  } : void 0;
18
+ const participants = reply.participants !== void 0 && reply.participants.some((id) => id !== reply.memberId) ? reply.participants : void 0;
18
19
  const send = async (named) => {
19
20
  try {
20
21
  return await fetchImpl(`${input.origin}/api/ontology/agent/reviews`, {
@@ -30,10 +31,11 @@ function agentReviews(input) {
30
31
  ...reply.channel === void 0 ? {} : { channel: reply.channel },
31
32
  chat_id: reply.chatId,
32
33
  recipient: reply.recipient,
33
- ...named === void 0 ? {} : {
34
- to: named.to,
35
- cc: named.cc
34
+ ...named.recipients === void 0 ? {} : {
35
+ to: named.recipients.to,
36
+ cc: named.recipients.cc
36
37
  },
38
+ ...named.participants === void 0 ? {} : { participants: named.participants },
37
39
  thread_id: reply.threadId,
38
40
  reply_to: reply.replyTo,
39
41
  member_id: reply.memberId,
@@ -53,10 +55,20 @@ function agentReviews(input) {
53
55
  });
54
56
  }
55
57
  };
56
- let response = await send(recipients);
57
- if (recipients !== void 0 && response.status === 400 && await namesRecipients(response)) {
58
- console.error("[segmentstream] reply held without its copies: the ontology predates them", { key: reply.key });
59
- response = await send(void 0);
58
+ let response = await send({
59
+ recipients,
60
+ participants
61
+ });
62
+ if (response.status === 400 && (recipients !== void 0 || participants !== void 0)) {
63
+ const refused = await refusedFields(response);
64
+ const withoutCopies = recipients !== void 0 && (refused.has("to") || refused.has("cc"));
65
+ const withoutReaders = participants !== void 0 && refused.has("participants");
66
+ if (withoutCopies) console.error("[segmentstream] reply held without its copies: the ontology predates them", { key: reply.key });
67
+ if (withoutReaders) console.error("[segmentstream] reply held without its readers: the ontology predates them", { key: reply.key });
68
+ if (withoutCopies || withoutReaders) response = await send({
69
+ recipients: withoutCopies ? void 0 : recipients,
70
+ participants: withoutReaders ? void 0 : participants
71
+ });
60
72
  }
61
73
  if (!response.ok) {
62
74
  const error = await refusal(response, "reply review");
@@ -70,15 +82,15 @@ function agentReviews(input) {
70
82
  }
71
83
  };
72
84
  }
73
- async function namesRecipients(response) {
85
+ async function refusedFields(response) {
74
86
  try {
75
87
  const body = await response.clone().json();
76
- return Array.isArray(body.issues) && body.issues.some((issue) => {
88
+ return new Set(Array.isArray(body.issues) ? body.issues.flatMap((issue) => {
77
89
  const path = issue?.path;
78
- return Array.isArray(path) && (path[0] === "to" || path[0] === "cc");
79
- });
90
+ return Array.isArray(path) && path.length > 0 ? [path[0]] : [];
91
+ }) : []);
80
92
  } catch {
81
- return false;
93
+ return new Set();
82
94
  }
83
95
  }
84
96
  function isRecord(value) {
@@ -35,6 +35,13 @@ export interface HeldReply {
35
35
  */
36
36
  readonly to?: ReadonlyArray<string>;
37
37
  readonly cc?: ReadonlyArray<string>;
38
+ /**
39
+ * A reply in a private chat several people share, such as an email thread: the members who read
40
+ * it in the chat's history, by user id, its member among them, as they read the message it
41
+ * answers. Approval delivers it to them as the agent's own send would. Absent where only its
42
+ * member reads it.
43
+ */
44
+ readonly participants?: ReadonlyArray<string>;
38
45
  /** The member the reply is for. */
39
46
  readonly memberId: string;
40
47
  readonly sessionId: string;
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { reviewFor } from "../../review.mjs";
8
- import { Pt as chatAddressOf, a as rolesOf, i as memberIdOf } from "../../../_chunks/principal-C7aAjyt4.mjs";
8
+ import { Bt as participantsOf, Ft as chatAddressOf, a as rolesOf, i as memberIdOf } from "../../../_chunks/principal-CVV9C_nO.mjs";
9
9
  function reviewOf(settings, principal) {
10
10
  return reviewFor(settings, rolesOf(principal));
11
11
  }
@@ -42,6 +42,7 @@ function heldReply(input) {
42
42
  const chat = chatAddressOf(input.principal);
43
43
  const memberId = memberIdOf(input.principal);
44
44
  const replyTo = input.principal?.attributes.replyToMessageId;
45
+ const participants = participantsOf(input.principal);
45
46
  if (chat === void 0 || memberId === void 0 || !holdsReplies(chat.provider)) return;
46
47
  return {
47
48
  key: `${input.sessionId}:${input.partId}`,
@@ -55,6 +56,7 @@ function heldReply(input) {
55
56
  to: input.recipients.to,
56
57
  cc: input.recipients.cc
57
58
  } : {},
59
+ ...participants === void 0 ? {} : { participants },
58
60
  memberId,
59
61
  sessionId: input.sessionId,
60
62
  text: input.text,
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { Ft as chatChannel, Pt as chatAddressOf, i as memberIdOf } from "../../../_chunks/principal-C7aAjyt4.mjs";
7
+ import { Ft as chatAddressOf, It as chatChannel, i as memberIdOf } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
8
  import { a as chatEvent, r as chatArchive } from "../../../_chunks/chat-archive-DavfKJDI.mjs";
9
9
  import { stampedChat } from "../chat-recorder.mjs";
10
10
  import { appOrigin } from "../environment.mjs";
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { a as rolesOf } from "../../_chunks/principal-C7aAjyt4.mjs";
7
+ import { a as rolesOf } from "../../_chunks/principal-CVV9C_nO.mjs";
8
8
  import { defineDynamic, defineSkill } from "eve/skills";
9
9
  function forRoles(roles, skill) {
10
10
  if (!Array.isArray(roles) || roles.length === 0 || !roles.every((role) => typeof role === "string" && role.trim() !== "")) throw new TypeError("forRoles() needs at least one role name; a skill for everyone is an ordinary skill file.");
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { wt as RUNTIME_SOURCE_PROTOCOL, Tt as compatibleRuntimeEnvelope, Et as principalRuntimeSource, Dt as readableRuntimeEnvelope, Ot as runtimeEnvelope, kt as telegramRuntimeSource } from "../../_chunks/principal-C7aAjyt4.mjs";
7
+ export { wt as RUNTIME_SOURCE_PROTOCOL, Tt as compatibleRuntimeEnvelope, Et as principalRuntimeSource, Dt as readableRuntimeEnvelope, Ot as runtimeEnvelope, kt as telegramRuntimeSource } from "../../_chunks/principal-CVV9C_nO.mjs";
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { Nt as SESSION_HEADER, R as ACT_AS_HEADER, _ as AttachmentError, jt as CHAT_HEADER, v as EARLIER_CHAT_HEADER } from "../../_chunks/principal-C7aAjyt4.mjs";
7
+ import { Pt as SESSION_HEADER, R as ACT_AS_HEADER, _ as AttachmentError, jt as CHAT_HEADER, v as EARLIER_CHAT_HEADER } from "../../_chunks/principal-CVV9C_nO.mjs";
8
8
  import { fetchFileGrant, transientFileStatus } from "./file-grant.mjs";
9
9
  var StoredFileError = class extends AttachmentError {
10
10
  filename;
@@ -8,7 +8,7 @@ import { admitMessage, localizedText } from "../admission.mjs";
8
8
  import { agentToolsAttribute } from "../agent-tools.mjs";
9
9
  import { agentChats, channelChats } from "../chats.mjs";
10
10
  import { withButtonDecision } from "../confirmation-buttons.mjs";
11
- import { b as agentAttachments, d as prepareInboundMedia, m as turnContent, zt as withChatAddress } from "../../../_chunks/principal-C7aAjyt4.mjs";
11
+ import { Vt as withChatAddress, b as agentAttachments, d as prepareInboundMedia, m as turnContent } from "../../../_chunks/principal-CVV9C_nO.mjs";
12
12
  import { channelAttributes, currentChannel, withNamedRoutes, withSessionChannels } from "../channel-scope.mjs";
13
13
  import { redactDiagnostic } from "../diagnostics.mjs";
14
14
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { _ as AttachmentError } from "../../../_chunks/principal-C7aAjyt4.mjs";
7
+ import { _ as AttachmentError } from "../../../_chunks/principal-CVV9C_nO.mjs";
8
8
  import { sendStoredAttachments } from "../attachments-send.mjs";
9
9
  import { MAXIMUM_PROXY_BODY_BYTES, connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";