@segmentstream/agent 0.54.0 → 0.55.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +10 -6
  3. package/dist/_chunks/{build-metadata-2TyBXJEt.mjs → build-metadata-CYSFZe6f.mjs} +1 -1
  4. package/dist/_chunks/{principal-DUla0Xge.mjs → principal-DIgU-kPR.mjs} +20 -8
  5. package/dist/extension/channels/email.d.ts +4 -3
  6. package/dist/extension/channels/email.mjs +2 -1
  7. package/dist/extension/channels/slack.d.ts +4 -3
  8. package/dist/extension/channels/slack.mjs +2 -1
  9. package/dist/extension/channels/telegram.d.ts +3 -1
  10. package/dist/extension/channels/telegram.mjs +2 -1
  11. package/dist/extension/channels/whatsapp.d.ts +3 -2
  12. package/dist/extension/channels/whatsapp.mjs +2 -1
  13. package/dist/extension/config.d.ts +165 -66
  14. package/dist/extension/config.mjs +137 -34
  15. package/dist/extension/connections/ontology.mjs +1 -1
  16. package/dist/extension/hooks/authorization.mjs +1 -1
  17. package/dist/extension/instructions/persona.mjs +1 -1
  18. package/dist/extension/lib/actor.mjs +1 -1
  19. package/dist/extension/lib/attachment-tools.d.ts +1 -1
  20. package/dist/extension/lib/attachment-tools.mjs +2 -2
  21. package/dist/extension/lib/attachments-send.mjs +1 -1
  22. package/dist/extension/lib/attachments.mjs +1 -1
  23. package/dist/extension/lib/build-metadata.mjs +1 -1
  24. package/dist/extension/lib/channel-scope.d.ts +67 -0
  25. package/dist/extension/lib/channel-scope.mjs +104 -0
  26. package/dist/extension/lib/chat-address.d.ts +18 -3
  27. package/dist/extension/lib/chat-address.mjs +1 -1
  28. package/dist/extension/lib/chat-archive.d.ts +6 -0
  29. package/dist/extension/lib/chat-archive.mjs +7 -2
  30. package/dist/extension/lib/chat-context.mjs +3 -3
  31. package/dist/extension/lib/chat-post-confirmation.d.ts +13 -2
  32. package/dist/extension/lib/chat-post-confirmation.mjs +8 -3
  33. package/dist/extension/lib/chat-recorder.d.ts +17 -0
  34. package/dist/extension/lib/chat-recorder.mjs +18 -9
  35. package/dist/extension/lib/chats.d.ts +7 -0
  36. package/dist/extension/lib/chats.mjs +31 -1
  37. package/dist/extension/lib/confirmations.mjs +1 -1
  38. package/dist/extension/lib/email/attachments-send.d.ts +1 -1
  39. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  40. package/dist/extension/lib/email/channel.d.ts +11 -3
  41. package/dist/extension/lib/email/channel.mjs +53 -42
  42. package/dist/extension/lib/guest-usage.mjs +1 -1
  43. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  44. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  45. package/dist/extension/lib/ontology-connection.mjs +1 -1
  46. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  47. package/dist/extension/lib/ontology-tools.mjs +1 -1
  48. package/dist/extension/lib/review/client.mjs +1 -0
  49. package/dist/extension/lib/review/hold.d.ts +7 -0
  50. package/dist/extension/lib/review/hold.mjs +2 -1
  51. package/dist/extension/lib/review/reply.mjs +3 -3
  52. package/dist/extension/lib/role-skill.mjs +1 -1
  53. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  54. package/dist/extension/lib/sent-files.mjs +1 -1
  55. package/dist/extension/lib/slack/adapter.d.ts +5 -4
  56. package/dist/extension/lib/slack/adapter.mjs +19 -15
  57. package/dist/extension/lib/slack/attachments-send.d.ts +1 -1
  58. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  59. package/dist/extension/lib/stored-files.mjs +1 -1
  60. package/dist/extension/lib/telegram/adapter.d.ts +8 -2
  61. package/dist/extension/lib/telegram/adapter.mjs +43 -31
  62. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  63. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  64. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  65. package/dist/extension/lib/telegram/chat-archive.mjs +11 -10
  66. package/dist/extension/lib/telegram/chat-post-card.mjs +4 -3
  67. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  68. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  69. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +2 -1
  70. package/dist/extension/lib/telegram/files.d.ts +4 -1
  71. package/dist/extension/lib/telegram/files.mjs +3 -2
  72. package/dist/extension/lib/telegram/health.mjs +1 -1
  73. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  74. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  75. package/dist/extension/lib/telegram/inbound.mjs +4 -4
  76. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  77. package/dist/extension/lib/telegram/principal.mjs +1 -1
  78. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  79. package/dist/extension/lib/telegram/signals.mjs +2 -1
  80. package/dist/extension/lib/telegram/silent.mjs +1 -1
  81. package/dist/extension/lib/telegram/structured.mjs +1 -1
  82. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  83. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  84. package/dist/extension/lib/web/auth.mjs +1 -1
  85. package/dist/extension/lib/web/channel.mjs +1 -1
  86. package/dist/extension/lib/whatsapp/adapter.d.ts +12 -6
  87. package/dist/extension/lib/whatsapp/adapter.mjs +17 -10
  88. package/dist/extension/lib/whatsapp/attachments-send.d.ts +1 -1
  89. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  90. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  91. package/dist/extension/lib/workspace-source.d.ts +1 -1
  92. package/dist/extension/lib/workspace-source.mjs +3 -2
  93. package/dist/extension/model.mjs +1 -1
  94. package/dist/extension/tools/attachments_discard.mjs +1 -1
  95. package/dist/extension/tools/attachments_list.mjs +1 -1
  96. package/dist/extension/tools/attachments_promote.mjs +1 -1
  97. package/dist/extension/tools/attachments_read.mjs +1 -1
  98. package/dist/extension/tools/attachments_send.mjs +10 -6
  99. package/dist/extension/tools/attachments_stage.mjs +1 -1
  100. package/dist/extension/tools/attachments_table.mjs +1 -1
  101. package/dist/extension/tools/questions_ask.mjs +1 -1
  102. package/dist/extension/tools/workspace_source.mjs +1 -1
  103. package/package.json +2 -2
@@ -5,9 +5,9 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { agentTaskIdOf } from "./agent-task.mjs";
8
- import { chatCoordinates } from "./chat-recorder.mjs";
8
+ import { chatCoordinates, sessionKind } from "./chat-recorder.mjs";
9
9
  import { chatArchive, collapseChatEvents, topicContext } from "./chat-archive.mjs";
10
- import { Ot as reportTelegramError } from "../../_chunks/principal-DUla0Xge.mjs";
10
+ import { kt as reportTelegramError } from "../../_chunks/principal-DIgU-kPR.mjs";
11
11
  import { createHash } from "node:crypto";
12
12
  import { deliveries, runs, turns } from "eve/events";
13
13
  import { defineState } from "eve/context";
@@ -145,7 +145,7 @@ function legacySince(context, turnId) {
145
145
  const CONTEXT_CHANNELS = new Set(["telegram", "email"]);
146
146
  function chatOf(context) {
147
147
  const coordinates = chatCoordinates(context);
148
- return coordinates === void 0 || !CONTEXT_CHANNELS.has(coordinates.provider) || agentTaskIdOf(context.session.auth.current) !== void 0 ? void 0 : coordinates;
148
+ return coordinates === void 0 || !CONTEXT_CHANNELS.has(sessionKind(context) ?? "") || agentTaskIdOf(context.session.auth.current) !== void 0 ? void 0 : coordinates;
149
149
  }
150
150
  function chatContextHook(archive = chatArchive()) {
151
151
  return {
@@ -4,11 +4,20 @@ export declare const CHAT_POST_PROTOCOL = "segmentstream/chat-post";
4
4
  export declare const CHAT_POST_ENVELOPE = "_segmentstream";
5
5
  /** The ontology's chat posting tool, without the connection's namespace. */
6
6
  export declare const CHAT_POST_TOOL = "chat_post_message";
7
- /** The providers whose chats this agent describes posts to; it refuses a destination elsewhere. */
7
+ /** The kinds of channel whose chats this agent describes posts to; it refuses one elsewhere. */
8
8
  export type ChatPostProvider = "telegram" | "slack" | "whatsapp";
9
9
  export interface ChatPostPreview {
10
10
  readonly chatId: string;
11
- readonly provider: ChatPostProvider;
11
+ /**
12
+ * The channel the destination is on, by its name, as the ontology's `chat_list` names it: its
13
+ * kind for the channel named after its kind, such as `telegram`.
14
+ */
15
+ readonly provider: string;
16
+ /**
17
+ * The kind of that channel, which decides how the message renders; `provider` when absent, as
18
+ * for a confirmation saved before channels had names.
19
+ */
20
+ readonly kind?: ChatPostProvider;
12
21
  readonly externalId: string;
13
22
  readonly title: string;
14
23
  readonly attribution: string;
@@ -19,6 +28,8 @@ export interface ChatPostPreview {
19
28
  }
20
29
  export declare function isChatPost(action: string): boolean;
21
30
  export declare function supportsChatPost(tool: Record<string, unknown>): boolean;
31
+ /** The kind of channel a preview's destination is on. */
32
+ export declare function chatPostKind(preview: ChatPostPreview): string;
22
33
  export declare function chatPostDigest(preview: ChatPostPreview): string;
23
34
  export declare function chatPostOperationId(sessionId: string, callId: string): string;
24
35
  export declare function describeChatPost(input: {
@@ -19,6 +19,9 @@ function isChatPost(action) {
19
19
  function supportsChatPost(tool) {
20
20
  return isChatPost(String(tool.name)) && object(tool._meta)["segmentstream/chat-post"] === 1;
21
21
  }
22
+ function chatPostKind(preview) {
23
+ return preview.kind ?? preview.provider;
24
+ }
22
25
  function chatPostDigest(preview) {
23
26
  return createHash("sha256").update(JSON.stringify([
24
27
  "v2",
@@ -39,6 +42,7 @@ function describeChatPost(input) {
39
42
  const { values, caller, destinations } = input;
40
43
  const items = Array.isArray(destinations.items) ? destinations.items.map(object) : [];
41
44
  const target = items[0];
45
+ const kind = target?.kind ?? target?.provider;
42
46
  if (Object.keys(values).some((key) => ![
43
47
  "chat",
44
48
  "text",
@@ -48,16 +52,17 @@ function describeChatPost(input) {
48
52
  target.title,
49
53
  target.external_id,
50
54
  caller.attribution
51
- ].every((value) => typeof value === "string" && value.length > 0) || target.provider !== "telegram" && target.provider !== "slack" && target.provider !== "whatsapp" || target.provider === "whatsapp" && values.reply_to !== void 0 || target.id !== values.chat && target.title !== values.chat) throw new Error("An unambiguous destination and a complete exact chat preview are required.");
55
+ ].every((value) => typeof value === "string" && value.length > 0) || typeof target.provider !== "string" || !target.provider || kind !== "telegram" && kind !== "slack" && kind !== "whatsapp" || kind === "whatsapp" && values.reply_to !== void 0 || target.id !== values.chat && target.title !== values.chat) throw new Error("An unambiguous destination and a complete exact chat preview are required.");
52
56
  const attribution = caller.attribution;
53
57
  const separator = typeof caller.attribution_separator === "string" ? caller.attribution_separator : "\n\n";
54
- const finalText = target.provider === "telegram" ? `${converter.fromMarkdown(values.text)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_` : target.provider === "slack" ? renderSlack(values.text, attribution, separator) : renderWhatsApp(values.text, attribution, separator);
58
+ const finalText = kind === "telegram" ? `${converter.fromMarkdown(values.text)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_` : kind === "slack" ? renderSlack(values.text, attribution, separator) : renderWhatsApp(values.text, attribution, separator);
55
59
  return {
56
60
  action: "",
57
61
  fields: [],
58
62
  chatPost: {
59
63
  chatId: target.id,
60
64
  provider: target.provider,
65
+ ...kind === target.provider ? {} : { kind },
61
66
  externalId: target.external_id,
62
67
  title: target.title,
63
68
  attribution,
@@ -68,4 +73,4 @@ function describeChatPost(input) {
68
73
  }
69
74
  };
70
75
  }
71
- export { CHAT_POST_ENVELOPE, CHAT_POST_PROTOCOL, CHAT_POST_TOOL, chatPostDigest, chatPostOperationId, describeChatPost, isChatPost, supportsChatPost };
76
+ export { CHAT_POST_ENVELOPE, CHAT_POST_PROTOCOL, CHAT_POST_TOOL, chatPostDigest, chatPostKind, chatPostOperationId, describeChatPost, isChatPost, supportsChatPost };
@@ -1,6 +1,23 @@
1
1
  import type { HookContext, HookEvent } from "eve/hooks";
2
2
  import { type ChatArchive } from "./chat-archive.js";
3
3
  type RuntimeContext = Pick<HookContext, "session" | "channel">;
4
+ /** Whether a hook's session is a Telegram channel's, which archives its own messages. */
5
+ export declare function isTelegram(context: {
6
+ readonly session: {
7
+ readonly auth: RuntimeContext["session"]["auth"];
8
+ };
9
+ readonly channel: RuntimeContext["channel"];
10
+ }): boolean;
11
+ /**
12
+ * The kind of channel a hook's session is on. Its coordinates name the channel, which for a channel
13
+ * not named after its kind is its name, not its kind.
14
+ */
15
+ export declare function sessionKind(context: {
16
+ readonly session: {
17
+ readonly auth: RuntimeContext["session"]["auth"];
18
+ };
19
+ readonly channel: RuntimeContext["channel"];
20
+ }): string | undefined;
4
21
  export declare function chatCoordinates(context: {
5
22
  readonly session: {
6
23
  readonly auth: RuntimeContext["session"]["auth"];
@@ -7,11 +7,18 @@ __eveCreateRequire(import.meta.url);
7
7
  import { n as contentText, t as CONTENT_CAPS } from "../../_chunks/content-cDtVnr8Y.mjs";
8
8
  import { chatArchive, chatEvent, sessionFailureEventId, summarizeArguments } from "./chat-archive.mjs";
9
9
  import { agentTaskIdOf } from "./agent-task.mjs";
10
- import { gt as chatAddressOf, i as memberIdOf, ot as guestIdOf } from "../../_chunks/principal-DUla0Xge.mjs";
10
+ import { _t as chatChannel, gt as chatAddressOf, i as memberIdOf, ot as guestIdOf } from "../../_chunks/principal-DIgU-kPR.mjs";
11
+ import { keyChannel, principalChannel } from "./channel-scope.mjs";
11
12
  import { parseAddress } from "./telegram/sessions.mjs";
12
13
  import { completionKind } from "./telegram/silent.mjs";
13
14
  import { recordModelServiceAlert } from "./model-service-alert.mjs";
14
15
  import { call } from "eve/events";
16
+ function isTelegram(context) {
17
+ return context.session.auth.current?.authenticator === "segmentstream-telegram" || context.channel.kind?.includes("telegram") === true;
18
+ }
19
+ function sessionKind(context) {
20
+ return isTelegram(context) ? "telegram" : chatAddressOf(context.session.auth.current)?.provider;
21
+ }
15
22
  function chatCoordinates(context) {
16
23
  const principal = context.session.auth.current;
17
24
  const taskId = agentTaskIdOf(principal);
@@ -43,26 +50,28 @@ function chatCoordinates(context) {
43
50
  senderId: `guest:${guestId}`
44
51
  };
45
52
  if (chat?.provider === "email" && webMemberId !== void 0) return {
46
- provider: "email",
53
+ provider: chatChannel(chat),
47
54
  chatId: chat.chatId,
48
55
  chatType: "private",
49
56
  threadId: chat.threadId === "" ? null : chat.threadId,
50
57
  participantIds: [webMemberId],
51
58
  senderId: chat.peer ?? null
52
59
  };
53
- const telegram = principal?.authenticator === "segmentstream-telegram" || context.channel.kind?.includes("telegram");
60
+ const telegram = isTelegram(context);
54
61
  const address = context.channel.continuationToken;
55
62
  const attributes = principal?.attributes;
56
63
  const fields = address?.split(":");
57
- const localAddress = telegram && fields?.length === 4 ? fields.slice(1).join(":") : address;
64
+ const namespaced = telegram && fields?.length === 4 ? fields.slice(1).join(":") : address;
65
+ const localAddress = telegram && namespaced !== void 0 ? keyChannel("telegram", namespaced).key : namespaced;
58
66
  const parsed = telegram && localAddress !== void 0 && /^-?\d+:\d*:\d*$/u.test(localAddress) ? parseAddress(localAddress) : void 0;
59
67
  const attributeChatId = typeof attributes?.chatId === "string" && (!telegram || /^-?\d+$/u.test(attributes.chatId)) ? attributes.chatId : void 0;
60
- const chatId = telegram ? parsed?.chatId ?? attributeChatId : attributeChatId !== void 0 ? attributeChatId : address;
68
+ const channelAddress = chat?.channel !== void 0 && address !== void 0 ? address.replace(`${chat.channel}/`, "") : address;
69
+ const chatId = telegram ? parsed?.chatId ?? attributeChatId : attributeChatId !== void 0 ? attributeChatId : channelAddress;
61
70
  if (!chatId) return;
62
71
  const memberId = memberIdOf(principal);
63
72
  const chatType = attributes?.chatType;
64
73
  return {
65
- provider: telegram ? "telegram" : context.channel.kind ?? "eve",
74
+ provider: (telegram ? principalChannel(principal) : chat?.channel) ?? (telegram ? "telegram" : context.channel.kind ?? "eve"),
66
75
  chatId,
67
76
  chatType: chatType === "group" || chatType === "supergroup" || chatType === void 0 && telegram && chatId.startsWith("-") ? "group" : chatType === "channel" ? "channel" : "private",
68
77
  threadId: !telegram ? null : parsed !== void 0 ? parsed.messageThreadId || null : typeof attributes?.messageThreadId === "string" ? attributes.messageThreadId : null,
@@ -173,7 +182,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
173
182
  phase: event.data.phase
174
183
  })
175
184
  }));
176
- if (!RECORDS_REPLIES.has(coordinates.provider) && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
185
+ if (!RECORDS_REPLIES.has(sessionKind(context) ?? "") && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
177
186
  ...base,
178
187
  eventId: `${eventId}:outbound`,
179
188
  kind: "outbound",
@@ -182,7 +191,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
182
191
  senderIsBot: true,
183
192
  status: "completed"
184
193
  }));
185
- } else if (event.type === "delivery.consumed" && coordinates.provider !== "telegram") await archive.append(chatEvent({
194
+ } else if (event.type === "delivery.consumed" && !isTelegram(context)) await archive.append(chatEvent({
186
195
  ...base,
187
196
  eventId,
188
197
  kind: "inbound",
@@ -201,4 +210,4 @@ function resultErrorMessage(output) {
201
210
  if (output !== null && typeof output === "object" && "message" in output && typeof output.message === "string") return output.message;
202
211
  return null;
203
212
  }
204
- export { chatCoordinates, chatRecorder };
213
+ export { chatCoordinates, chatRecorder, isTelegram, sessionKind };
@@ -1,4 +1,5 @@
1
1
  import { type AgentChat, type AgentIdentities } from "./identities.js";
2
+ import type { ChannelKind } from "../config.js";
2
3
  /** How long a chat's report stands before the next message reports it again. */
3
4
  export declare const REPORT_INTERVAL_MS: number;
4
5
  export declare const REPORT_FAILURE_THRESHOLD = 3;
@@ -72,5 +73,11 @@ export declare function agentChats(input: {
72
73
  readonly logError?: (message: string, error: unknown) => void;
73
74
  readonly logRecovery?: (message: string, detail: unknown) => void;
74
75
  }): AgentChats;
76
+ /**
77
+ * The chat registry of every channel of `kind`, each reporting its chats under its own name, as
78
+ * the registry keys them: a report reaches the registry of the channel the current request runs
79
+ * for. Health covers them all.
80
+ */
81
+ export declare function channelChats(kind: ChannelKind, create: (provider: string) => AgentChats): AgentChats;
75
82
  /** The registry's facts as turn context: only the fields it holds. */
76
83
  export declare function chatContext(chat: AgentChat | undefined): ReadonlyArray<string>;
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { AgentIdentityError } from "./identities.mjs";
8
8
  import { redactDiagnostic } from "./diagnostics.mjs";
9
+ import { currentChannel } from "./channel-scope.mjs";
9
10
  const MAXIMUM_WHEN_TO_USE_LENGTH = 1e3;
10
11
  const REPORT_INTERVAL_MS = 6e5;
11
12
  const REPORT_FAILURE_THRESHOLD = 3;
@@ -192,6 +193,35 @@ function agentChats(input) {
192
193
  }
193
194
  };
194
195
  }
196
+ function channelChats(kind, create) {
197
+ const registries = new Map();
198
+ const current = () => {
199
+ const name = currentChannel(kind);
200
+ let registry = registries.get(name);
201
+ if (registry === void 0) {
202
+ registry = create(name);
203
+ registries.set(name, registry);
204
+ }
205
+ return registry;
206
+ };
207
+ return {
208
+ joined: (report) => current().joined(report),
209
+ seen: (report) => current().seen(report),
210
+ left: (report) => current().left(report),
211
+ agentLeft: (report) => current().agentLeft(report),
212
+ migrated: (report) => current().migrated(report),
213
+ chat: (chatId) => current().chat(chatId),
214
+ health() {
215
+ const all = [...registries.values()].map((registry) => registry.health());
216
+ return {
217
+ failureThreshold: 3,
218
+ totalFailures: all.reduce((sum, health) => sum + health.totalFailures, 0),
219
+ degraded: all.some((health) => health.degraded),
220
+ chats: all.flatMap((health) => health.chats)
221
+ };
222
+ }
223
+ };
224
+ }
195
225
  function chatContext(chat) {
196
226
  if (chat === void 0) return [];
197
227
  const lines = ["<chat>", `title: ${chat.title}`];
@@ -200,4 +230,4 @@ function chatContext(chat) {
200
230
  lines.push("</chat>");
201
231
  return [lines.join("\n")];
202
232
  }
203
- export { REPORT_FAILURE_THRESHOLD, REPORT_INTERVAL_MS, agentChats, chatContext };
233
+ export { REPORT_FAILURE_THRESHOLD, REPORT_INTERVAL_MS, agentChats, channelChats, chatContext };
@@ -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 { N as CONFIRMATION_TTL_MS, P as actionApproval, F as confirmations, I as inputHash, L as needsConfirmation } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ export { N as CONFIRMATION_TTL_MS, P as actionApproval, F as confirmations, I as inputHash, L as needsConfirmation } from "../../_chunks/principal-DIgU-kPR.mjs";
@@ -32,7 +32,7 @@ export declare function sendEmailAttachments(options: {
32
32
  readonly sessionId: string;
33
33
  /** The tool call: with the session, it names the reply in the thread. */
34
34
  readonly callId: string;
35
- /** The workspace's `channels.email.connection`. */
35
+ /** The connection of the email channel the chat is on, such as `channels.email.connection`. */
36
36
  readonly connection: string | undefined;
37
37
  readonly environment?: Environment;
38
38
  readonly token?: RuntimeToken;
@@ -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-DUla0Xge.mjs";
7
+ import { _ as AttachmentError } from "../../../_chunks/principal-DIgU-kPR.mjs";
8
8
  import { sendStoredAttachments } from "../attachments-send.mjs";
9
9
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
10
10
  import { redactDiagnostic } from "../diagnostics.mjs";
@@ -26,8 +26,12 @@ import { type Gmail } from "./gmail.js";
26
26
  * `failed`. One Gmail does not take for a while waits there, out of the 16 KiB cursor, and each
27
27
  * wake tries the replies still waiting, finding by its key one an earlier attempt sent. Mail staff
28
28
  * send from the mailbox in a thread where the agent has a chat joins that chat as their message.
29
+ *
30
+ * Every channel of kind `email` is served here: `channels.email` at {@link EMAIL_ROUTE}, and a
31
+ * channel of another name, such as `support_mail`, at `{@link EMAIL_ROUTE}/support_mail`, each on
32
+ * its own mailbox and with its name in its chats' keys.
29
33
  */
30
- /** Where SegmentStream wakes the channel. */
34
+ /** Where SegmentStream wakes the channel named `email`; another email channel adds its name. */
31
35
  export declare const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
32
36
  /** The authenticator of an email session's principal. */
33
37
  export declare const EMAIL_AUTHENTICATOR = "segmentstream-email";
@@ -37,7 +41,8 @@ export declare const EMAIL_AUTHENTICATOR = "segmentstream-email";
37
41
  */
38
42
  export declare const MAXIMUM_CURSOR_LENGTH = 16384;
39
43
  export interface EmailChannelOptions {
40
- readonly settings: () => EmailSettings | null;
44
+ /** The settings of the email channel `name`, or null when there is no such email channel. */
45
+ readonly settings: (name: string) => EmailSettings | null;
41
46
  readonly admission: () => AdmissionSettings;
42
47
  readonly models?: () => SegmentStreamAgentConfig["models"];
43
48
  readonly review?: {
@@ -70,7 +75,10 @@ export interface EmailChannelOptions {
70
75
  * write in the same thread have a chat and a session each, as replies reach only their sender.
71
76
  */
72
77
  export declare function emailChatId(threadId: string, sender: string): string;
73
- /** The principal of an email session: the member who writes from the address. */
78
+ /**
79
+ * The principal of an email session: the member who writes from the address, on the email channel
80
+ * the current wake runs for.
81
+ */
74
82
  export declare function emailPrincipal(member: PairedMember, sender: string, threadId: string): SessionAuthContext;
75
83
  /** The email channel of the extension. */
76
84
  export declare function segmentstreamEmail(options: EmailChannelOptions): Channel;
@@ -8,7 +8,8 @@ import { PUBSUB_TOPIC } from "../../config.mjs";
8
8
  import { admitMessage, localizedText } from "../admission.mjs";
9
9
  import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
11
- import { S as fetchStoredAttachment, b as agentAttachments, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent, yt as withChatAddress } from "../../../_chunks/principal-DUla0Xge.mjs";
11
+ import { S as fetchStoredAttachment, b as agentAttachments, bt as withChatAddress, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent } from "../../../_chunks/principal-DIgU-kPR.mjs";
12
+ import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
12
13
  import { chatArchive, chatEvent, replyEvent } from "../chat-archive.mjs";
13
14
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
14
15
  import { redactDiagnostic } from "../diagnostics.mjs";
@@ -130,6 +131,7 @@ function emailChatId(threadId, sender) {
130
131
  return `${threadId}:${sender}`;
131
132
  }
132
133
  function emailPrincipal(member, sender, threadId) {
134
+ const channel = currentChannel("email");
133
135
  return withChatAddress({
134
136
  authenticator: EMAIL_AUTHENTICATOR,
135
137
  issuer: "email",
@@ -142,10 +144,12 @@ function emailPrincipal(member, sender, threadId) {
142
144
  roles: member.roles,
143
145
  ...agentToolsAttribute(member.agentTools),
144
146
  ...member.name === null ? {} : { memberName: member.name },
145
- ...member.locale === void 0 ? {} : { locale: member.locale }
147
+ ...member.locale === void 0 ? {} : { locale: member.locale },
148
+ ...channelAttributes("email", channel)
146
149
  }
147
150
  }, {
148
151
  provider: "email",
152
+ ...channel === "email" ? {} : { channel },
149
153
  chatId: emailChatId(threadId, sender),
150
154
  threadId,
151
155
  kind: "private",
@@ -183,7 +187,7 @@ function emailChannelDefinition(options) {
183
187
  let capabilities;
184
188
  let reviewed;
185
189
  let chats = options.archive ?? options.review?.archive;
186
- const settings = () => options.settings();
190
+ const settings = () => options.settings(currentChannel("email"));
187
191
  const mailbox = () => options.gmail ?? gmail(() => {
188
192
  const connection = settings()?.connection;
189
193
  if (connection === void 0) throw new Error("The email channel is not configured in agent/segmentstream.json.");
@@ -242,7 +246,8 @@ function emailChannelDefinition(options) {
242
246
  try {
243
247
  await archive().append(replyEvent({
244
248
  key: reply.key,
245
- provider: "email",
249
+ kind: "email",
250
+ provider: currentChannel("email"),
246
251
  chatId: reply.chatId,
247
252
  threadId: reply.threadId,
248
253
  participantIds: reply.participantIds,
@@ -289,7 +294,7 @@ function emailChannelDefinition(options) {
289
294
  if (store.pendingReplies === void 0) return false;
290
295
  try {
291
296
  page = await store.pendingReplies({
292
- provider: "email",
297
+ provider: currentChannel("email"),
293
298
  limit: REPLIES_PER_WAKE,
294
299
  requestedBefore: new Date(startedAt - REPLY_WAKE_AFTER_MS).toISOString()
295
300
  });
@@ -397,7 +402,7 @@ function emailChannelDefinition(options) {
397
402
  ...inbound.length === 0 ? {} : { store: {
398
403
  attachments: files(),
399
404
  memberId,
400
- chat: providerChat("email", emailChatId(added.threadId, mail.from)),
405
+ chat: providerChat(currentChannel("email"), emailChatId(added.threadId, mail.from)),
401
406
  source: "email",
402
407
  sourceRef: (index) => `${added.threadId}:${added.id}:${index}`
403
408
  } }
@@ -427,7 +432,7 @@ function emailChannelDefinition(options) {
427
432
  });
428
433
  await args.from(emailChatId(added.threadId, mail.from)).send(content, {
429
434
  auth,
430
- idempotencyKey: `email:${added.id}`,
435
+ idempotencyKey: currentKey("email", `email:${added.id}`),
431
436
  ...media.context.length === 0 ? {} : { context: media.context }
432
437
  });
433
438
  }
@@ -452,15 +457,15 @@ function emailChannelDefinition(options) {
452
457
  for (const recipient of mail.recipients) {
453
458
  const chatId = emailChatId(threadId, recipient);
454
459
  const held = (await archive().context({
455
- provider: "email",
460
+ provider: currentChannel("email"),
456
461
  chatId,
457
462
  threadId,
458
463
  limit: 1
459
464
  })).events[0];
460
465
  if (held === void 0) continue;
461
466
  await archive().append(chatEvent({
462
- eventId: `email:staff:${id}:${recipient}`,
463
- provider: "email",
467
+ eventId: currentKey("email", `email:staff:${id}:${recipient}`),
468
+ provider: currentChannel("email"),
464
469
  chatId,
465
470
  threadId,
466
471
  chatType: "private",
@@ -509,12 +514,15 @@ function emailChannelDefinition(options) {
509
514
  async function wake(request, args) {
510
515
  const current = settings();
511
516
  const secret = webhookSecret(environment);
517
+ const name = currentChannel("email");
512
518
  if (!channelsEnabled(environment) || current === null || secret === void 0) return new Response(null, { status: 404 });
513
519
  const body = await request.text();
514
520
  if (!signed(secret, body, request.headers.get("x-hub-signature-256"))) return Response.json({ error: "invalid_signature" }, { status: 401 });
515
521
  let requested;
516
522
  try {
517
- requested = JSON.parse(body).cursor;
523
+ const parsed = JSON.parse(body);
524
+ if (parsed.channel === void 0 ? name !== "email" : parsed.channel !== name) return Response.json({ error: "invalid_request" }, { status: 400 });
525
+ requested = parsed.cursor;
518
526
  } catch {
519
527
  return Response.json({ error: "invalid_request" }, { status: 400 });
520
528
  }
@@ -657,38 +665,41 @@ function emailChannelDefinition(options) {
657
665
  return Response.json({ error: "unavailable" }, { status: 503 });
658
666
  }
659
667
  }
668
+ const events = inHandlerChannels("email", { async "turn.settled"(event, ctx) {
669
+ const { outcome, turnId } = event.data;
670
+ const principal = ctx.session.auth.current;
671
+ const chat = chatAddressOf(principal);
672
+ if (outcome !== "completed" || chat?.provider !== "email" || chat.peer === void 0) return;
673
+ const text = replyText(ctx.view, turnId);
674
+ if (completionKind(text) !== "reply") return;
675
+ const reviewing = review()?.review;
676
+ if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
677
+ principal,
678
+ sessionId: ctx.session.id,
679
+ turnId,
680
+ partId: turnId,
681
+ text
682
+ }))) return;
683
+ const memberId = memberIdOf(principal);
684
+ const reply = {
685
+ key: replyKeyOf(ctx.session.id, turnId),
686
+ chatId: chat.chatId,
687
+ threadId: chat.threadId,
688
+ to: chat.peer,
689
+ text,
690
+ participantIds: memberId === void 0 ? [] : [memberId],
691
+ sessionId: ctx.session.id,
692
+ turnId,
693
+ at: new Date(now()).toISOString()
694
+ };
695
+ await record(reply, "requested");
696
+ await send(reply, REPLY_ATTEMPTS);
697
+ } });
660
698
  return {
661
- routes: [POST(EMAIL_ROUTE, wake)],
662
- events: { async "turn.settled"(event, ctx) {
663
- const { outcome, turnId } = event.data;
664
- const principal = ctx.session.auth.current;
665
- const chat = chatAddressOf(principal);
666
- if (outcome !== "completed" || chat?.provider !== "email" || chat.peer === void 0) return;
667
- const text = replyText(ctx.view, turnId);
668
- if (completionKind(text) !== "reply") return;
669
- const reviewing = review()?.review;
670
- if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
671
- principal,
672
- sessionId: ctx.session.id,
673
- turnId,
674
- partId: turnId,
675
- text
676
- }))) return;
677
- const memberId = memberIdOf(principal);
678
- const reply = {
679
- key: replyKeyOf(ctx.session.id, turnId),
680
- chatId: chat.chatId,
681
- threadId: chat.threadId,
682
- to: chat.peer,
683
- text,
684
- participantIds: memberId === void 0 ? [] : [memberId],
685
- sessionId: ctx.session.id,
686
- turnId,
687
- at: new Date(now()).toISOString()
688
- };
689
- await record(reply, "requested");
690
- await send(reply, REPLY_ATTEMPTS);
691
- } },
699
+ routes: withNamedRoutes("email", [POST(EMAIL_ROUTE, wake)], (name) => {
700
+ return options.settings(name) !== null;
701
+ }),
702
+ events,
692
703
  fetchFile: (url, context) => fetchStoredAttachment(files(), url, context)
693
704
  };
694
705
  }
@@ -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-DUla0Xge.mjs";
9
+ import { ot as guestIdOf } from "../../_chunks/principal-DIgU-kPR.mjs";
10
10
  const GUEST_USAGE_PATH = "/api/ontology/agent/guests/usage";
11
11
  const REPORT_TIMEOUT_MS = 5e3;
12
12
  function ontologyGuestUsage(options = {}) {
@@ -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-DUla0Xge.mjs";
7
+ export { f as attachmentsContext, p as storeFiles, m as turnContent } from "../../../_chunks/principal-DIgU-kPR.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-DUla0Xge.mjs";
7
+ export { f as attachmentsContext, d as prepareInboundMedia, p as storeFiles, m as turnContent } from "../../../_chunks/principal-DIgU-kPR.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-DUla0Xge.mjs";
7
+ export { R as ACT_AS_HEADER, w as actAsHeaders, T as ontologyConnection } from "../../_chunks/principal-DIgU-kPR.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, P as actionApproval, Pt as runtimeEnvelope, V as actorKey, j as ontologyTools } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ import { F as confirmations, Ft as runtimeEnvelope, H as actorOf, I as inputHash, P as actionApproval, V as actorKey, j as ontologyTools } from "../../_chunks/principal-DIgU-kPR.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-DUla0Xge.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-DIgU-kPR.mjs";
@@ -23,6 +23,7 @@ function agentReviews(input) {
23
23
  body: JSON.stringify({
24
24
  key: reply.key,
25
25
  provider: reply.provider,
26
+ ...reply.channel === void 0 ? {} : { channel: reply.channel },
26
27
  chat_id: reply.chatId,
27
28
  recipient: reply.recipient,
28
29
  thread_id: reply.threadId,
@@ -9,6 +9,13 @@ export interface HeldReply {
9
9
  /** Names the reply, so a report repeated after a failure creates one review. */
10
10
  readonly key: string;
11
11
  readonly provider: "telegram" | "slack" | "whatsapp" | "email";
12
+ /**
13
+ * The channel the chat is on, by name, when it is not the one named after its kind: approval
14
+ * sends the reply through its connection in the ontology's `chat`. Absent for the channel named
15
+ * after its kind, as before channels had names, so an ontology service that knows no names holds
16
+ * its replies, and refuses those of another channel.
17
+ */
18
+ readonly channel?: string;
12
19
  readonly chatId: string;
13
20
  /**
14
21
  * Whom the provider sends the reply to: the person's own id in their private chat, where
@@ -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 { a as rolesOf, gt as chatAddressOf, i as memberIdOf } from "../../../_chunks/principal-DUla0Xge.mjs";
8
+ import { a as rolesOf, gt as chatAddressOf, i as memberIdOf } from "../../../_chunks/principal-DIgU-kPR.mjs";
9
9
  function reviewOf(settings, principal) {
10
10
  return reviewFor(settings, rolesOf(principal));
11
11
  }
@@ -48,6 +48,7 @@ function heldReply(input) {
48
48
  return {
49
49
  key: `${input.sessionId}:${input.partId}`,
50
50
  provider: chat.provider,
51
+ ...chat.channel === void 0 ? {} : { channel: chat.channel },
51
52
  chatId: chat.chatId,
52
53
  recipient: chat.kind === "private" && chat.peer !== void 0 ? chat.peer : chat.chatId,
53
54
  threadId: chat.threadId,
@@ -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 { gt as chatAddressOf, i as memberIdOf } from "../../../_chunks/principal-DUla0Xge.mjs";
7
+ import { _t as chatChannel, gt as chatAddressOf, i as memberIdOf } from "../../../_chunks/principal-DIgU-kPR.mjs";
8
8
  import { chatArchive, chatEvent } from "../chat-archive.mjs";
9
9
  import { appOrigin } from "../environment.mjs";
10
10
  import { agentReviews } from "./client.mjs";
@@ -29,7 +29,7 @@ function replyReview(options) {
29
29
  if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
30
30
  const chat = chatAddressOf(input.principal);
31
31
  const coordinates = chat === void 0 ? void 0 : {
32
- provider: chat.provider,
32
+ provider: chatChannel(chat),
33
33
  chatId: chat.chatId,
34
34
  threadId: chat.threadId === "" ? null : chat.threadId
35
35
  };
@@ -110,7 +110,7 @@ function withReviewedReplies(channel, review, archive) {
110
110
  const memberId = memberIdOf(principal);
111
111
  if (chat !== void 0) await archive().append(chatEvent({
112
112
  eventId: `review:${context.session.id}:${event.data.partId}:outbound`,
113
- provider: chat.provider,
113
+ provider: chatChannel(chat),
114
114
  chatId: chat.chatId,
115
115
  chatType: chat.kind === "group" ? "group" : "private",
116
116
  threadId: chat.threadId === "" ? null : chat.threadId,