@segmentstream/agent 0.54.0 → 0.56.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 (114) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +12 -6
  3. package/dist/_chunks/{build-metadata-2TyBXJEt.mjs → build-metadata-DqDm9a2E.mjs} +1 -1
  4. package/dist/_chunks/{principal-DUla0Xge.mjs → principal-TJ6zB2rF.mjs} +24 -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 +212 -66
  14. package/dist/extension/config.mjs +196 -34
  15. package/dist/extension/connections/ontology.mjs +1 -1
  16. package/dist/extension/extension.d.ts +7 -1
  17. package/dist/extension/extension.mjs +2 -1
  18. package/dist/extension/hooks/authorization.mjs +1 -1
  19. package/dist/extension/instructions/persona.mjs +1 -1
  20. package/dist/extension/lib/actor.mjs +1 -1
  21. package/dist/extension/lib/attachment-tools.d.ts +1 -1
  22. package/dist/extension/lib/attachment-tools.mjs +2 -2
  23. package/dist/extension/lib/attachments-send.mjs +1 -1
  24. package/dist/extension/lib/attachments.d.ts +1 -1
  25. package/dist/extension/lib/attachments.mjs +1 -1
  26. package/dist/extension/lib/build-metadata.mjs +1 -1
  27. package/dist/extension/lib/channel-scope.d.ts +67 -0
  28. package/dist/extension/lib/channel-scope.mjs +104 -0
  29. package/dist/extension/lib/chat-address.d.ts +27 -4
  30. package/dist/extension/lib/chat-address.mjs +1 -1
  31. package/dist/extension/lib/chat-archive.d.ts +16 -0
  32. package/dist/extension/lib/chat-archive.mjs +22 -2
  33. package/dist/extension/lib/chat-context.mjs +3 -3
  34. package/dist/extension/lib/chat-post-confirmation.d.ts +14 -3
  35. package/dist/extension/lib/chat-post-confirmation.mjs +9 -3
  36. package/dist/extension/lib/chat-recorder.d.ts +17 -0
  37. package/dist/extension/lib/chat-recorder.mjs +24 -11
  38. package/dist/extension/lib/chats.d.ts +7 -0
  39. package/dist/extension/lib/chats.mjs +31 -1
  40. package/dist/extension/lib/confirmations.mjs +1 -1
  41. package/dist/extension/lib/email/attachments-send.d.ts +1 -1
  42. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  43. package/dist/extension/lib/email/channel.d.ts +11 -3
  44. package/dist/extension/lib/email/channel.mjs +53 -42
  45. package/dist/extension/lib/guest-usage.mjs +1 -1
  46. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  47. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  48. package/dist/extension/lib/ontology-connection.mjs +1 -1
  49. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  50. package/dist/extension/lib/ontology-tools.mjs +1 -1
  51. package/dist/extension/lib/review/client.mjs +1 -0
  52. package/dist/extension/lib/review/hold.d.ts +8 -1
  53. package/dist/extension/lib/review/hold.mjs +4 -2
  54. package/dist/extension/lib/review/reply.mjs +3 -3
  55. package/dist/extension/lib/role-skill.mjs +1 -1
  56. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  57. package/dist/extension/lib/sent-files.mjs +1 -1
  58. package/dist/extension/lib/slack/adapter.d.ts +5 -4
  59. package/dist/extension/lib/slack/adapter.mjs +19 -15
  60. package/dist/extension/lib/slack/attachments-send.d.ts +1 -1
  61. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  62. package/dist/extension/lib/stored-files.mjs +1 -1
  63. package/dist/extension/lib/telegram/adapter.d.ts +8 -2
  64. package/dist/extension/lib/telegram/adapter.mjs +43 -31
  65. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  66. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  67. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  68. package/dist/extension/lib/telegram/chat-archive.mjs +11 -10
  69. package/dist/extension/lib/telegram/chat-post-card.mjs +4 -3
  70. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  71. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  72. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +2 -1
  73. package/dist/extension/lib/telegram/files.d.ts +4 -1
  74. package/dist/extension/lib/telegram/files.mjs +3 -2
  75. package/dist/extension/lib/telegram/health.mjs +1 -1
  76. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  77. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  78. package/dist/extension/lib/telegram/inbound.mjs +4 -4
  79. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  80. package/dist/extension/lib/telegram/principal.mjs +1 -1
  81. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  82. package/dist/extension/lib/telegram/signals.mjs +2 -1
  83. package/dist/extension/lib/telegram/silent.mjs +1 -1
  84. package/dist/extension/lib/telegram/structured.mjs +1 -1
  85. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  86. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  87. package/dist/extension/lib/web/auth.mjs +1 -1
  88. package/dist/extension/lib/web/channel.mjs +1 -1
  89. package/dist/extension/lib/whatsapp/adapter.d.ts +12 -6
  90. package/dist/extension/lib/whatsapp/adapter.mjs +17 -10
  91. package/dist/extension/lib/whatsapp/attachments-send.d.ts +1 -1
  92. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  93. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  94. package/dist/extension/lib/workspace-channel/attachments-send.d.ts +35 -0
  95. package/dist/extension/lib/workspace-channel/attachments-send.mjs +119 -0
  96. package/dist/extension/lib/workspace-channel/channel.d.ts +229 -0
  97. package/dist/extension/lib/workspace-channel/channel.mjs +525 -0
  98. package/dist/extension/lib/workspace-channel/connection.d.ts +55 -0
  99. package/dist/extension/lib/workspace-channel/connection.mjs +68 -0
  100. package/dist/extension/lib/workspace-channel/secrets.d.ts +32 -0
  101. package/dist/extension/lib/workspace-channel/secrets.mjs +55 -0
  102. package/dist/extension/lib/workspace-source.d.ts +1 -1
  103. package/dist/extension/lib/workspace-source.mjs +3 -2
  104. package/dist/extension/model.mjs +1 -1
  105. package/dist/extension/tools/attachments_discard.mjs +1 -1
  106. package/dist/extension/tools/attachments_list.mjs +1 -1
  107. package/dist/extension/tools/attachments_promote.mjs +1 -1
  108. package/dist/extension/tools/attachments_read.mjs +1 -1
  109. package/dist/extension/tools/attachments_send.mjs +15 -7
  110. package/dist/extension/tools/attachments_stage.mjs +1 -1
  111. package/dist/extension/tools/attachments_table.mjs +1 -1
  112. package/dist/extension/tools/questions_ask.mjs +1 -1
  113. package/dist/extension/tools/workspace_source.mjs +1 -1
  114. package/package.json +2 -2
@@ -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-TJ6zB2rF.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);
@@ -42,27 +49,29 @@ function chatCoordinates(context) {
42
49
  participantIds: [],
43
50
  senderId: `guest:${guestId}`
44
51
  };
45
- if (chat?.provider === "email" && webMemberId !== void 0) return {
46
- provider: "email",
52
+ if ((chat?.provider === "email" || chat?.provider === "custom") && webMemberId !== void 0) return {
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,
@@ -70,7 +79,11 @@ function chatCoordinates(context) {
70
79
  senderId: principal?.subject ?? null
71
80
  };
72
81
  }
73
- const RECORDS_REPLIES = new Set(["telegram", "email"]);
82
+ const RECORDS_REPLIES = new Set([
83
+ "telegram",
84
+ "email",
85
+ "custom"
86
+ ]);
74
87
  const UNADDRESSED_SESSIONS_REMEMBERED = 1e3;
75
88
  function reportUnaddressed(event, context, reported) {
76
89
  const sessionId = context.session.id;
@@ -173,7 +186,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
173
186
  phase: event.data.phase
174
187
  })
175
188
  }));
176
- if (!RECORDS_REPLIES.has(coordinates.provider) && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
189
+ if (!RECORDS_REPLIES.has(sessionKind(context) ?? "") && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
177
190
  ...base,
178
191
  eventId: `${eventId}:outbound`,
179
192
  kind: "outbound",
@@ -182,7 +195,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
182
195
  senderIsBot: true,
183
196
  status: "completed"
184
197
  }));
185
- } else if (event.type === "delivery.consumed" && coordinates.provider !== "telegram") await archive.append(chatEvent({
198
+ } else if (event.type === "delivery.consumed" && !isTelegram(context)) await archive.append(chatEvent({
186
199
  ...base,
187
200
  eventId,
188
201
  kind: "inbound",
@@ -201,4 +214,4 @@ function resultErrorMessage(output) {
201
214
  if (output !== null && typeof output === "object" && "message" in output && typeof output.message === "string") return output.message;
202
215
  return null;
203
216
  }
204
- export { chatCoordinates, chatRecorder };
217
+ 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-TJ6zB2rF.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-TJ6zB2rF.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-TJ6zB2rF.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-TJ6zB2rF.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-TJ6zB2rF.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-TJ6zB2rF.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-TJ6zB2rF.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, H as actorOf, I as inputHash, It as runtimeEnvelope, P as actionApproval, V as actorKey, j as ontologyTools } from "../../_chunks/principal-TJ6zB2rF.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-TJ6zB2rF.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,
@@ -8,7 +8,14 @@ import { type ReviewSettings, type Review } from "../../review.js";
8
8
  export interface HeldReply {
9
9
  /** Names the reply, so a report repeated after a failure creates one review. */
10
10
  readonly key: string;
11
- readonly provider: "telegram" | "slack" | "whatsapp" | "email";
11
+ readonly provider: "telegram" | "slack" | "whatsapp" | "email" | "custom";
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,14 +5,15 @@ 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-TJ6zB2rF.mjs";
9
9
  function reviewOf(settings, principal) {
10
10
  return reviewFor(settings, rolesOf(principal));
11
11
  }
12
12
  const REVIEWED_PROVIDERS = new Set([
13
13
  "telegram",
14
14
  "whatsapp",
15
- "email"
15
+ "email",
16
+ "custom"
16
17
  ]);
17
18
  function repliesReviewed(settings, principal) {
18
19
  const provider = chatAddressOf(principal)?.provider;
@@ -48,6 +49,7 @@ function heldReply(input) {
48
49
  return {
49
50
  key: `${input.sessionId}:${input.partId}`,
50
51
  provider: chat.provider,
52
+ ...chat.channel === void 0 ? {} : { channel: chat.channel },
51
53
  chatId: chat.chatId,
52
54
  recipient: chat.kind === "private" && chat.peer !== void 0 ? chat.peer : chat.chatId,
53
55
  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-TJ6zB2rF.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,
@@ -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-DUla0Xge.mjs";
7
+ import { a as rolesOf } from "../../_chunks/principal-TJ6zB2rF.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 { jt as RUNTIME_SOURCE_PROTOCOL, Mt as compatibleRuntimeEnvelope, Nt as principalRuntimeSource, Pt as runtimeEnvelope, Ft as telegramRuntimeSource } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ export { Nt as RUNTIME_SOURCE_PROTOCOL, Pt as compatibleRuntimeEnvelope, Ft as principalRuntimeSource, It as runtimeEnvelope, Lt as telegramRuntimeSource } from "../../_chunks/principal-TJ6zB2rF.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 { R as ACT_AS_HEADER, _ as AttachmentError, ht as SESSION_HEADER, mt as CHAT_HEADER, v as EARLIER_CHAT_HEADER } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ import { R as ACT_AS_HEADER, _ as AttachmentError, ht as SESSION_HEADER, mt as CHAT_HEADER, v as EARLIER_CHAT_HEADER } from "../../_chunks/principal-TJ6zB2rF.mjs";
8
8
  import { fetchFileGrant, transientFileStatus } from "./file-grant.mjs";
9
9
  var StoredFileError = class extends AttachmentError {
10
10
  filename;
@@ -18,7 +18,8 @@ import { type RuntimeToken } from "../runtime-token.js";
18
18
  /**
19
19
  * The SegmentStream Slack channel (`agent-design.md`, "Channels"): eve's Slack channel at
20
20
  * `POST /eve/v1/slack`, for the Slack app SegmentStream created for the workspace's
21
- * `SlackConnection`. The app sends its events, interactions and slash commands to SegmentStream,
21
+ * `SlackConnection` that `channels.slack` names, and at `POST /eve/segmentstream/v1/slack/<name>`
22
+ * for the app of every other channel of kind `slack`. The app sends its events, interactions and slash commands to SegmentStream,
22
23
  * which checks them with the app's signing secret and relays them here signed as Slack signs, with
23
24
  * the project's `SEGMENTSTREAM_AGENT_WEBHOOK_SECRET`. Every Web API call and file download goes
24
25
  * through the connection proxy, which adds the bot token: no Slack credential enters this process.
@@ -45,8 +46,8 @@ export declare class SlackProxyRouteError extends Error {
45
46
  readonly name = "SlackProxyRouteError";
46
47
  }
47
48
  export interface SlackChannelOptions {
48
- /** The mounted `channels.slack`, or `null` when the workspace has no Slack channel. */
49
- readonly settings: () => SlackSettings | null;
49
+ /** The Slack channel `name` the mount declares, or `null` when it declares no such channel. */
50
+ readonly settings: (name: string) => SlackSettings | null;
50
51
  readonly admission: () => AdmissionSettings;
51
52
  /**
52
53
  * The workspace's group routing. In `mention` mode a reply in a followed thread reaches the
@@ -59,7 +60,7 @@ export interface SlackChannelOptions {
59
60
  readonly fetch?: typeof fetch;
60
61
  /** The ontology's pairing routes; tests pass a fake. */
61
62
  readonly identities?: AgentIdentities;
62
- /** The chat registry the channels are reported to; tests pass their own. */
63
+ /** The chat registry the channels are reported to, for every Slack channel; tests pass their own. */
63
64
  readonly chats?: AgentChats;
64
65
  /** Where members' files are stored as attachments; tests pass their own. */
65
66
  readonly attachments?: AgentAttachments;