@segmentstream/agent 0.61.3 → 0.62.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.62.0
4
+
5
+ The agent now sees what someone of the workspace writes to a person outside it, on every channel.
6
+ Each such message joins the chat the agent already has with that person as a `human` outbound
7
+ message: the inbox shows it, the agent reads it in its next turn, and it starts no turn. Mail sent
8
+ by hand from the mailbox already worked this way.
9
+
10
+ - **WhatsApp.** On a number connected in Coexistence, replies written in the WhatsApp Business app
11
+ now join the chat. Meta reports them as `smb_message_echoes`, and SegmentStream relays them to the
12
+ agent beside people's messages.
13
+ - **Workspace channels.** `defineChannel`'s `parse` can return such a message with
14
+ `direction: "outbound"`, its sender the workspace's account, and `by: "bot"` when a program wrote
15
+ it. A message whose id `send` returned for the agent's own reply is left out.
16
+
17
+ Every channel records messages that start no turn through one writer. A message the archive already
18
+ holds by its provider id is recorded once, and nothing is recorded for a chat the agent does not
19
+ have.
20
+
21
+ The agent's chat context and the review judge label a message `agent` only when the agent wrote
22
+ it, that is, when its sender is `agent`. Another program's outbound message is `bot`.
23
+
24
+ A workspace channel's reply is kept with the provider's id of each message `send` returned, one
25
+ archive row per part when a long reply is split. A provider that reports the agent's own replies
26
+ back therefore records nothing new.
27
+
28
+ ## 0.61.4
29
+
30
+ Pins @segmentstream/ontology 0.128.0.
31
+
3
32
  ## 0.61.3
4
33
 
5
34
  The platform instructions every agent reads are reorganized into sections (records, acting,
@@ -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
- var version = "0.61.3";
7
+ var version = "0.62.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -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-DiP2XNAy.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-CAm4A43b.mjs";
@@ -139,7 +139,12 @@ export declare function topicContext(archive: ChatArchive, input: Omit<Parameter
139
139
  * program's. It names who wrote the text, not the account it left from.
140
140
  */
141
141
  export type ChatAuthor = "agent" | "human" | "bot";
142
- export declare function chatAuthor(event: Pick<ChatEvent, "kind" | "senderIsBot">): ChatAuthor;
142
+ /**
143
+ * The sender of every message the agent wrote: its replies and posts. A program's message on the
144
+ * workspace's side, such as a provider's broadcast, has its own account as the sender.
145
+ */
146
+ export declare const AGENT_SENDER = "agent";
147
+ export declare function chatAuthor(event: Pick<ChatEvent, "kind" | "senderIsBot" | "senderId">): ChatAuthor;
143
148
  /** Collapse delivery snapshots from older archives before building a user/model transcript. */
144
149
  export declare function collapseChatEvents(events: ChatPage["events"]): ChatPage["events"];
145
150
  /**
@@ -25,7 +25,7 @@ function replyEvent(input) {
25
25
  turnId: input.turnId,
26
26
  kind: "outbound",
27
27
  text: input.text,
28
- senderId: "agent",
28
+ senderId: AGENT_SENDER,
29
29
  senderIsBot: true,
30
30
  status: input.status,
31
31
  messageId: input.messageId ?? null,
@@ -62,8 +62,9 @@ async function topicContext(archive, input) {
62
62
  function isTelegramMessage(event) {
63
63
  return event.provider === "telegram" || event.eventId.startsWith(channelKey("telegram", event.provider, "telegram:"));
64
64
  }
65
+ const AGENT_SENDER = "agent";
65
66
  function chatAuthor(event) {
66
- return !event.senderIsBot ? "human" : event.kind === "outbound" ? "agent" : "bot";
67
+ return !event.senderIsBot ? "human" : event.kind === "outbound" && event.senderId === "agent" ? "agent" : "bot";
67
68
  }
68
69
  function collapseChatEvents(events) {
69
70
  const latest = new Map();
@@ -185,4 +186,4 @@ function summarizeArguments(value) {
185
186
  };
186
187
  return JSON.stringify(workflowValue(visit(value, 0), { boundary: "chat arguments" })).slice(0, 4e3);
187
188
  }
188
- export { chatArchive, chatAuthor, chatEvent, collapseChatEvents, replyEvent, replyOperation, sessionFailureEventId, summarizeArguments, topicContext };
189
+ export { AGENT_SENDER, chatArchive, chatAuthor, chatEvent, collapseChatEvents, replyEvent, replyOperation, sessionFailureEventId, summarizeArguments, topicContext };
@@ -0,0 +1,73 @@
1
+ import type { AdmittedChat } from "./admission.js";
2
+ import { type ChatArchive, type ChatAuthor } from "./chat-archive.js";
3
+ /**
4
+ * Messages in a chat that start no turn (docs/agent-chat-storage.md, "Messages without a turn").
5
+ * Every channel records them here, in one shape: the archive keeps them under the chat's
6
+ * coordinates, the inbox shows them, and the agent reads the ones it was not sent in its next
7
+ * turn's context.
8
+ */
9
+ /** A file a recorded message carries, by what the provider says of it: no turn runs to store it. */
10
+ export interface RecordedFile {
11
+ readonly name?: string;
12
+ readonly mimeType?: string;
13
+ readonly size?: number;
14
+ }
15
+ /** A message the archive keeps without a turn. */
16
+ export interface RecordedMessage {
17
+ /** The channel's name, as the archive keys its chats. */
18
+ readonly provider: string;
19
+ readonly chatId: string;
20
+ readonly threadId?: string | null;
21
+ /** The members the chat belongs to, who may read it. */
22
+ readonly participantIds: ReadonlyArray<string>;
23
+ /** The archive's key: a provider's message is recorded once, whichever delivery reads it. */
24
+ readonly eventId: string;
25
+ /**
26
+ * `inbound` from the chat's person; `outbound` from the workspace's side, written outside the
27
+ * agent, such as in the provider's own app.
28
+ */
29
+ readonly direction: "inbound" | "outbound";
30
+ /** Who wrote it: a human, or another program. The agent's own replies are recorded as sent. */
31
+ readonly by: Exclude<ChatAuthor, "agent">;
32
+ /** The writer's account at the provider. */
33
+ readonly senderId: string | null;
34
+ readonly senderName?: string | null;
35
+ /** The provider's id of the message. */
36
+ readonly messageId: string;
37
+ readonly text: string;
38
+ readonly files?: ReadonlyArray<RecordedFile>;
39
+ }
40
+ /** Records one message that starts no turn; true for its first record. */
41
+ export declare function recordChatMessage(archive: ChatArchive, message: RecordedMessage): Promise<boolean | void>;
42
+ /** What became of a message the workspace's side wrote outside the agent. */
43
+ export type SentOutsideOutcome =
44
+ /** Recorded in the person's chat. */
45
+ "recorded"
46
+ /** The agent has no chat with the person there: nothing is recorded. */
47
+ | "no_chat"
48
+ /** The archive holds the message already, such as the agent's own reply a provider echoes. */
49
+ | "known";
50
+ /**
51
+ * Records what the workspace's side wrote in a person's chat outside the agent, such as a reply
52
+ * from the provider's own app: an `outbound` message of a human, or of a program when the provider
53
+ * says so, which starts no turn. Only a chat the agent already has with the person is recorded, its
54
+ * members those of its latest message, so a number's or a mailbox's other conversations stay out of
55
+ * the archive. A message the archive holds by its provider id is skipped.
56
+ */
57
+ export declare function recordSentOutside(archive: ChatArchive, message: Omit<RecordedMessage, "participantIds" | "direction">): Promise<SentOutsideOutcome>;
58
+ /**
59
+ * Records a person's message in a private chat a member of the workspace took over, which starts
60
+ * no turn: the inbox shows it, and the agent reads it in its context once the chat is handed back.
61
+ * The event is keyed by the provider's message id, so a redelivered message is recorded once. A
62
+ * decision beside it says why the agent did not answer.
63
+ */
64
+ export declare function recordHandledMessage(archive: ChatArchive, input: {
65
+ readonly chat: AdmittedChat;
66
+ readonly memberId: string;
67
+ /** The person's account at the provider. */
68
+ readonly senderId: string | null;
69
+ readonly senderName?: string | null;
70
+ readonly messageId: string;
71
+ readonly text: string;
72
+ readonly files?: ReadonlyArray<RecordedFile>;
73
+ }): Promise<void>;
@@ -0,0 +1,89 @@
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 { chatEvent } from "./chat-archive.mjs";
8
+ async function recordChatMessage(archive, message) {
9
+ const { eventId } = message;
10
+ return archive.append(chatEvent({
11
+ eventId,
12
+ provider: message.provider,
13
+ chatId: message.chatId,
14
+ chatType: "private",
15
+ threadId: message.threadId === void 0 || message.threadId === "" ? null : message.threadId,
16
+ participantIds: message.participantIds,
17
+ senderId: message.senderId === "agent" ? null : message.senderId,
18
+ senderName: message.senderName ?? null,
19
+ senderIsBot: message.by === "bot",
20
+ kind: message.direction,
21
+ messageId: message.messageId,
22
+ text: message.text,
23
+ ...message.direction === "outbound" ? { status: "completed" } : {},
24
+ attachments: (message.files ?? []).map((file, index) => ({
25
+ id: `${eventId}:file:${index}`,
26
+ kind: "file",
27
+ ...file.name === void 0 ? {} : { filename: file.name },
28
+ ...file.mimeType === void 0 ? {} : { contentType: file.mimeType },
29
+ ...file.size === void 0 ? {} : { size: file.size }
30
+ }))
31
+ }));
32
+ }
33
+ async function recordSentOutside(archive, message) {
34
+ const chat = {
35
+ provider: message.provider,
36
+ chatId: message.chatId,
37
+ ...message.threadId === void 0 || message.threadId === null || message.threadId === "" ? {} : { threadId: message.threadId }
38
+ };
39
+ const [latest] = (await archive.context({
40
+ ...chat,
41
+ limit: 1
42
+ })).events;
43
+ if (latest === void 0) return "no_chat";
44
+ const [known] = (await archive.context({
45
+ ...chat,
46
+ messageId: message.messageId,
47
+ limit: 1
48
+ })).events;
49
+ if (known !== void 0) return "known";
50
+ await recordChatMessage(archive, {
51
+ ...message,
52
+ direction: "outbound",
53
+ participantIds: latest.participantIds
54
+ });
55
+ return "recorded";
56
+ }
57
+ async function recordHandledMessage(archive, input) {
58
+ const { chat } = input;
59
+ const eventId = `handled:${chat.channel}:${chat.chatId}:${input.messageId}`;
60
+ await recordChatMessage(archive, {
61
+ provider: chat.channel,
62
+ chatId: chat.chatId,
63
+ threadId: chat.threadId ?? null,
64
+ participantIds: [input.memberId],
65
+ eventId,
66
+ direction: "inbound",
67
+ by: "human",
68
+ senderId: input.senderId,
69
+ senderName: input.senderName ?? null,
70
+ messageId: input.messageId,
71
+ text: input.text,
72
+ ...input.files === void 0 ? {} : { files: input.files }
73
+ });
74
+ await archive.append(chatEvent({
75
+ eventId: `${eventId}:decision`,
76
+ provider: chat.channel,
77
+ chatId: chat.chatId,
78
+ chatType: "private",
79
+ threadId: chat.threadId === void 0 || chat.threadId === "" ? null : chat.threadId,
80
+ participantIds: [input.memberId],
81
+ senderId: input.senderId,
82
+ messageId: input.messageId,
83
+ kind: "decision",
84
+ decision: "silent",
85
+ reason: "chat_handled",
86
+ status: "completed"
87
+ }));
88
+ }
89
+ export { recordChatMessage, recordHandledMessage, recordSentOutside };
@@ -10,8 +10,8 @@ import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
11
11
  import { S as fetchStoredAttachment, b as agentAttachments, bt as withChatAddress, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent } from "../../../_chunks/principal-TJ6zB2rF.mjs";
12
12
  import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
13
- import { chatArchive, chatEvent, replyEvent } from "../chat-archive.mjs";
14
- import { recordHandledMessage } from "../handled-chat.mjs";
13
+ import { chatArchive, replyEvent } from "../chat-archive.mjs";
14
+ import { recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
15
15
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
16
16
  import { redactDiagnostic } from "../diagnostics.mjs";
17
17
  import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
@@ -482,38 +482,22 @@ function emailChannelDefinition(options) {
482
482
  }
483
483
  const mail = sentMail(parsed, own);
484
484
  if (mail.automated || parsed.headers.some((header) => header.key === REPLY_KEY_HEADER.toLowerCase()) || threadId === void 0 || mail.text === "" && mail.attachments.length === 0) return;
485
- for (const recipient of mail.recipients) {
486
- const chatId = emailChatId(threadId, recipient);
487
- const held = (await archive().context({
488
- provider: currentChannel("email"),
489
- chatId,
490
- threadId,
491
- limit: 1
492
- })).events[0];
493
- if (held === void 0) continue;
494
- await archive().append(chatEvent({
495
- eventId: currentKey("email", `email:staff:${id}:${recipient}`),
496
- provider: currentChannel("email"),
497
- chatId,
498
- threadId,
499
- chatType: "private",
500
- participantIds: held.participantIds,
501
- senderId: mail.fromAddress ?? null,
502
- senderName: mail.fromName ?? null,
503
- senderIsBot: false,
504
- kind: "outbound",
505
- messageId: id,
506
- text: mail.text,
507
- status: "completed",
508
- attachments: mail.attachments.map((file, index) => ({
509
- id: `${id}:${index}`,
510
- kind: "file",
511
- filename: file.filename,
512
- contentType: file.contentType,
513
- size: file.size
514
- }))
515
- }));
516
- }
485
+ for (const recipient of mail.recipients) await recordSentOutside(archive(), {
486
+ provider: currentChannel("email"),
487
+ chatId: emailChatId(threadId, recipient),
488
+ threadId,
489
+ eventId: currentKey("email", `email:staff:${id}:${recipient}`),
490
+ by: "human",
491
+ senderId: mail.fromAddress ?? null,
492
+ senderName: mail.fromName ?? null,
493
+ messageId: id,
494
+ text: mail.text,
495
+ files: mail.attachments.map((file) => ({
496
+ name: file.filename,
497
+ mimeType: file.contentType,
498
+ size: file.size
499
+ }))
500
+ });
517
501
  }
518
502
  async function handle(added, restarted, own, current, args) {
519
503
  if (added.labelIds.some((label) => DISCARDED.has(label))) return;
@@ -21,7 +21,7 @@ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
21
21
  import { slackFileDownload, slackFiles } from "./files.mjs";
22
22
  import { runtimeToken } from "../runtime-token.mjs";
23
23
  import { chatArchive } from "../chat-archive.mjs";
24
- import { recordHandledMessage } from "../handled-chat.mjs";
24
+ import { recordHandledMessage } from "../chat-messages.mjs";
25
25
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
26
26
  import { AsyncLocalStorage } from "node:async_hooks";
27
27
  import { slackChannel } from "eve/channels/slack";
@@ -10,7 +10,7 @@ import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
11
  import { handleWorkspaceCallback, isWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-DiP2XNAy.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CAm4A43b.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.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 { t as agentBuild } from "../../../_chunks/build-metadata-DiP2XNAy.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CAm4A43b.mjs";
8
8
  import { runtimeRequestFailure } from "./runtime-request.mjs";
9
9
  import { GET } from "eve/channels";
10
10
  const HEALTH_ROUTE = "/eve/v1/telegram/health";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { E as OntologyActionNotPermitted, Ft as principalRuntimeSource, It as runtimeEnvelope, L as needsConfirmation, Lt as telegramRuntimeSource, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName } from "../../../_chunks/principal-TJ6zB2rF.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-DiP2XNAy.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CAm4A43b.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -13,6 +13,7 @@ import { type Environment } from "../environment.js";
13
13
  import { type AgentIdentities, type PairedMember } from "../identities.js";
14
14
  import { type RuntimeToken } from "../runtime-token.js";
15
15
  import { type ChatArchive } from "../chat-archive.js";
16
+ import { type WhatsAppEcho } from "./echoes.js";
16
17
  /**
17
18
  * The SegmentStream WhatsApp channel (`agent-design.md`, "Channels"): eve's Chat SDK bridge with
18
19
  * the Chat SDK WhatsApp adapter, at `POST /eve/v1/whatsapp` for `channels.whatsapp` and at
@@ -27,6 +28,10 @@ import { type ChatArchive } from "../chat-archive.js";
27
28
  * transcribed and every file is stored as the member's attachment before the turn. eve keeps the
28
29
  * file parts of the other files and downloads them through this adapter when the turn starts.
29
30
  *
31
+ * What the business writes from the WhatsApp Business app on a number in Coexistence reaches the
32
+ * channel as Meta's `smb_message_echoes`: it is recorded in the person's chat as a human's outbound
33
+ * message, which the inbox shows and the agent reads in its next turn, and starts no turn.
34
+ *
30
35
  * Only paired members are answered. A sender nobody paired gets the workspace's
31
36
  * `replies.pairingRequired` text with a button labelled `replies.pairingButton` that opens the
32
37
  * app's `/agent/connect`, or the text followed by the link where the workspace sets no label.
@@ -71,6 +76,8 @@ interface WhatsAppRuntime {
71
76
  readonly enabled: () => boolean;
72
77
  readonly secret: () => string | undefined;
73
78
  readonly proxy: () => ConnectionProxy;
79
+ /** Records what the business wrote from the WhatsApp Business app; none when omitted. */
80
+ readonly echoes?: (echoes: ReadonlyArray<WhatsAppEcho>) => Promise<void>;
74
81
  }
75
82
  /**
76
83
  * The Chat SDK WhatsApp adapter with its network replaced: it accepts only the platform's relayed
@@ -21,7 +21,8 @@ import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../
21
21
  import { agentIdentities } from "../identities.mjs";
22
22
  import { runtimeToken } from "../runtime-token.mjs";
23
23
  import { chatArchive } from "../chat-archive.mjs";
24
- import { recordHandledMessage } from "../handled-chat.mjs";
24
+ import { recordHandledMessage } from "../chat-messages.mjs";
25
+ import { recordEchoes, whatsappEchoes } from "./echoes.mjs";
25
26
  import { withPlainLinks } from "./links.mjs";
26
27
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
27
28
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -80,6 +81,25 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
80
81
  async handleWebhook(request, options) {
81
82
  if (!this.#runtime.enabled()) return new Response(null, { status: 404 });
82
83
  if (request.method !== "POST") return new Response(null, { status: 405 });
84
+ const record = this.#runtime.echoes;
85
+ if (record !== void 0) {
86
+ const body = await request.clone().text();
87
+ if (this.verifySignature(body, request.headers.get("x-hub-signature-256"))) {
88
+ let payload;
89
+ try {
90
+ payload = JSON.parse(body);
91
+ } catch {
92
+ payload = void 0;
93
+ }
94
+ const echoes = whatsappEchoes(payload);
95
+ if (echoes.length > 0) try {
96
+ await record(echoes);
97
+ } catch (cause) {
98
+ report("echo_record_failed", cause);
99
+ return new Response(null, { status: 503 });
100
+ }
101
+ }
102
+ }
83
103
  return super.handleWebhook(request, options);
84
104
  }
85
105
  verifySignature(body, signature) {
@@ -194,6 +214,7 @@ function segmentstreamWhatsApp(options) {
194
214
  const runtime = {
195
215
  enabled: () => channelsEnabled(environment) && settings() !== null && webhookSecret(environment) !== void 0,
196
216
  secret: () => webhookSecret(environment),
217
+ echoes: (echoes) => recordEchoes(chats(), echoes),
197
218
  proxy: () => {
198
219
  const connection = settings()?.connection;
199
220
  if (connection === void 0) throw new Error("The WhatsApp channel is not configured in agent/segmentstream.json.");
@@ -0,0 +1,28 @@
1
+ import type { ChatArchive } from "../chat-archive.js";
2
+ import { type RecordedFile } from "../chat-messages.js";
3
+ /**
4
+ * What the business wrote from the WhatsApp Business app on a number connected in Coexistence: Meta
5
+ * reports each such message as a `smb_message_echoes` change, which the platform relays to the
6
+ * agent beside `messages`. The channel records it in the person's chat as a human's outbound
7
+ * message, and it starts no turn.
8
+ */
9
+ export interface WhatsAppEcho {
10
+ /** The person's chat, as the Chat SDK adapter names it: `whatsapp:<phone number id>:<user>`. */
11
+ readonly chatId: string;
12
+ /** Meta's id of the message. */
13
+ readonly id: string;
14
+ /** The business number that sent it. */
15
+ readonly from: string | null;
16
+ readonly text: string;
17
+ readonly files: ReadonlyArray<RecordedFile>;
18
+ }
19
+ /**
20
+ * The echoes a relayed delivery holds, in order. One that names no person, or carries neither text
21
+ * nor a file, such as a reaction, is left out.
22
+ */
23
+ export declare function whatsappEchoes(payload: unknown): ReadonlyArray<WhatsAppEcho>;
24
+ /**
25
+ * Records each echo in the person's chat on the WhatsApp channel the delivery runs for, as a
26
+ * human's outbound message, keyed by Meta's id so a delivery read again records it once.
27
+ */
28
+ export declare function recordEchoes(archive: ChatArchive, echoes: ReadonlyArray<WhatsAppEcho>): Promise<void>;
@@ -0,0 +1,69 @@
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 { currentChannel, currentKey } from "../channel-scope.mjs";
8
+ import { recordSentOutside } from "../chat-messages.mjs";
9
+ const MEDIA = [
10
+ "image",
11
+ "video",
12
+ "audio",
13
+ "document",
14
+ "sticker"
15
+ ];
16
+ function record(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
18
+ }
19
+ function text(value) {
20
+ return typeof value === "string" && value !== "" ? value : void 0;
21
+ }
22
+ function whatsappEchoes(payload) {
23
+ const entries = record(payload)?.entry;
24
+ if (!Array.isArray(entries)) return [];
25
+ return entries.flatMap((entry) => {
26
+ const changes = record(entry)?.changes;
27
+ return (Array.isArray(changes) ? changes : []).flatMap((change) => {
28
+ const value = record(record(change)?.value);
29
+ if (record(change)?.field !== "smb_message_echoes" || value === void 0) return [];
30
+ const phoneNumberId = text(record(value.metadata)?.phone_number_id);
31
+ const echoes = value.message_echoes;
32
+ if (phoneNumberId === void 0 || !Array.isArray(echoes)) return [];
33
+ return echoes.flatMap((item) => {
34
+ const echo = record(item);
35
+ const id = text(echo?.id);
36
+ const user = text(echo?.to) ?? text(echo?.to_user_id);
37
+ if (echo === void 0 || id === void 0 || user === void 0) return [];
38
+ const type = text(echo.type);
39
+ const media = MEDIA.find((kind) => kind === type);
40
+ const file = media === void 0 ? void 0 : record(echo[media]);
41
+ const body = type === "text" ? text(record(echo.text)?.body) ?? "" : text(file?.caption) ?? "";
42
+ const files = file === void 0 ? [] : [{
43
+ ...text(file.filename) === void 0 ? {} : { name: text(file.filename) },
44
+ ...text(file.mime_type) === void 0 ? {} : { mimeType: text(file.mime_type) }
45
+ }];
46
+ return body === "" && files.length === 0 ? [] : [{
47
+ chatId: `whatsapp:${phoneNumberId}:${user}`,
48
+ id,
49
+ from: text(echo.from) ?? null,
50
+ text: body,
51
+ files
52
+ }];
53
+ });
54
+ });
55
+ });
56
+ }
57
+ async function recordEchoes(archive, echoes) {
58
+ for (const echo of echoes) await recordSentOutside(archive, {
59
+ provider: currentChannel("whatsapp"),
60
+ chatId: echo.chatId,
61
+ eventId: currentKey("whatsapp", `whatsapp:echo:${echo.id}`),
62
+ by: "human",
63
+ senderId: echo.from,
64
+ messageId: echo.id,
65
+ text: echo.text,
66
+ files: echo.files
67
+ });
68
+ }
69
+ export { recordEchoes, whatsappEchoes };
@@ -57,7 +57,7 @@ export interface ChannelSender {
57
57
  readonly id: string;
58
58
  readonly name?: string;
59
59
  }
60
- /** One message a person wrote, as the channel's code reads it from a provider's event. */
60
+ /** One message in a person's chat, as the channel's code reads it from a provider's event. */
61
61
  export interface ChannelMessage {
62
62
  /**
63
63
  * The provider's id of the message: one turn, whichever webhook delivery or wake reads it again.
@@ -66,10 +66,21 @@ export interface ChannelMessage {
66
66
  readonly id: string;
67
67
  /** The person's chat with the channel. */
68
68
  readonly chatId: string;
69
+ /** Who wrote it: the person, or for an `outbound` message the workspace's account. */
69
70
  readonly sender: ChannelSender;
70
71
  readonly text: string;
71
72
  /** Files the message carries; read only when `limits.files` is on. */
72
73
  readonly files?: ReadonlyArray<ChannelFile>;
74
+ /**
75
+ * `inbound` (the default): the person wrote to the channel, and the agent answers. `outbound`:
76
+ * the workspace's side wrote to the person outside the agent, such as in the provider's own app.
77
+ * It starts no turn: it is recorded in the chat the agent has with the person, for the inbox and
78
+ * the agent's next turn, and left out when there is none or when it is the agent's own reply,
79
+ * known by the id `send` answered.
80
+ */
81
+ readonly direction?: "inbound" | "outbound";
82
+ /** Who wrote an `outbound` message: `human` (the default), or `bot` for another program. */
83
+ readonly by?: "human" | "bot";
73
84
  }
74
85
  /** A file the agent sends, its bytes read. */
75
86
  export interface ChannelReplyFile {
@@ -138,8 +149,8 @@ export interface ChannelDefinition {
138
149
  };
139
150
  /**
140
151
  * The messages one provider event holds: a webhook's body, parsed as JSON when it is JSON, or an
141
- * event a poll read. Events that are no person's message, such as delivery receipts or the
142
- * channel's own replies, hold none.
152
+ * event a poll read. Events that hold no message, such as delivery receipts, hold none; what the
153
+ * workspace's side sent is an `outbound` message.
143
154
  */
144
155
  parse(event: unknown, context: ChannelContext): ReadonlyArray<ChannelMessage> | Promise<ReadonlyArray<ChannelMessage>>;
145
156
  /** Sends one message; answers the provider's id of it, when it gives one. */
@@ -10,8 +10,8 @@ import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
11
11
  import { S as fetchStoredAttachment, b as agentAttachments, bt as withChatAddress, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent, xt as workspaceIdentityProvider } from "../../../_chunks/principal-TJ6zB2rF.mjs";
12
12
  import { CHANNEL_ATTRIBUTE, channelKey } from "../channel-scope.mjs";
13
- import { chatArchive, chatEvent } from "../chat-archive.mjs";
14
- import { recordHandledMessage } from "../handled-chat.mjs";
13
+ import { AGENT_SENDER, chatArchive, chatEvent } from "../chat-archive.mjs";
14
+ import { recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
15
15
  import { connectionProxy } from "../connection-proxy.mjs";
16
16
  import { redactDiagnostic } from "../diagnostics.mjs";
17
17
  import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
@@ -52,8 +52,8 @@ function isRecord(value) {
52
52
  }
53
53
  function validMessage(value) {
54
54
  if (!isRecord(value) || !isRecord(value.sender)) return;
55
- const { id, chatId, sender, text, files } = value;
56
- return typeof id === "string" && WORKSPACE_CHANNEL_ID.test(id) && typeof chatId === "string" && WORKSPACE_CHANNEL_ID.test(chatId) && typeof sender.id === "string" && WORKSPACE_CHANNEL_ID.test(sender.id) && (sender.name === void 0 || typeof sender.name === "string") && typeof text === "string" && (files === void 0 || Array.isArray(files)) ? {
55
+ const { id, chatId, sender, text, files, direction, by } = value;
56
+ return typeof id === "string" && WORKSPACE_CHANNEL_ID.test(id) && typeof chatId === "string" && WORKSPACE_CHANNEL_ID.test(chatId) && typeof sender.id === "string" && WORKSPACE_CHANNEL_ID.test(sender.id) && (sender.name === void 0 || typeof sender.name === "string") && typeof text === "string" && (files === void 0 || Array.isArray(files)) && (direction === void 0 || direction === "inbound" || direction === "outbound") && (by === void 0 || by === "human" || by === "bot") ? {
57
57
  id,
58
58
  chatId,
59
59
  sender: {
@@ -61,7 +61,11 @@ function validMessage(value) {
61
61
  ...sender.name?.trim() ? { name: sender.name.trim() } : {}
62
62
  },
63
63
  text: text.slice(0, MAXIMUM_TEXT),
64
- ...files === void 0 ? {} : { files }
64
+ ...files === void 0 ? {} : { files },
65
+ ...direction === "outbound" ? {
66
+ direction,
67
+ by: by ?? "human"
68
+ } : {}
65
69
  } : void 0;
66
70
  }
67
71
  function splitReply(text, maxLength) {
@@ -197,18 +201,39 @@ function workspaceChannelDefinition(options) {
197
201
  return reference;
198
202
  };
199
203
  async function deliver(reply) {
200
- let id = null;
204
+ const parts = [];
201
205
  for (const [index, text] of splitReply(reply.text, maxLength).entries()) {
202
206
  const sent = await options.send({
203
207
  ...reply,
204
208
  text,
205
209
  ...index === 0 || reply.files === void 0 ? {} : { files: [] }
206
210
  }, context());
207
- id = typeof sent?.id === "string" && sent.id !== "" ? sent.id : null;
211
+ parts.push({
212
+ text,
213
+ id: typeof sent?.id === "string" && sent.id !== "" ? sent.id : null
214
+ });
208
215
  }
209
- return id;
216
+ return parts;
210
217
  }
211
218
  async function dispatch(message, args) {
219
+ if (message.direction === "outbound") {
220
+ await recordSentOutside(archive(), {
221
+ provider: name,
222
+ chatId: message.chatId,
223
+ eventId: channelKey(WORKSPACE_CHANNEL_KIND, name, `${WORKSPACE_CHANNEL_KIND}:sent:${message.id}`),
224
+ by: message.by ?? "human",
225
+ senderId: message.sender.id,
226
+ senderName: message.sender.name ?? null,
227
+ messageId: message.id,
228
+ text: message.text,
229
+ files: (files ? message.files ?? [] : []).map((file) => ({
230
+ name: file.filename,
231
+ mimeType: file.contentType,
232
+ ...file.size === void 0 ? {} : { size: file.size }
233
+ }))
234
+ });
235
+ return;
236
+ }
212
237
  const turn = message.text.trim() !== "" || files && (message.files?.length ?? 0) > 0;
213
238
  const notice = (text) => deliver({
214
239
  chatId: message.chatId,
@@ -518,8 +543,9 @@ function workspaceChannelDefinition(options) {
518
543
  partId: turnId,
519
544
  text
520
545
  }))) return;
546
+ let parts;
521
547
  try {
522
- await deliver({
548
+ parts = await deliver({
523
549
  chatId: chat.chatId,
524
550
  to: chat.peer,
525
551
  text
@@ -529,8 +555,9 @@ function workspaceChannelDefinition(options) {
529
555
  return;
530
556
  }
531
557
  const memberId = memberIdOf(principal);
532
- await archive().append(chatEvent({
533
- eventId: `${WORKSPACE_CHANNEL_KIND}:reply:${ctx.session.id}:${turnId}`,
558
+ const eventId = `${WORKSPACE_CHANNEL_KIND}:reply:${ctx.session.id}:${turnId}`;
559
+ for (const [index, part] of parts.entries()) await archive().append(chatEvent({
560
+ eventId: index === 0 ? eventId : `${eventId}:${index}`,
534
561
  provider: name,
535
562
  chatId: chat.chatId,
536
563
  chatType: "private",
@@ -539,8 +566,9 @@ function workspaceChannelDefinition(options) {
539
566
  sessionId: ctx.session.id,
540
567
  turnId,
541
568
  kind: "outbound",
542
- text,
543
- senderId: "agent",
569
+ text: part.text,
570
+ messageId: part.id,
571
+ senderId: AGENT_SENDER,
544
572
  senderIsBot: true,
545
573
  status: "completed"
546
574
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.61.3",
3
+ "version": "0.62.0",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -80,7 +80,7 @@
80
80
  "@chat-adapter/state-memory": "4.42.0",
81
81
  "@chat-adapter/telegram": "4.41.0",
82
82
  "@chat-adapter/whatsapp": "4.42.0",
83
- "@segmentstream/ontology": "0.127.0",
83
+ "@segmentstream/ontology": "0.128.0",
84
84
  "@vercel/oidc": "^3.8.4",
85
85
  "ai": "^7.0.172",
86
86
  "chat": "4.42.0",
@@ -1,25 +0,0 @@
1
- import type { AdmittedChat } from "./admission.js";
2
- import { type ChatArchive } from "./chat-archive.js";
3
- /** A file the person sent, by what the provider says of it: no turn runs to store it. */
4
- export interface HandledFile {
5
- readonly name?: string;
6
- readonly mimeType?: string;
7
- readonly size?: number;
8
- }
9
- /**
10
- * Records a person's message in a private chat a member of staff took over, which starts no turn.
11
- * The archive keeps it under the chat's coordinates, as the recorder keeps a turn's message, so
12
- * staff read it in the inbox and the agent reads it in its context once the chat is handed back.
13
- * The event is keyed by the provider's message id, so a redelivered message is recorded once. A
14
- * decision beside it says why the agent did not answer.
15
- */
16
- export declare function recordHandledMessage(archive: ChatArchive, input: {
17
- readonly chat: AdmittedChat;
18
- readonly memberId: string;
19
- /** The person's account at the provider. */
20
- readonly senderId: string | null;
21
- readonly senderName?: string | null;
22
- readonly messageId: string;
23
- readonly text: string;
24
- readonly files?: ReadonlyArray<HandledFile>;
25
- }): Promise<void>;
@@ -1,43 +0,0 @@
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 { chatEvent } from "./chat-archive.mjs";
8
- async function recordHandledMessage(archive, input) {
9
- const { chat } = input;
10
- const eventId = `handled:${chat.channel}:${chat.chatId}:${input.messageId}`;
11
- const coordinates = {
12
- provider: chat.channel,
13
- chatId: chat.chatId,
14
- chatType: "private",
15
- threadId: chat.threadId === void 0 || chat.threadId === "" ? null : chat.threadId,
16
- participantIds: [input.memberId],
17
- senderId: input.senderId,
18
- messageId: input.messageId
19
- };
20
- await archive.append(chatEvent({
21
- ...coordinates,
22
- eventId,
23
- kind: "inbound",
24
- senderName: input.senderName ?? null,
25
- text: input.text,
26
- attachments: (input.files ?? []).map((file, index) => ({
27
- id: `${eventId}:file:${index}`,
28
- kind: "file",
29
- ...file.name === void 0 ? {} : { filename: file.name },
30
- ...file.mimeType === void 0 ? {} : { contentType: file.mimeType },
31
- ...file.size === void 0 ? {} : { size: file.size }
32
- }))
33
- }));
34
- await archive.append(chatEvent({
35
- ...coordinates,
36
- eventId: `${eventId}:decision`,
37
- kind: "decision",
38
- decision: "silent",
39
- reason: "chat_handled",
40
- status: "completed"
41
- }));
42
- }
43
- export { recordHandledMessage };