@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
@@ -0,0 +1,3 @@
1
+ /** Reports a guest's model cost to the ontology, for the guests' money caps; see `lib/guest-usage.ts`. */
2
+ declare const _default: import("eve/hooks").HookDefinition<"usage.recorded">;
3
+ export default _default;
@@ -0,0 +1,11 @@
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 segmentstream from "../extension.mjs";
8
+ import { guestUsageHandler } from "../lib/guest-usage.mjs";
9
+ import { defineHook } from "eve/hooks";
10
+ var guest_usage_default = defineHook({ events: { "usage.recorded": guestUsageHandler({ limits: () => segmentstream.config.limits }) } });
11
+ export { guest_usage_default as default };
@@ -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-JoaOmdFL.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 { B as ACT_AS_HEADER, V as ActorRequiredError, H as actorHeaders, U as actorKey, W as actorOf, G as isGuestSession, K as member, q as memberTool, J as notForGuests } from "../../_chunks/principal-JoaOmdFL.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 { S as agentAttachments, i as memberIdOf, mt as chatAddressOf } from "../../_chunks/principal-JoaOmdFL.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 { Ct as failureText, _ as AttachmentError, mt as chatAddressOf } from "../../_chunks/principal-JoaOmdFL.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";
@@ -11,13 +11,12 @@ import type { RuntimeToken } from "./runtime-token.js";
11
11
  export declare const MAXIMUM_ATTACHMENT_BYTES: number;
12
12
  /** How long an attachment stays available. */
13
13
  export declare const ATTACHMENT_TTL_HOURS = 24;
14
- export declare const CHAT_HEADER = "X-SegmentStream-Agent-Chat";
14
+ export { CHAT_HEADER, SESSION_HEADER } from "./chat-address.js";
15
15
  /**
16
16
  * @legacy agent.conversation-header
17
17
  * The chat's header for ontology services built before it took the name chat; sent alongside.
18
18
  */
19
19
  export declare const EARLIER_CHAT_HEADER = "X-SegmentStream-Agent-Conversation";
20
- export declare const SESSION_HEADER = "X-SegmentStream-Agent-Session";
21
20
  /** The URL protocol of a file part that names a stored attachment instead of a Telegram file. */
22
21
  export declare const ATTACHMENT_URL_PROTOCOL = "segmentstream-attachment:";
23
22
  /** Where an attachment comes from: a channel's message, or the agent's sandbox. */
@@ -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, v as CHAT_HEADER, y as EARLIER_CHAT_HEADER, b as MAXIMUM_ATTACHMENT_BYTES, x as SESSION_HEADER, S as agentAttachments, C as attachmentUrl, w as fetchStoredAttachment, T as parseAttachmentUrl } from "../../_chunks/principal-JoaOmdFL.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-Bc9qfC4D.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,13 +5,26 @@ 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
  }
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
+ */
25
+ export declare const CHAT_HEADER = "X-SegmentStream-Agent-Chat";
26
+ /** The header that names the agent's session in that chat. */
27
+ export declare const SESSION_HEADER = "X-SegmentStream-Agent-Session";
15
28
  /** The session attribute that carries a non-Telegram channel's chat, as JSON. */
16
29
  export declare const CHAT_ATTRIBUTE = "segmentstreamChat";
17
30
  /** A channel's principal with the chat its message came from. */
@@ -22,9 +35,22 @@ export declare function withChatAddress(principal: SessionAuthContext, chat: Cha
22
35
  * carried, so sessions from before this attribute keep working.
23
36
  */
24
37
  export declare function chatAddressOf(principal?: SessionAuthContext | null): ChatAddress | undefined;
38
+ /**
39
+ * The headers that name the chat a session's principal speaks from, and the agent's session there,
40
+ * as the chat archive names them: the channel by its name. The ontology keeps them with the history of every action the
41
+ * agent runs for the principal, a guest's included, so that a record leads back to its chat; a web
42
+ * chat counts only as the member's or guest's own. A task has no chat, and sends none.
43
+ */
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;
25
50
  /**
26
51
  * Whether a destination is the chat itself. A private destination names its person, not
27
- * 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.
28
54
  */
29
55
  export declare function isSameChat(chat: ChatAddress, destination: {
30
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 chatAddressOf, ht as isSameChat, gt as withChatAddress } from "../../_chunks/principal-JoaOmdFL.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,
@@ -5,9 +5,9 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { agentTaskIdOf } from "./agent-task.mjs";
8
- import { chatCoordinates } from "./chat-recorder.mjs";
8
+ import { chatCoordinates, sessionKind } from "./chat-recorder.mjs";
9
9
  import { chatArchive, collapseChatEvents, topicContext } from "./chat-archive.mjs";
10
- import { Tt as reportTelegramError } from "../../_chunks/principal-JoaOmdFL.mjs";
10
+ import { kt as reportTelegramError } from "../../_chunks/principal-DIgU-kPR.mjs";
11
11
  import { createHash } from "node:crypto";
12
12
  import { deliveries, runs, turns } from "eve/events";
13
13
  import { defineState } from "eve/context";
@@ -145,7 +145,7 @@ function legacySince(context, turnId) {
145
145
  const CONTEXT_CHANNELS = new Set(["telegram", "email"]);
146
146
  function chatOf(context) {
147
147
  const coordinates = chatCoordinates(context);
148
- return coordinates === void 0 || !CONTEXT_CHANNELS.has(coordinates.provider) || agentTaskIdOf(context.session.auth.current) !== void 0 ? void 0 : coordinates;
148
+ return coordinates === void 0 || !CONTEXT_CHANNELS.has(sessionKind(context) ?? "") || agentTaskIdOf(context.session.auth.current) !== void 0 ? void 0 : coordinates;
149
149
  }
150
150
  function chatContextHook(archive = chatArchive()) {
151
151
  return {
@@ -4,11 +4,20 @@ export declare const CHAT_POST_PROTOCOL = "segmentstream/chat-post";
4
4
  export declare const CHAT_POST_ENVELOPE = "_segmentstream";
5
5
  /** The ontology's chat posting tool, without the connection's namespace. */
6
6
  export declare const CHAT_POST_TOOL = "chat_post_message";
7
- /** The providers whose chats this agent describes posts to; it refuses a destination elsewhere. */
7
+ /** The kinds of channel whose chats this agent describes posts to; it refuses one elsewhere. */
8
8
  export type ChatPostProvider = "telegram" | "slack" | "whatsapp";
9
9
  export interface ChatPostPreview {
10
10
  readonly chatId: string;
11
- readonly provider: ChatPostProvider;
11
+ /**
12
+ * The channel the destination is on, by its name, as the ontology's `chat_list` names it: its
13
+ * kind for the channel named after its kind, such as `telegram`.
14
+ */
15
+ readonly provider: string;
16
+ /**
17
+ * The kind of that channel, which decides how the message renders; `provider` when absent, as
18
+ * for a confirmation saved before channels had names.
19
+ */
20
+ readonly kind?: ChatPostProvider;
12
21
  readonly externalId: string;
13
22
  readonly title: string;
14
23
  readonly attribution: string;
@@ -19,6 +28,8 @@ export interface ChatPostPreview {
19
28
  }
20
29
  export declare function isChatPost(action: string): boolean;
21
30
  export declare function supportsChatPost(tool: Record<string, unknown>): boolean;
31
+ /** The kind of channel a preview's destination is on. */
32
+ export declare function chatPostKind(preview: ChatPostPreview): string;
22
33
  export declare function chatPostDigest(preview: ChatPostPreview): string;
23
34
  export declare function chatPostOperationId(sessionId: string, callId: string): string;
24
35
  export declare function describeChatPost(input: {
@@ -19,6 +19,9 @@ function isChatPost(action) {
19
19
  function supportsChatPost(tool) {
20
20
  return isChatPost(String(tool.name)) && object(tool._meta)["segmentstream/chat-post"] === 1;
21
21
  }
22
+ function chatPostKind(preview) {
23
+ return preview.kind ?? preview.provider;
24
+ }
22
25
  function chatPostDigest(preview) {
23
26
  return createHash("sha256").update(JSON.stringify([
24
27
  "v2",
@@ -39,6 +42,7 @@ function describeChatPost(input) {
39
42
  const { values, caller, destinations } = input;
40
43
  const items = Array.isArray(destinations.items) ? destinations.items.map(object) : [];
41
44
  const target = items[0];
45
+ const kind = target?.kind ?? target?.provider;
42
46
  if (Object.keys(values).some((key) => ![
43
47
  "chat",
44
48
  "text",
@@ -48,16 +52,17 @@ function describeChatPost(input) {
48
52
  target.title,
49
53
  target.external_id,
50
54
  caller.attribution
51
- ].every((value) => typeof value === "string" && value.length > 0) || target.provider !== "telegram" && target.provider !== "slack" && target.provider !== "whatsapp" || target.provider === "whatsapp" && values.reply_to !== void 0 || target.id !== values.chat && target.title !== values.chat) throw new Error("An unambiguous destination and a complete exact chat preview are required.");
55
+ ].every((value) => typeof value === "string" && value.length > 0) || typeof target.provider !== "string" || !target.provider || kind !== "telegram" && kind !== "slack" && kind !== "whatsapp" || kind === "whatsapp" && values.reply_to !== void 0 || target.id !== values.chat && target.title !== values.chat) throw new Error("An unambiguous destination and a complete exact chat preview are required.");
52
56
  const attribution = caller.attribution;
53
57
  const separator = typeof caller.attribution_separator === "string" ? caller.attribution_separator : "\n\n";
54
- const finalText = target.provider === "telegram" ? `${converter.fromMarkdown(values.text)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_` : target.provider === "slack" ? renderSlack(values.text, attribution, separator) : renderWhatsApp(values.text, attribution, separator);
58
+ const finalText = kind === "telegram" ? `${converter.fromMarkdown(values.text)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_` : kind === "slack" ? renderSlack(values.text, attribution, separator) : renderWhatsApp(values.text, attribution, separator);
55
59
  return {
56
60
  action: "",
57
61
  fields: [],
58
62
  chatPost: {
59
63
  chatId: target.id,
60
64
  provider: target.provider,
65
+ ...kind === target.provider ? {} : { kind },
61
66
  externalId: target.external_id,
62
67
  title: target.title,
63
68
  attribution,
@@ -68,4 +73,4 @@ function describeChatPost(input) {
68
73
  }
69
74
  };
70
75
  }
71
- export { CHAT_POST_ENVELOPE, CHAT_POST_PROTOCOL, CHAT_POST_TOOL, chatPostDigest, chatPostOperationId, describeChatPost, isChatPost, supportsChatPost };
76
+ export { CHAT_POST_ENVELOPE, CHAT_POST_PROTOCOL, CHAT_POST_TOOL, chatPostDigest, chatPostKind, chatPostOperationId, describeChatPost, isChatPost, supportsChatPost };
@@ -1,6 +1,23 @@
1
1
  import type { HookContext, HookEvent } from "eve/hooks";
2
2
  import { type ChatArchive } from "./chat-archive.js";
3
3
  type RuntimeContext = Pick<HookContext, "session" | "channel">;
4
+ /** Whether a hook's session is a Telegram channel's, which archives its own messages. */
5
+ export declare function isTelegram(context: {
6
+ readonly session: {
7
+ readonly auth: RuntimeContext["session"]["auth"];
8
+ };
9
+ readonly channel: RuntimeContext["channel"];
10
+ }): boolean;
11
+ /**
12
+ * The kind of channel a hook's session is on. Its coordinates name the channel, which for a channel
13
+ * not named after its kind is its name, not its kind.
14
+ */
15
+ export declare function sessionKind(context: {
16
+ readonly session: {
17
+ readonly auth: RuntimeContext["session"]["auth"];
18
+ };
19
+ readonly channel: RuntimeContext["channel"];
20
+ }): string | undefined;
4
21
  export declare function chatCoordinates(context: {
5
22
  readonly session: {
6
23
  readonly auth: RuntimeContext["session"]["auth"];
@@ -7,11 +7,18 @@ __eveCreateRequire(import.meta.url);
7
7
  import { n as contentText, t as CONTENT_CAPS } from "../../_chunks/content-cDtVnr8Y.mjs";
8
8
  import { chatArchive, chatEvent, sessionFailureEventId, summarizeArguments } from "./chat-archive.mjs";
9
9
  import { agentTaskIdOf } from "./agent-task.mjs";
10
- import { i as memberIdOf, mt as chatAddressOf, ot as guestIdOf } from "../../_chunks/principal-JoaOmdFL.mjs";
10
+ import { _t as chatChannel, gt as chatAddressOf, i as memberIdOf, ot as guestIdOf } from "../../_chunks/principal-DIgU-kPR.mjs";
11
+ import { keyChannel, principalChannel } from "./channel-scope.mjs";
11
12
  import { parseAddress } from "./telegram/sessions.mjs";
12
13
  import { completionKind } from "./telegram/silent.mjs";
13
14
  import { recordModelServiceAlert } from "./model-service-alert.mjs";
14
15
  import { call } from "eve/events";
16
+ function isTelegram(context) {
17
+ return context.session.auth.current?.authenticator === "segmentstream-telegram" || context.channel.kind?.includes("telegram") === true;
18
+ }
19
+ function sessionKind(context) {
20
+ return isTelegram(context) ? "telegram" : chatAddressOf(context.session.auth.current)?.provider;
21
+ }
15
22
  function chatCoordinates(context) {
16
23
  const principal = context.session.auth.current;
17
24
  const taskId = agentTaskIdOf(principal);
@@ -43,26 +50,28 @@ function chatCoordinates(context) {
43
50
  senderId: `guest:${guestId}`
44
51
  };
45
52
  if (chat?.provider === "email" && webMemberId !== void 0) return {
46
- provider: "email",
53
+ provider: chatChannel(chat),
47
54
  chatId: chat.chatId,
48
55
  chatType: "private",
49
56
  threadId: chat.threadId === "" ? null : chat.threadId,
50
57
  participantIds: [webMemberId],
51
58
  senderId: chat.peer ?? null
52
59
  };
53
- const telegram = principal?.authenticator === "segmentstream-telegram" || context.channel.kind?.includes("telegram");
60
+ const telegram = isTelegram(context);
54
61
  const address = context.channel.continuationToken;
55
62
  const attributes = principal?.attributes;
56
63
  const fields = address?.split(":");
57
- const localAddress = telegram && fields?.length === 4 ? fields.slice(1).join(":") : address;
64
+ const namespaced = telegram && fields?.length === 4 ? fields.slice(1).join(":") : address;
65
+ const localAddress = telegram && namespaced !== void 0 ? keyChannel("telegram", namespaced).key : namespaced;
58
66
  const parsed = telegram && localAddress !== void 0 && /^-?\d+:\d*:\d*$/u.test(localAddress) ? parseAddress(localAddress) : void 0;
59
67
  const attributeChatId = typeof attributes?.chatId === "string" && (!telegram || /^-?\d+$/u.test(attributes.chatId)) ? attributes.chatId : void 0;
60
- const chatId = telegram ? parsed?.chatId ?? attributeChatId : attributeChatId !== void 0 ? attributeChatId : address;
68
+ const channelAddress = chat?.channel !== void 0 && address !== void 0 ? address.replace(`${chat.channel}/`, "") : address;
69
+ const chatId = telegram ? parsed?.chatId ?? attributeChatId : attributeChatId !== void 0 ? attributeChatId : channelAddress;
61
70
  if (!chatId) return;
62
71
  const memberId = memberIdOf(principal);
63
72
  const chatType = attributes?.chatType;
64
73
  return {
65
- provider: telegram ? "telegram" : context.channel.kind ?? "eve",
74
+ provider: (telegram ? principalChannel(principal) : chat?.channel) ?? (telegram ? "telegram" : context.channel.kind ?? "eve"),
66
75
  chatId,
67
76
  chatType: chatType === "group" || chatType === "supergroup" || chatType === void 0 && telegram && chatId.startsWith("-") ? "group" : chatType === "channel" ? "channel" : "private",
68
77
  threadId: !telegram ? null : parsed !== void 0 ? parsed.messageThreadId || null : typeof attributes?.messageThreadId === "string" ? attributes.messageThreadId : null,
@@ -173,7 +182,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
173
182
  phase: event.data.phase
174
183
  })
175
184
  }));
176
- if (!RECORDS_REPLIES.has(coordinates.provider) && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
185
+ if (!RECORDS_REPLIES.has(sessionKind(context) ?? "") && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
177
186
  ...base,
178
187
  eventId: `${eventId}:outbound`,
179
188
  kind: "outbound",
@@ -182,7 +191,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
182
191
  senderIsBot: true,
183
192
  status: "completed"
184
193
  }));
185
- } else if (event.type === "delivery.consumed" && coordinates.provider !== "telegram") await archive.append(chatEvent({
194
+ } else if (event.type === "delivery.consumed" && !isTelegram(context)) await archive.append(chatEvent({
186
195
  ...base,
187
196
  eventId,
188
197
  kind: "inbound",
@@ -201,4 +210,4 @@ function resultErrorMessage(output) {
201
210
  if (output !== null && typeof output === "object" && "message" in output && typeof output.message === "string") return output.message;
202
211
  return null;
203
212
  }
204
- export { chatCoordinates, chatRecorder };
213
+ export { chatCoordinates, chatRecorder, isTelegram, sessionKind };
@@ -1,4 +1,5 @@
1
1
  import { type AgentChat, type AgentIdentities } from "./identities.js";
2
+ import type { ChannelKind } from "../config.js";
2
3
  /** How long a chat's report stands before the next message reports it again. */
3
4
  export declare const REPORT_INTERVAL_MS: number;
4
5
  export declare const REPORT_FAILURE_THRESHOLD = 3;
@@ -72,5 +73,11 @@ export declare function agentChats(input: {
72
73
  readonly logError?: (message: string, error: unknown) => void;
73
74
  readonly logRecovery?: (message: string, detail: unknown) => void;
74
75
  }): AgentChats;
76
+ /**
77
+ * The chat registry of every channel of `kind`, each reporting its chats under its own name, as
78
+ * the registry keys them: a report reaches the registry of the channel the current request runs
79
+ * for. Health covers them all.
80
+ */
81
+ export declare function channelChats(kind: ChannelKind, create: (provider: string) => AgentChats): AgentChats;
75
82
  /** The registry's facts as turn context: only the fields it holds. */
76
83
  export declare function chatContext(chat: AgentChat | undefined): ReadonlyArray<string>;