@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
@@ -49,7 +49,39 @@ const ADMISSION_REPLY_KEYS = [
49
49
  "groupPairingRequired",
50
50
  "refused"
51
51
  ];
52
+ const CHANNEL_KINDS = [
53
+ "telegram",
54
+ "whatsapp",
55
+ "slack",
56
+ "email"
57
+ ];
58
+ const CHANNEL_NAME = /^[a-z][a-z0-9_]{0,31}$/;
59
+ const RESERVED_CHANNEL_NAMES = ["web", "task"];
60
+ const MAXIMUM_CHANNELS = 20;
61
+ function isChannelKind(value) {
62
+ return CHANNEL_KINDS.some((kind) => kind === value);
63
+ }
52
64
  const SESSION_SCOPES = ["chat", "thread"];
65
+ function declaredChannels(channels) {
66
+ if (channels === null || channels === void 0 || typeof channels !== "object") return [];
67
+ const entries = Object.entries(channels).flatMap(([name, value]) => {
68
+ if (!isRecord(value) || typeof value.connection !== "string") return [];
69
+ const kind = value.kind ?? name;
70
+ if (!isChannelKind(kind) || isChannelKind(name) && name !== kind) return [];
71
+ return [{
72
+ name,
73
+ kind,
74
+ settings: Object.fromEntries(Object.entries(value).filter(([key]) => key !== "kind"))
75
+ }];
76
+ });
77
+ return [...CHANNEL_KINDS.flatMap((kind) => entries.filter((entry) => entry.name === kind)), ...entries.filter((entry) => !isChannelKind(entry.name))];
78
+ }
79
+ function channelsOfKind(channels, kind) {
80
+ return declaredChannels(channels).filter((channel) => channel.kind === kind);
81
+ }
82
+ function channelOf(channels, kind, name) {
83
+ return channelsOfKind(channels, kind).find((channel) => channel.name === name)?.settings ?? null;
84
+ }
53
85
  const IGNORED_SESSION_KEYS = [
54
86
  "compactAt",
55
87
  "timezone",
@@ -149,12 +181,11 @@ function section(input) {
149
181
  function isTelegramPolicy(value) {
150
182
  return TELEGRAM_POLICIES.some((policy) => policy === value);
151
183
  }
152
- function whatsappSettings(value, issues) {
153
- const path = ["channels", "whatsapp"];
184
+ function whatsappSettings(value, issues, path = ["channels", "whatsapp"]) {
154
185
  const whatsapp = section({
155
186
  value,
156
187
  path,
157
- allowed: ["connection"],
188
+ allowed: ["connection", "kind"],
158
189
  issues
159
190
  });
160
191
  if (whatsapp === void 0) return null;
@@ -167,12 +198,11 @@ function whatsappSettings(value, issues) {
167
198
  }
168
199
  return { connection: whatsapp.connection };
169
200
  }
170
- function slackSettings(value, issues) {
171
- const path = ["channels", "slack"];
201
+ function slackSettings(value, issues, path = ["channels", "slack"]) {
172
202
  const slack = section({
173
203
  value,
174
204
  path,
175
- allowed: ["connection"],
205
+ allowed: ["connection", "kind"],
176
206
  issues
177
207
  });
178
208
  if (slack === void 0) return null;
@@ -232,13 +262,13 @@ function webSettings(value, issues) {
232
262
  });
233
263
  return issues.length > before ? null : { domains };
234
264
  }
235
- function emailSettings(value, issues) {
236
- const path = ["channels", "email"];
265
+ function emailSettings(value, issues, path = ["channels", "email"]) {
237
266
  const email = section({
238
267
  value,
239
268
  path,
240
269
  allowed: [
241
270
  "connection",
271
+ "kind",
242
272
  "query",
243
273
  "checkAfterMinutes",
244
274
  "push"
@@ -283,14 +313,14 @@ function emailSettings(value, issues) {
283
313
  push: push === void 0 ? null : { topic: push.topic }
284
314
  };
285
315
  }
286
- function telegramSettings(value, issues) {
287
- const path = ["channels", "telegram"];
316
+ function telegramSettings(value, issues, path = ["channels", "telegram"]) {
288
317
  const telegram = section({
289
318
  value,
290
319
  path,
291
320
  allowed: [
292
321
  "connection",
293
- "policy",
322
+ "kind",
323
+ ...path.at(-1) === "telegram" ? ["policy"] : [],
294
324
  "groups",
295
325
  "linkPreviews",
296
326
  "additionalOwnOrigins",
@@ -343,10 +373,19 @@ function telegramSettings(value, issues) {
343
373
  path: [...path, "additionalOwnOrigins"]
344
374
  });
345
375
  const appLinks = telegram.appLinks === void 0 ? "web" : telegram.appLinks;
376
+ const miniApp = path.at(-1) === "telegram";
346
377
  if (!TELEGRAM_APP_LINKS.some((mode) => mode === appLinks)) issues.push({
347
378
  message: "must be \"web\" or \"miniApp\"",
348
379
  path: [...path, "appLinks"]
349
380
  });
381
+ else if (appLinks === "miniApp" && !miniApp) issues.push({
382
+ message: "must be \"web\": only the bot of channels.telegram opens the app as a Mini App",
383
+ path: [...path, "appLinks"]
384
+ });
385
+ if (telegram.menuButton !== void 0 && !miniApp) issues.push({
386
+ message: "is only for channels.telegram, whose bot opens the app as a Mini App",
387
+ path: [...path, "menuButton"]
388
+ });
350
389
  const interimMessages = telegram.interimMessages === void 0 ? false : telegram.interimMessages;
351
390
  if (typeof interimMessages !== "boolean") issues.push({
352
391
  message: "must be true or false",
@@ -431,6 +470,82 @@ function telegramSettings(value, issues) {
431
470
  } }
432
471
  } : null;
433
472
  }
473
+ function channelSettings(channels, issues) {
474
+ const result = {
475
+ telegram: telegramSettings(channels?.telegram, issues),
476
+ whatsapp: whatsappSettings(channels?.whatsapp, issues),
477
+ slack: slackSettings(channels?.slack, issues),
478
+ email: emailSettings(channels?.email, issues)
479
+ };
480
+ for (const kind of CHANNEL_KINDS) {
481
+ const value = channels?.[kind];
482
+ if (isRecord(value) && value.kind !== void 0 && value.kind !== kind) issues.push({
483
+ message: `must be "${kind}": a channel named after a kind is that kind; give another name to a channel of another kind`,
484
+ path: [
485
+ "channels",
486
+ kind,
487
+ "kind"
488
+ ]
489
+ });
490
+ }
491
+ for (const [name, value] of Object.entries(channels ?? {})) {
492
+ if (isChannelKind(name)) continue;
493
+ const path = ["channels", name];
494
+ if (!CHANNEL_NAME.test(name)) {
495
+ issues.push({
496
+ message: "must be a channel name: a lower-case letter, then up to 31 lower-case letters, digits or _",
497
+ path
498
+ });
499
+ continue;
500
+ }
501
+ if (RESERVED_CHANNEL_NAMES.includes(name)) {
502
+ issues.push({
503
+ message: "is a name the platform keeps its own chats under; choose another",
504
+ path
505
+ });
506
+ continue;
507
+ }
508
+ if (!isRecord(value)) {
509
+ issues.push({
510
+ message: "must be an object",
511
+ path
512
+ });
513
+ continue;
514
+ }
515
+ const kind = value.kind;
516
+ if (!isChannelKind(kind)) {
517
+ issues.push({
518
+ message: `must name the channel's kind: ${CHANNEL_KINDS.join(", ")}`,
519
+ path: [...path, "kind"]
520
+ });
521
+ continue;
522
+ }
523
+ const settings = kind === "telegram" ? telegramSettings(value, issues, path) : kind === "whatsapp" ? whatsappSettings(value, issues, path) : kind === "slack" ? slackSettings(value, issues, path) : emailSettings(value, issues, path);
524
+ if (settings !== null) result[name] = {
525
+ kind,
526
+ ...settings
527
+ };
528
+ }
529
+ const declared = declaredChannels(result);
530
+ if (declared.length > 20) issues.push({
531
+ message: `may declare at most 20 channels`,
532
+ path: ["channels"]
533
+ });
534
+ const named = new Map();
535
+ for (const channel of declared) {
536
+ const other = named.get(channel.settings.connection);
537
+ if (other === void 0) named.set(channel.settings.connection, channel.name);
538
+ else issues.push({
539
+ message: `is also the connection of channels.${other}; each channel needs a connection of its own`,
540
+ path: [
541
+ "channels",
542
+ channel.name,
543
+ "connection"
544
+ ]
545
+ });
546
+ }
547
+ return result;
548
+ }
434
549
  function workspaceHook(value, path, issues) {
435
550
  const configured = section({
436
551
  value,
@@ -807,12 +922,7 @@ function validateConfig(input, options = {}) {
807
922
  const channels = section({
808
923
  value: root?.channels,
809
924
  path: ["channels"],
810
- allowed: [
811
- "telegram",
812
- "whatsapp",
813
- "slack",
814
- "email"
815
- ],
925
+ allowed: isRecord(root?.channels) ? Object.keys(root.channels) : [],
816
926
  issues
817
927
  });
818
928
  const models = section({
@@ -843,10 +953,8 @@ function validateConfig(input, options = {}) {
843
953
  message: "is retired; remove this setting (legacy \"deferred\" is accepted for compatibility)",
844
954
  path: ["confirmations", "mode"]
845
955
  });
846
- const telegram = telegramSettings(channels?.telegram, issues);
847
- const whatsapp = whatsappSettings(channels?.whatsapp, issues);
848
- const slack = slackSettings(channels?.slack, issues);
849
- const email = emailSettings(channels?.email, issues);
956
+ const declared = channelSettings(channels, issues);
957
+ const kinds = new Set(declaredChannels(declared).map((channel) => channel.kind));
850
958
  const authoredGroupsInput = currentGroupPolicyInput(root?.groups);
851
959
  for (const issue of groupPolicyIssues(authoredGroupsInput)) issues.push({
852
960
  ...issue,
@@ -953,7 +1061,7 @@ function validateConfig(input, options = {}) {
953
1061
  message: "is required when groupPairingButton is configured",
954
1062
  path: ["replies", "groupPairingRequired"]
955
1063
  });
956
- if (telegram !== null && !legacyArchive) {
1064
+ if (kinds.has("telegram") && !legacyArchive) {
957
1065
  for (const key of ["pairingRequired", "pairingButton"]) if (replies[key] === void 0) issues.push({
958
1066
  message: "is required for Telegram",
959
1067
  path: ["replies", key]
@@ -967,11 +1075,11 @@ function validateConfig(input, options = {}) {
967
1075
  ]
968
1076
  });
969
1077
  }
970
- if (whatsapp !== null && replies.pairingRequired === void 0) issues.push({
1078
+ if (kinds.has("whatsapp") && replies.pairingRequired === void 0) issues.push({
971
1079
  message: "is required for WhatsApp",
972
1080
  path: ["replies", "pairingRequired"]
973
1081
  });
974
- if (slack !== null && replies.pairingRequired === void 0) issues.push({
1082
+ if (kinds.has("slack") && replies.pairingRequired === void 0) issues.push({
975
1083
  message: "is required for Slack",
976
1084
  path: ["replies", "pairingRequired"]
977
1085
  });
@@ -1008,15 +1116,10 @@ function validateConfig(input, options = {}) {
1008
1116
  if (issues.length > 0) return { issues };
1009
1117
  return { value: {
1010
1118
  groups,
1011
- channels: {
1012
- telegram: telegram === null ? null : {
1013
- ...telegram,
1014
- policy: groups.mode
1015
- },
1016
- whatsapp,
1017
- slack,
1018
- email
1019
- },
1119
+ channels: Object.fromEntries(Object.entries(declared).map(([name, channel]) => [name, channel !== null && (name === "telegram" || "kind" in channel && channel.kind === "telegram") ? {
1120
+ ...channel,
1121
+ policy: groups.mode
1122
+ } : channel])),
1020
1123
  models: {
1021
1124
  chat,
1022
1125
  stt,
@@ -1059,4 +1162,4 @@ function manifestOf(config) {
1059
1162
  if (validation.issues !== void 0) throw new SegmentStreamAgentConfigError(validation.issues);
1060
1163
  return validation.value;
1061
1164
  }
1062
- export { ADMISSION_REPLY_KEYS, DEFAULT_ADMISSION_LIMITS, DEFAULT_ATTACHMENTS_MODEL, DEFAULT_DECISION_MODEL, DEFAULT_EMAIL_QUERY, DEFAULT_IMAGE_DESCRIPTION_MODEL, DEFAULT_STT_MODEL, EMAIL_CHECK_MINUTES, GUEST_USD_CEILINGS, MAXIMUM_WEB_DOMAINS, PUBSUB_TOPIC, SESSION_SCOPES, SegmentStreamAgentConfigError, TELEGRAM_POLICIES, admissionLimitsOf, chatModelChoiceOf, configSchema, configWarnings, isLegacyAgentArchive, manifestOf, validateConfig };
1165
+ export { ADMISSION_REPLY_KEYS, CHANNEL_KINDS, CHANNEL_NAME, DEFAULT_ADMISSION_LIMITS, DEFAULT_ATTACHMENTS_MODEL, DEFAULT_DECISION_MODEL, DEFAULT_EMAIL_QUERY, DEFAULT_IMAGE_DESCRIPTION_MODEL, DEFAULT_STT_MODEL, EMAIL_CHECK_MINUTES, GUEST_USD_CEILINGS, MAXIMUM_CHANNELS, MAXIMUM_WEB_DOMAINS, PUBSUB_TOPIC, RESERVED_CHANNEL_NAMES, SESSION_SCOPES, SegmentStreamAgentConfigError, TELEGRAM_POLICIES, admissionLimitsOf, channelOf, channelsOfKind, chatModelChoiceOf, configSchema, configWarnings, declaredChannels, isChannelKind, isLegacyAgentArchive, manifestOf, validateConfig };
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { T as ontologyConnection } from "../../_chunks/principal-DUla0Xge.mjs";
8
+ import { T as ontologyConnection } from "../../_chunks/principal-DIgU-kPR.mjs";
9
9
  import { defineDynamic } from "eve/connections";
10
10
  var ontology_default = defineDynamic(async (context) => {
11
11
  if (!segmentstream.config.ontology.connection) return null;
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
8
  import { localizedText } from "../lib/admission.mjs";
9
9
  import { confirmationLocale } from "../lib/telegram/confirmation-text.mjs";
10
- import "../../_chunks/principal-DUla0Xge.mjs";
10
+ import "../../_chunks/principal-DIgU-kPR.mjs";
11
11
  import { defineHook } from "eve/hooks";
12
12
  var authorization_default = defineHook({ events: { "interaction.opened": (event, context) => {
13
13
  const principal = context.session.auth.current;
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { a as rolesOf } from "../../_chunks/principal-DUla0Xge.mjs";
8
+ import { a as rolesOf } from "../../_chunks/principal-DIgU-kPR.mjs";
9
9
  import { personaFor } from "../personas.mjs";
10
10
  import { defineDynamic, defineInstructions } from "eve/instructions";
11
11
  var persona_default = defineDynamic((context) => {
@@ -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, z as ActorRequiredError, B as actorHeaders, V as actorKey, H as actorOf, U as isGuestSession, W as member, G as memberTool, K as notForGuests } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ export { R as ACT_AS_HEADER, z as ActorRequiredError, B as actorHeaders, V as actorKey, H as actorOf, U as isGuestSession, W as member, G as memberTool, K as notForGuests } from "../../_chunks/principal-DIgU-kPR.mjs";
@@ -17,7 +17,7 @@ export declare const MAXIMUM_INLINE_BYTES: number;
17
17
  export declare class AttachmentOwnerError extends Error {
18
18
  readonly name = "AttachmentOwnerError";
19
19
  }
20
- /** The chat a channel stores a message's files under: `<provider>:<chat id>`. */
20
+ /** The chat a channel stores a message's files under: `<channel>:<chat id>`, by the channel's name. */
21
21
  export declare function providerChat(provider: string, chatId: string): string;
22
22
  /** The owner of the turn's attachments, from the session principal and the session id. */
23
23
  export declare function attachmentOwner(input: {
@@ -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 agentAttachments, gt as chatAddressOf, i as memberIdOf } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ import { _t as chatChannel, b as agentAttachments, gt as chatAddressOf, i as memberIdOf } from "../../_chunks/principal-DIgU-kPR.mjs";
8
8
  import { detectFile, documentText } from "./attachment-formats.mjs";
9
9
  import { readSheets, typedTable } from "./attachment-tables.mjs";
10
10
  import { appOrigin } from "./environment.mjs";
@@ -23,7 +23,7 @@ function attachmentOwner(input) {
23
23
  if (memberId === void 0 || memberId === "" || chat === void 0) throw new AttachmentOwnerError("Attachments require a workspace member in a chat with the agent.");
24
24
  return {
25
25
  memberId,
26
- chat: providerChat(chat.provider, chat.chatId),
26
+ chat: providerChat(chatChannel(chat), chat.chatId),
27
27
  ...input.sessionId === "" ? {} : { sessionId: input.sessionId }
28
28
  };
29
29
  }
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { attachmentOwner } from "./attachment-tools.mjs";
8
- import { Et as failureText, _ as AttachmentError, gt as chatAddressOf } from "../../_chunks/principal-DUla0Xge.mjs";
8
+ import { Dt as failureText, _ as AttachmentError, gt as chatAddressOf } from "../../_chunks/principal-DIgU-kPR.mjs";
9
9
  import { appOrigin, channelsEnabled } from "./environment.mjs";
10
10
  import { transientFileStatus } from "./file-grant.mjs";
11
11
  import { runtimeToken } from "./runtime-token.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 { h as ATTACHMENT_TTL_HOURS, g as ATTACHMENT_URL_PROTOCOL, _ as AttachmentError, mt as CHAT_HEADER, v as EARLIER_CHAT_HEADER, y as MAXIMUM_ATTACHMENT_BYTES, ht as SESSION_HEADER, b as agentAttachments, x as attachmentUrl, S as fetchStoredAttachment, C as parseAttachmentUrl } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ export { h as ATTACHMENT_TTL_HOURS, g as ATTACHMENT_URL_PROTOCOL, _ as AttachmentError, mt as CHAT_HEADER, v as EARLIER_CHAT_HEADER, y as MAXIMUM_ATTACHMENT_BYTES, ht as SESSION_HEADER, b as agentAttachments, x as attachmentUrl, S as fetchStoredAttachment, C as parseAttachmentUrl } 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 { t as agentBuild } from "../../_chunks/build-metadata-2TyBXJEt.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-CYSFZe6f.mjs";
@@ -0,0 +1,67 @@
1
+ import type { HttpRouteDefinition, RouteHandlerArgs } from "eve/channels";
2
+ import type { SessionAuthContext } from "eve/context";
3
+ import { type ChannelKind } from "../config.js";
4
+ /** The principal attribute that names a session's channel when it is not named after its kind. */
5
+ export declare const CHANNEL_ATTRIBUTE = "channel";
6
+ /** Runs `work` for the channel `name` of `kind`, and everything `work` starts. */
7
+ export declare function inChannel<T>(kind: ChannelKind, name: string, work: () => T): T;
8
+ /** The channel of `kind` the current request or delivery runs for: the kind's own when none. */
9
+ export declare function currentChannel(kind: ChannelKind): string;
10
+ /** Whether a channel is the one named after its kind, whose keys never change. */
11
+ export declare function isDefaultChannel(kind: string, name: string): boolean;
12
+ /**
13
+ * A key of one of the channel's chats: the default channel's key as it always was, any other
14
+ * channel's with its name in front. A key that already carries the name keeps it once: a session's
15
+ * continuation token, saved for a pending question or a confirmation and used again, has it.
16
+ */
17
+ export declare function channelKey(kind: string, name: string, key: string): string;
18
+ /** {@link channelKey} for the channel of `kind` the current request or delivery runs for. */
19
+ export declare function currentKey(kind: ChannelKind, key: string): string;
20
+ /** The channel a key belongs to and the key without its name; a key without one is the kind's. */
21
+ export declare function keyChannel(kind: string, key: string): {
22
+ readonly name: string;
23
+ readonly key: string;
24
+ };
25
+ /** The attributes a named channel's principal carries; none for the channel named after its kind. */
26
+ export declare function channelAttributes(kind: ChannelKind, name?: string): Readonly<Record<string, string>>;
27
+ /** The channel a principal speaks on, when its channel stamped one that is not named after a kind. */
28
+ export declare function principalChannel(principal: SessionAuthContext | null | undefined): string | undefined;
29
+ /**
30
+ * The channel a session of `kind` belongs to: its principal's, else the one its continuation token
31
+ * names, else the kind's own.
32
+ */
33
+ export declare function sessionChannel(kind: ChannelKind, input: {
34
+ readonly principal?: SessionAuthContext | null;
35
+ readonly token?: string;
36
+ }): string;
37
+ /** The channel a handler's session belongs to. */
38
+ export declare function handlerChannel(kind: ChannelKind, context: unknown): string;
39
+ /** Wraps a handler of session events so it runs for its session's channel. */
40
+ export declare function inHandlerChannel<Handler extends (event: never, context: never) => unknown>(kind: ChannelKind, handler: Handler): Handler;
41
+ /** Where the extension serves the channels not named after their kind: `<base>/<kind>/<name>`. */
42
+ export declare const NAMED_CHANNEL_ROUTE = "/eve/segmentstream/v1";
43
+ /** The path of a named channel of `kind`'s route, with its name as the `channel` parameter. */
44
+ export declare function namedChannelPath(kind: ChannelKind): string;
45
+ /**
46
+ * A route's operations for the channel `name`: the addresses it reaches carry the channel's name,
47
+ * so its sessions never meet another channel's.
48
+ */
49
+ export declare function channelArgs<State>(kind: ChannelKind, name: string, args: RouteHandlerArgs<State>): RouteHandlerArgs<State>;
50
+ /**
51
+ * The routes eve's channel of `kind` serves for its kind's own channel, served again for each
52
+ * other channel of the kind at {@link namedChannelPath}: each request runs for the channel its path
53
+ * names, and its sessions' addresses carry that name. A name that is no channel of the kind
54
+ * answers 404. The kind's own routes run for the kind's own channel.
55
+ */
56
+ export declare function withNamedRoutes<State>(kind: ChannelKind, routes: ReadonlyArray<HttpRouteDefinition<State>>, declared: (name: string) => boolean): HttpRouteDefinition<State>[];
57
+ /**
58
+ * An eve channel whose session handlers run for their sessions' channels: the events it handles,
59
+ * on `events` or on the `adapter` where eve's Chat SDK and Slack channels keep them, and the files
60
+ * it fetches for a turn.
61
+ */
62
+ export declare function withSessionChannels<Channel extends object>(kind: ChannelKind, channel: Channel): Channel;
63
+ /**
64
+ * Wraps every handler in an object of session event handlers, those whose names are event types,
65
+ * such as `turn.started` or `committed`, so each runs for its session's channel.
66
+ */
67
+ export declare function inHandlerChannels<Handlers extends object>(kind: ChannelKind, handlers: Handlers): Handlers;
@@ -0,0 +1,104 @@
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 { CHANNEL_NAME } from "../config.mjs";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ const scope = new AsyncLocalStorage();
10
+ const SEPARATOR = "/";
11
+ const CHANNEL_ATTRIBUTE = "channel";
12
+ function inChannel(kind, name, work) {
13
+ return scope.run({
14
+ kind,
15
+ name
16
+ }, work);
17
+ }
18
+ function currentChannel(kind) {
19
+ const current = scope.getStore();
20
+ return current?.kind === kind ? current.name : kind;
21
+ }
22
+ function isDefaultChannel(kind, name) {
23
+ return name === kind;
24
+ }
25
+ function channelKey(kind, name, key) {
26
+ return isDefaultChannel(kind, name) || key.startsWith(`${name}${SEPARATOR}`) ? key : `${name}${SEPARATOR}${key}`;
27
+ }
28
+ function currentKey(kind, key) {
29
+ return channelKey(kind, currentChannel(kind), key);
30
+ }
31
+ function keyChannel(kind, key) {
32
+ const separator = key.indexOf(SEPARATOR);
33
+ const name = separator < 0 ? "" : key.slice(0, separator);
34
+ return separator > 0 && CHANNEL_NAME.test(name) && name !== kind ? {
35
+ name,
36
+ key: key.slice(separator + 1)
37
+ } : {
38
+ name: kind,
39
+ key
40
+ };
41
+ }
42
+ function channelAttributes(kind, name = currentChannel(kind)) {
43
+ return isDefaultChannel(kind, name) ? {} : { [CHANNEL_ATTRIBUTE]: name };
44
+ }
45
+ function principalChannel(principal) {
46
+ const name = principal?.attributes[CHANNEL_ATTRIBUTE];
47
+ return typeof name === "string" && CHANNEL_NAME.test(name) ? name : void 0;
48
+ }
49
+ function sessionChannel(kind, input) {
50
+ return principalChannel(input.principal) ?? (input.token === void 0 ? kind : keyChannel(kind, input.token).name);
51
+ }
52
+ function handlerChannel(kind, context) {
53
+ const handler = typeof context === "object" && context !== null ? context : {};
54
+ const token = handler.channel?.continuation?.token ?? handler.continuation?.token;
55
+ return sessionChannel(kind, {
56
+ principal: handler.session?.auth?.current ?? null,
57
+ ...typeof token === "string" ? { token } : {}
58
+ });
59
+ }
60
+ function inHandlerChannel(kind, handler) {
61
+ return ((event, context) => inChannel(kind, handlerChannel(kind, context), () => handler(event, context)));
62
+ }
63
+ const NAMED_CHANNEL_ROUTE = "/eve/segmentstream/v1";
64
+ function namedChannelPath(kind) {
65
+ return `${NAMED_CHANNEL_ROUTE}/${kind}/:channel`;
66
+ }
67
+ function channelArgs(kind, name, args) {
68
+ return isDefaultChannel(kind, name) ? args : {
69
+ ...args,
70
+ from: (address) => args.from(channelKey(kind, name, address)),
71
+ resolveSession: (address) => args.resolveSession(channelKey(kind, name, address))
72
+ };
73
+ }
74
+ function withNamedRoutes(kind, routes, declared) {
75
+ return [...routes.map((route) => ({
76
+ ...route,
77
+ handler: (request, args) => inChannel(kind, kind, () => route.handler(request, args))
78
+ })), ...routes.filter((route, index) => routes.findIndex((other) => other.method === route.method) === index).map((route) => ({
79
+ ...route,
80
+ path: namedChannelPath(kind),
81
+ handler: (request, args) => {
82
+ const name = args.params.channel ?? "";
83
+ return isDefaultChannel(kind, name) || !CHANNEL_NAME.test(name) || !declared(name) ? Promise.resolve(new Response(null, { status: 404 })) : inChannel(kind, name, () => route.handler(request, channelArgs(kind, name, args)));
84
+ }
85
+ }))];
86
+ }
87
+ function withSessionChannels(kind, channel) {
88
+ const value = channel;
89
+ const adapter = value.adapter;
90
+ const fetchFile = adapter?.fetchFile;
91
+ return {
92
+ ...channel,
93
+ ...value.events === void 0 ? {} : { events: inHandlerChannels(kind, value.events) },
94
+ ...value.fetchFile === void 0 ? {} : { fetchFile: inHandlerChannel(kind, value.fetchFile) },
95
+ ...adapter === void 0 ? {} : { adapter: {
96
+ ...inHandlerChannels(kind, adapter),
97
+ ...typeof fetchFile === "function" ? { fetchFile: inHandlerChannel(kind, fetchFile) } : {}
98
+ } }
99
+ };
100
+ }
101
+ function inHandlerChannels(kind, handlers) {
102
+ return Object.fromEntries(Object.entries(handlers).map(([name, handler]) => [name, typeof handler === "function" && (name.includes(".") || name === "committed") ? inHandlerChannel(kind, handler) : handler]));
103
+ }
104
+ export { CHANNEL_ATTRIBUTE, NAMED_CHANNEL_ROUTE, channelArgs, channelAttributes, channelKey, currentChannel, currentKey, handlerChannel, inChannel, inHandlerChannel, inHandlerChannels, isDefaultChannel, keyChannel, namedChannelPath, principalChannel, sessionChannel, withNamedRoutes, withSessionChannels };
@@ -5,14 +5,23 @@ import type { SessionAuthContext } from "eve/context";
5
5
  * there the member's id on the provider, which a private destination on that provider names.
6
6
  */
7
7
  export interface ChatAddress {
8
+ /** The kind of channel the chat is on, which decides how it behaves. */
8
9
  readonly provider: "telegram" | "slack" | "whatsapp" | "web" | "email";
10
+ /**
11
+ * The channel's name when it is not named after its kind, such as `sales_whatsapp`; absent for
12
+ * the channel named after its kind. Read it with {@link chatChannel}.
13
+ */
14
+ readonly channel?: string;
9
15
  readonly chatId: string;
10
16
  /** `""` without a thread. */
11
17
  readonly threadId: string;
12
18
  readonly kind: "private" | "group";
13
19
  readonly peer?: string;
14
20
  }
15
- /** The header that names the chat an ontology request comes from: `<provider>:<chat id>`. */
21
+ /**
22
+ * The header that names the chat an ontology request comes from: `<channel>:<chat id>`, by the
23
+ * channel's name as the archive keys it, such as `telegram:-100123` or `sales_whatsapp:…`.
24
+ */
16
25
  export declare const CHAT_HEADER = "X-SegmentStream-Agent-Chat";
17
26
  /** The header that names the agent's session in that chat. */
18
27
  export declare const SESSION_HEADER = "X-SegmentStream-Agent-Session";
@@ -28,14 +37,20 @@ export declare function withChatAddress(principal: SessionAuthContext, chat: Cha
28
37
  export declare function chatAddressOf(principal?: SessionAuthContext | null): ChatAddress | undefined;
29
38
  /**
30
39
  * The headers that name the chat a session's principal speaks from, and the agent's session there,
31
- * as the chat archive names them. The ontology keeps them with the history of every action the
40
+ * as the chat archive names them: the channel by its name. The ontology keeps them with the history of every action the
32
41
  * agent runs for the principal, a guest's included, so that a record leads back to its chat; a web
33
42
  * chat counts only as the member's or guest's own. A task has no chat, and sends none.
34
43
  */
35
44
  export declare function chatHeaders(principal: SessionAuthContext | null | undefined, sessionId?: string): Record<string, string>;
45
+ /**
46
+ * The channel a chat is on, by name: what the archive, the chat registry, attachments and the
47
+ * ontology's chat destinations key it by. The channel named after its kind is the kind.
48
+ */
49
+ export declare function chatChannel(chat: Pick<ChatAddress, "provider" | "channel">): string;
36
50
  /**
37
51
  * Whether a destination is the chat itself. A private destination names its person, not
38
- * the chat: a Slack direct message is `D…` while its person is `U…`.
52
+ * the chat: a Slack direct message is `D…` while its person is `U…`. A destination's provider is
53
+ * the channel it is on, by name.
39
54
  */
40
55
  export declare function isSameChat(chat: ChatAddress, destination: {
41
56
  readonly provider: string;
@@ -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 { pt as CHAT_ATTRIBUTE, mt as CHAT_HEADER, ht as SESSION_HEADER, gt as chatAddressOf, _t as chatHeaders, vt as isSameChat, yt as withChatAddress } from "../../_chunks/principal-DUla0Xge.mjs";
7
+ export { pt as CHAT_ATTRIBUTE, mt as CHAT_HEADER, ht as SESSION_HEADER, gt as chatAddressOf, _t as chatChannel, vt as chatHeaders, yt as isSameChat, bt as withChatAddress } from "../../_chunks/principal-DIgU-kPR.mjs";
@@ -95,6 +95,12 @@ export declare function replyOperation(key: string): string;
95
95
  */
96
96
  export declare function replyEvent(input: {
97
97
  readonly key: string;
98
+ /**
99
+ * The kind of channel the chat is on; `provider` when absent. The event's id is the kind's, with
100
+ * the channel's name in front for a channel not named after its kind.
101
+ */
102
+ readonly kind?: string;
103
+ /** The channel the chat is on, by its name: the kind for the channel named after its kind. */
98
104
  readonly provider: string;
99
105
  readonly chatId: string;
100
106
  readonly threadId: string | null;
@@ -4,6 +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 { channelKey } from "./channel-scope.mjs";
7
8
  import { proxyEnvironment } from "./environment.mjs";
8
9
  import { runtimeToken } from "./runtime-token.mjs";
9
10
  import { r as workflowValue } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
@@ -11,8 +12,9 @@ function replyOperation(key) {
11
12
  return `reply:${key}`;
12
13
  }
13
14
  function replyEvent(input) {
15
+ const kind = input.kind ?? input.provider;
14
16
  return chatEvent({
15
- eventId: `${input.provider}:reply:${input.key}:${input.status}`,
17
+ eventId: channelKey(kind, input.provider, `${kind}:reply:${input.key}:${input.status}`),
16
18
  operationId: replyOperation(input.key),
17
19
  provider: input.provider,
18
20
  chatId: input.chatId,
@@ -57,10 +59,13 @@ async function topicContext(archive, input) {
57
59
  events
58
60
  };
59
61
  }
62
+ function isTelegramMessage(event) {
63
+ return event.provider === "telegram" || event.eventId.startsWith(channelKey("telegram", event.provider, "telegram:"));
64
+ }
60
65
  function collapseChatEvents(events) {
61
66
  const latest = new Map();
62
67
  for (const event of events) {
63
- const key = event.kind === "outbound" && event.operationId != null ? `chat-delivery:${event.operationId}` : event.kind === "inbound" && event.provider === "telegram" && event.messageId !== null ? `telegram:${event.chatId}:${event.messageId}:message` : event.kind === "outbound" && /^telegram:(send|edit):/u.test(event.eventId) ? event.eventId.replace(/:result$/u, "") : event.eventId;
68
+ const key = event.kind === "outbound" && event.operationId != null ? `chat-delivery:${event.operationId}` : event.kind === "inbound" && isTelegramMessage(event) && event.messageId !== null ? channelKey("telegram", event.provider, `telegram:${event.chatId}:${event.messageId}:message`) : event.kind === "outbound" && /^telegram:(send|edit):/u.test(event.eventId) ? event.eventId.replace(/:result$/u, "") : event.eventId;
64
69
  const previous = latest.get(key);
65
70
  if (previous === void 0 || (/^\d+$/u.test(event.sequence) && /^\d+$/u.test(previous.sequence) ? BigInt(event.sequence) > BigInt(previous.sequence) : event.storedAt > previous.storedAt)) latest.set(key, {
66
71
  ...event,