@segmentstream/agent 0.53.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 (114) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +21 -8
  3. package/dist/_chunks/{build-metadata-Bc9qfC4D.mjs → build-metadata-CYSFZe6f.mjs} +1 -1
  4. package/dist/_chunks/{principal-JoaOmdFL.mjs → principal-DIgU-kPR.mjs} +71 -29
  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 +188 -67
  14. package/dist/extension/config.mjs +173 -36
  15. package/dist/extension/connections/ontology.mjs +1 -1
  16. package/dist/extension/hooks/authorization.mjs +1 -1
  17. package/dist/extension/hooks/guest-usage.d.ts +3 -0
  18. package/dist/extension/hooks/guest-usage.mjs +11 -0
  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 -2
  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 -1
  30. package/dist/extension/lib/chat-address.mjs +1 -1
  31. package/dist/extension/lib/chat-archive.d.ts +6 -0
  32. package/dist/extension/lib/chat-archive.mjs +7 -2
  33. package/dist/extension/lib/chat-context.mjs +3 -3
  34. package/dist/extension/lib/chat-post-confirmation.d.ts +13 -2
  35. package/dist/extension/lib/chat-post-confirmation.mjs +8 -3
  36. package/dist/extension/lib/chat-recorder.d.ts +17 -0
  37. package/dist/extension/lib/chat-recorder.mjs +18 -9
  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.d.ts +6 -1
  41. package/dist/extension/lib/confirmations.mjs +1 -1
  42. package/dist/extension/lib/email/attachments-send.d.ts +1 -1
  43. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  44. package/dist/extension/lib/email/channel.d.ts +11 -3
  45. package/dist/extension/lib/email/channel.mjs +53 -42
  46. package/dist/extension/lib/guest-usage.d.ts +53 -0
  47. package/dist/extension/lib/guest-usage.mjs +52 -0
  48. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  49. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  50. package/dist/extension/lib/ontology-connection.mjs +1 -1
  51. package/dist/extension/lib/ontology-file-call.mjs +2 -1
  52. package/dist/extension/lib/ontology-tools.d.ts +2 -0
  53. package/dist/extension/lib/ontology-tools.mjs +1 -1
  54. package/dist/extension/lib/review/client.mjs +1 -0
  55. package/dist/extension/lib/review/hold.d.ts +7 -0
  56. package/dist/extension/lib/review/hold.mjs +2 -1
  57. package/dist/extension/lib/review/reply.mjs +3 -3
  58. package/dist/extension/lib/role-skill.mjs +1 -1
  59. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  60. package/dist/extension/lib/sent-files.mjs +1 -1
  61. package/dist/extension/lib/slack/adapter.d.ts +5 -4
  62. package/dist/extension/lib/slack/adapter.mjs +19 -15
  63. package/dist/extension/lib/slack/attachments-send.d.ts +1 -1
  64. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  65. package/dist/extension/lib/stored-files.mjs +1 -1
  66. package/dist/extension/lib/telegram/adapter.d.ts +8 -2
  67. package/dist/extension/lib/telegram/adapter.mjs +43 -31
  68. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  69. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  70. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  71. package/dist/extension/lib/telegram/chat-archive.mjs +11 -10
  72. package/dist/extension/lib/telegram/chat-post-card.mjs +4 -3
  73. package/dist/extension/lib/telegram/confirmations.mjs +3 -3
  74. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  75. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +2 -1
  76. package/dist/extension/lib/telegram/files.d.ts +4 -1
  77. package/dist/extension/lib/telegram/files.mjs +3 -2
  78. package/dist/extension/lib/telegram/health.mjs +1 -1
  79. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  80. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  81. package/dist/extension/lib/telegram/inbound.mjs +4 -4
  82. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  83. package/dist/extension/lib/telegram/principal.mjs +1 -1
  84. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  85. package/dist/extension/lib/telegram/signals.mjs +2 -1
  86. package/dist/extension/lib/telegram/silent.mjs +1 -1
  87. package/dist/extension/lib/telegram/structured.mjs +1 -1
  88. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  89. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  90. package/dist/extension/lib/web/auth.d.ts +18 -4
  91. package/dist/extension/lib/web/auth.mjs +1 -1
  92. package/dist/extension/lib/web/channel.mjs +1 -1
  93. package/dist/extension/lib/whatsapp/adapter.d.ts +12 -6
  94. package/dist/extension/lib/whatsapp/adapter.mjs +17 -10
  95. package/dist/extension/lib/whatsapp/attachments-send.d.ts +1 -1
  96. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  97. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  98. package/dist/extension/lib/workspace-source.d.ts +1 -1
  99. package/dist/extension/lib/workspace-source.mjs +3 -2
  100. package/dist/extension/model.mjs +1 -1
  101. package/dist/extension/tools/attachments_discard.mjs +1 -1
  102. package/dist/extension/tools/attachments_list.mjs +1 -1
  103. package/dist/extension/tools/attachments_promote.mjs +1 -1
  104. package/dist/extension/tools/attachments_read.mjs +1 -1
  105. package/dist/extension/tools/attachments_send.mjs +10 -6
  106. package/dist/extension/tools/attachments_stage.mjs +1 -1
  107. package/dist/extension/tools/attachments_table.mjs +1 -1
  108. package/dist/extension/tools/questions_ask.mjs +1 -1
  109. package/dist/extension/tools/unanswered.d.ts +2 -0
  110. package/dist/extension/tools/unanswered.mjs +39 -0
  111. package/dist/extension/tools/workspace_source.mjs +1 -1
  112. package/dist/tools/index.d.ts +1 -0
  113. package/dist/tools/index.mjs +2 -1
  114. package/package.json +2 -2
@@ -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 };
@@ -19,8 +19,13 @@ export interface ActionAnnotations {
19
19
  /** Safety comes from the authenticated ontology, never from the name or model prose. */
20
20
  export declare function needsConfirmation(labels: ActionAnnotations): boolean;
21
21
  export declare function inputHash(input: unknown): string;
22
+ /**
23
+ * A confirmation requested by a member, or by a guest whom the ontology lets confirm: only they
24
+ * may confirm or cancel it. A member's names `memberId`; a guest's names `guestId` alone.
25
+ */
22
26
  export interface Confirmation {
23
- readonly memberId: string;
27
+ readonly memberId?: string;
28
+ readonly guestId?: string;
24
29
  readonly action: string;
25
30
  readonly inputHash: string;
26
31
  readonly expiresAt: number;
@@ -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 CONFIRMATION_TTL_MS, I as actionApproval, L as confirmations, R as inputHash, z as needsConfirmation } from "../../_chunks/principal-JoaOmdFL.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-JoaOmdFL.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 agentAttachments, d as prepareInboundMedia, gt as withChatAddress, i as memberIdOf, m as turnContent, mt as chatAddressOf, w as fetchStoredAttachment } from "../../../_chunks/principal-JoaOmdFL.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
  }
@@ -0,0 +1,53 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import type { AdmissionLimitsInput } from "../config.js";
3
+ import { type Environment } from "./environment.js";
4
+ import { type RuntimeToken } from "./runtime-token.js";
5
+ /**
6
+ * A guest's spend: the model cost of their turns, which the ontology holds against the agent's
7
+ * `limits.guest.usdPerDay` and `workspaceUsdPerDay` before their next turn. The agent reports each
8
+ * model answer's cost as the runtime records it (`usage.recorded`), so a turn's answers add up to
9
+ * the turn's cost, and a turn that fails or is cancelled is counted too, since the provider billed it.
10
+ */
11
+ /** Where the agent reports a guest's spend, with the deployment's runtime token. */
12
+ export declare const GUEST_USAGE_PATH = "/api/ontology/agent/guests/usage";
13
+ /** One report: the guest, what an answer cost, and a key that names the report once. */
14
+ export interface GuestUsage {
15
+ readonly guestId: string;
16
+ readonly costUsd: number;
17
+ readonly key: string;
18
+ }
19
+ export type GuestUsageReport = (usage: GuestUsage) => Promise<void>;
20
+ /** The ontology's spend route, called with the deployment's runtime token. Throws on a refusal. */
21
+ export declare function ontologyGuestUsage(options?: {
22
+ readonly environment?: Environment;
23
+ readonly token?: RuntimeToken;
24
+ readonly fetch?: typeof fetch;
25
+ }): GuestUsageReport;
26
+ /** Whether the agent's limits cap guests' spend, so that their turns' cost is worth reporting. */
27
+ export declare function capsGuestSpend(limits: AdmissionLimitsInput | undefined): boolean;
28
+ /**
29
+ * The handler of `usage.recorded` that reports a guest's model cost: only in a guest's session,
30
+ * only for an answer whose cost the provider reported, and only while the agent caps guests' spend.
31
+ * `key` is the event's place in the session's stream, so a handler run again reports nothing twice.
32
+ * A report that fails never fails the turn; the guest's next turns are still counted.
33
+ */
34
+ export declare function guestUsageHandler(options: {
35
+ readonly limits: () => AdmissionLimitsInput | undefined;
36
+ readonly report?: GuestUsageReport;
37
+ }): (event: {
38
+ readonly data: {
39
+ readonly usage: {
40
+ readonly costUsd?: number;
41
+ };
42
+ };
43
+ }, context: {
44
+ readonly session: {
45
+ readonly id: string;
46
+ readonly auth: {
47
+ readonly current: SessionAuthContext | null;
48
+ };
49
+ };
50
+ readonly occurrence: {
51
+ readonly idempotencyKey: string;
52
+ };
53
+ }) => Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { appOrigin } from "./environment.mjs";
8
+ import { runtimeToken } from "./runtime-token.mjs";
9
+ import { ot as guestIdOf } from "../../_chunks/principal-DIgU-kPR.mjs";
10
+ const GUEST_USAGE_PATH = "/api/ontology/agent/guests/usage";
11
+ const REPORT_TIMEOUT_MS = 5e3;
12
+ function ontologyGuestUsage(options = {}) {
13
+ return async ({ guestId, costUsd, key }) => {
14
+ const response = await (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}${GUEST_USAGE_PATH}`, {
15
+ method: "POST",
16
+ headers: {
17
+ authorization: `Bearer ${await (options.token ?? runtimeToken)()}`,
18
+ "content-type": "application/json"
19
+ },
20
+ body: JSON.stringify({
21
+ guest_id: guestId,
22
+ cost_usd: costUsd,
23
+ key
24
+ }),
25
+ signal: AbortSignal.timeout(REPORT_TIMEOUT_MS)
26
+ });
27
+ response.body?.cancel().catch(() => void 0);
28
+ if (!response.ok) throw new Error(`The ontology did not record a guest's spend (${response.status}).`);
29
+ };
30
+ }
31
+ function capsGuestSpend(limits) {
32
+ return limits?.guest?.usdPerDay !== void 0 || limits?.guest?.workspaceUsdPerDay !== void 0;
33
+ }
34
+ function guestUsageHandler(options) {
35
+ let report = options.report;
36
+ return async (event, context) => {
37
+ const guestId = guestIdOf(context.session.auth.current);
38
+ const costUsd = event.data.usage.costUsd;
39
+ if (guestId === void 0 || costUsd === void 0 || !Number.isFinite(costUsd) || costUsd <= 0 || !capsGuestSpend(options.limits())) return;
40
+ report ??= ontologyGuestUsage();
41
+ try {
42
+ await report({
43
+ guestId,
44
+ costUsd,
45
+ key: `${context.session.id}:${context.occurrence.idempotencyKey}`.slice(0, 256)
46
+ });
47
+ } catch (error) {
48
+ console.warn("A guest's spend could not be reported to the ontology.", error);
49
+ }
50
+ };
51
+ }
52
+ export { GUEST_USAGE_PATH, capsGuestSpend, guestUsageHandler, ontologyGuestUsage };
@@ -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-JoaOmdFL.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-JoaOmdFL.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 { B as ACT_AS_HEADER, E as actAsHeaders, D as ontologyConnection } from "../../_chunks/principal-JoaOmdFL.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 { I as actionApproval, L as confirmations, N as ontologyTools, R as inputHash, U as actorKey, W as actorOf, jt as runtimeEnvelope } from "../../_chunks/principal-JoaOmdFL.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";
@@ -173,6 +173,7 @@ function ontologyFileCall(texts) {
173
173
  if (saved.saveResult && (await ontologyTools({ principal: ctx.session.auth.current }).labels(actor, saved.name, saved.arguments)).readOnlyHint !== true) throw new Error("Saving a result requires a permitted read-only ontology tool.");
174
174
  const result = await ontologyTools({
175
175
  principal: ctx.session.auth.current,
176
+ sessionId: ctx.session.id,
176
177
  envelope: runtimeEnvelope({
177
178
  principal: ctx.session.auth.current,
178
179
  sessionId: ctx.session.id,
@@ -46,6 +46,8 @@ export declare function ontologyTools(options?: {
46
46
  * by the clients of one caller.
47
47
  */
48
48
  readonly runtimeSources?: Map<string, boolean>;
49
+ /** The agent session the calls are made in, which the ontology keeps with their chat. */
50
+ readonly sessionId?: string;
49
51
  }): {
50
52
  rpc: (actor: OntologyActor, method: string, params: Record<string, unknown>, signal?: AbortSignal) => Promise<Record<string, unknown>>;
51
53
  supportsRuntimeSource(actor: OntologyActor, signal?: AbortSignal): Promise<boolean>;
@@ -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 { O as OntologyActionNotPermitted, k as OntologyFileUnavailable, A as OntologyToolRejected, j as actionToolName, M as ontologyToolLabels, N as ontologyTools, P as promotionTarget } from "../../_chunks/principal-JoaOmdFL.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, i as memberIdOf, mt as chatAddressOf } from "../../../_chunks/principal-JoaOmdFL.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 { i as memberIdOf, mt as chatAddressOf } from "../../../_chunks/principal-JoaOmdFL.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,
@@ -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-JoaOmdFL.mjs";
7
+ import { a as rolesOf } from "../../_chunks/principal-DIgU-kPR.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 { Ot as RUNTIME_SOURCE_PROTOCOL, kt as compatibleRuntimeEnvelope, At as principalRuntimeSource, jt as runtimeEnvelope, Mt as telegramRuntimeSource } from "../../_chunks/principal-JoaOmdFL.mjs";
7
+ export { Mt as RUNTIME_SOURCE_PROTOCOL, Nt as compatibleRuntimeEnvelope, Pt as principalRuntimeSource, Ft as runtimeEnvelope, It as telegramRuntimeSource } 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 { B as ACT_AS_HEADER, _ as AttachmentError, v as CHAT_HEADER, x as SESSION_HEADER, y as EARLIER_CHAT_HEADER } from "../../_chunks/principal-JoaOmdFL.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-DIgU-kPR.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;