@segmentstream/agent 0.66.2 → 0.66.3
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 +18 -0
- package/dist/_chunks/{build-metadata-DzJPAo8F.mjs → build-metadata-BCD71wzL.mjs} +1 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/chat-recorder.d.ts +16 -0
- package/dist/extension/lib/chat-recorder.mjs +18 -10
- package/dist/extension/lib/review/judge.mjs +3 -1
- package/dist/extension/lib/review/reply.d.ts +4 -3
- package/dist/extension/lib/review/reply.mjs +20 -13
- package/dist/extension/lib/telegram/adapter.mjs +1 -1
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/lib/whatsapp/adapter.d.ts +25 -3
- package/dist/extension/lib/whatsapp/adapter.mjs +47 -5
- package/dist/extension/lib/whatsapp/attachments-send.d.ts +9 -3
- package/dist/extension/lib/whatsapp/attachments-send.mjs +25 -2
- package/dist/extension/lib/whatsapp/sent.d.ts +38 -0
- package/dist/extension/lib/whatsapp/sent.mjs +73 -0
- package/dist/extension/tools/attachments_send.mjs +1 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.66.3
|
|
4
|
+
|
|
5
|
+
In a reviewed Slack direct message, a `whenUnsure` review now reads the person's earlier messages
|
|
6
|
+
in the direct message, whatever thread the reply answers, where it read none and judged the reply
|
|
7
|
+
alone. The review's verdicts, and a reply it lets through, are archived in the person's direct
|
|
8
|
+
message beside their messages, no longer under the reply's thread. An approved reply is still
|
|
9
|
+
sent in the thread it answers.
|
|
10
|
+
|
|
11
|
+
The agent's WhatsApp replies, and the files `attachments_send` sends in a WhatsApp chat, are
|
|
12
|
+
archived with WhatsApp's id of each message (`wamid.…`). A message Meta accepts and later reports
|
|
13
|
+
it could not deliver now shows as failed in the chat's history, as messages sent with `chat.send`
|
|
14
|
+
and `postMessage` already do, and a message of the agent's that the number reports back as an echo
|
|
15
|
+
is not recorded again. Each message is archived as WhatsApp received it, in WhatsApp's formatting:
|
|
16
|
+
a reply longer than one WhatsApp message is several messages in the chat. A reply WhatsApp refuses
|
|
17
|
+
at once is no longer archived as sent.
|
|
18
|
+
|
|
19
|
+
Pins @segmentstream/ontology 0.139.3.
|
|
20
|
+
|
|
3
21
|
## 0.66.2
|
|
4
22
|
|
|
5
23
|
A webhook, the guests' bot check or a workspace channel that moves from a workspace secret to a
|
|
@@ -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.66.
|
|
7
|
+
var version = "0.66.3";
|
|
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-
|
|
7
|
+
export { t as agentBuild } from "../../_chunks/build-metadata-BCD71wzL.mjs";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "eve/context";
|
|
1
2
|
import type { HookContext, HookEvent } from "eve/hooks";
|
|
2
3
|
import { type ChatArchive } from "./chat-archive.js";
|
|
3
4
|
type RuntimeContext = Pick<HookContext, "session" | "channel">;
|
|
@@ -18,6 +19,21 @@ export declare function sessionKind(context: {
|
|
|
18
19
|
};
|
|
19
20
|
readonly channel: RuntimeContext["channel"];
|
|
20
21
|
}): string | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* A member's private chat, kept under the chat its channel stamped, by the channel's name, the
|
|
24
|
+
* same coordinates its replies, attachments and reviews use: an email chat is one Gmail thread
|
|
25
|
+
* with one person, a WhatsApp chat one person's thread, a Slack chat a direct message, and a
|
|
26
|
+
* workspace channel's chat one person's. Undefined for Telegram, which keys its chats from its
|
|
27
|
+
* updates, a web chat, a group, and a session without a member.
|
|
28
|
+
*/
|
|
29
|
+
export declare function stampedPrivateChat(principal: SessionAuthContext | null | undefined): {
|
|
30
|
+
provider: string;
|
|
31
|
+
chatId: string;
|
|
32
|
+
chatType: "private";
|
|
33
|
+
threadId: string | null;
|
|
34
|
+
participantIds: string[];
|
|
35
|
+
senderId: string | null;
|
|
36
|
+
} | undefined;
|
|
21
37
|
export declare function chatCoordinates(context: {
|
|
22
38
|
readonly session: {
|
|
23
39
|
readonly auth: RuntimeContext["session"]["auth"];
|
|
@@ -20,6 +20,19 @@ function isTelegram(context) {
|
|
|
20
20
|
function sessionKind(context) {
|
|
21
21
|
return isTelegram(context) ? "telegram" : chatAddressOf(context.session.auth.current)?.provider;
|
|
22
22
|
}
|
|
23
|
+
function stampedPrivateChat(principal) {
|
|
24
|
+
const chat = chatAddressOf(principal);
|
|
25
|
+
const memberId = memberIdOf(principal);
|
|
26
|
+
if (chat === void 0 || chat.kind !== "private" || chat.provider === "telegram" || chat.provider === "web" || memberId === void 0) return;
|
|
27
|
+
return {
|
|
28
|
+
provider: chatChannel(chat),
|
|
29
|
+
chatId: chat.chatId,
|
|
30
|
+
chatType: "private",
|
|
31
|
+
threadId: chat.provider === "slack" || chat.threadId === "" ? null : chat.threadId,
|
|
32
|
+
participantIds: [memberId],
|
|
33
|
+
senderId: chat.peer ?? null
|
|
34
|
+
};
|
|
35
|
+
}
|
|
23
36
|
function chatCoordinates(context) {
|
|
24
37
|
const principal = context.session.auth.current;
|
|
25
38
|
const taskId = agentTaskIdOf(principal);
|
|
@@ -59,14 +72,8 @@ function chatCoordinates(context) {
|
|
|
59
72
|
participantIds: [],
|
|
60
73
|
senderId: `guest:${guestId}`
|
|
61
74
|
};
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
chatId: chat.chatId,
|
|
65
|
-
chatType: "private",
|
|
66
|
-
threadId: chat.provider === "slack" || chat.threadId === "" ? null : chat.threadId,
|
|
67
|
-
participantIds: [webMemberId],
|
|
68
|
-
senderId: chat.peer ?? null
|
|
69
|
-
};
|
|
75
|
+
const stamped = stampedPrivateChat(principal);
|
|
76
|
+
if (stamped !== void 0) return stamped;
|
|
70
77
|
const telegram = isTelegram(context);
|
|
71
78
|
const address = context.channel.continuationToken;
|
|
72
79
|
const attributes = principal?.attributes;
|
|
@@ -92,7 +99,8 @@ function chatCoordinates(context) {
|
|
|
92
99
|
const RECORDS_REPLIES = new Set([
|
|
93
100
|
"telegram",
|
|
94
101
|
"email",
|
|
95
|
-
"custom"
|
|
102
|
+
"custom",
|
|
103
|
+
"whatsapp"
|
|
96
104
|
]);
|
|
97
105
|
const UNADDRESSED_SESSIONS_REMEMBERED = 1e3;
|
|
98
106
|
function reportUnaddressed(event, context, reported) {
|
|
@@ -224,4 +232,4 @@ function resultErrorMessage(output) {
|
|
|
224
232
|
if (output !== null && typeof output === "object" && "message" in output && typeof output.message === "string") return output.message;
|
|
225
233
|
return null;
|
|
226
234
|
}
|
|
227
|
-
export { chatCoordinates, chatRecorder, isTelegram, sessionKind };
|
|
235
|
+
export { chatCoordinates, chatRecorder, isTelegram, sessionKind, stampedPrivateChat };
|
|
@@ -67,7 +67,9 @@ async function judgeReply(input) {
|
|
|
67
67
|
}
|
|
68
68
|
async function readChat(archive, coordinates) {
|
|
69
69
|
return chatLines((await topicContext(archive, {
|
|
70
|
-
|
|
70
|
+
provider: coordinates.provider,
|
|
71
|
+
chatId: coordinates.chatId,
|
|
72
|
+
threadId: coordinates.threadId,
|
|
71
73
|
limit: 100
|
|
72
74
|
})).events);
|
|
73
75
|
}
|
|
@@ -37,11 +37,12 @@ export declare function replyReview(options: {
|
|
|
37
37
|
/**
|
|
38
38
|
* An eve channel whose final replies are reviewed: its `content.completed` handler sends a reply
|
|
39
39
|
* only when {@link ReplyReview.sendOrHold} allows it, and is given an empty reply otherwise, so it
|
|
40
|
-
* clears its typing status and posts nothing. A sent reply of a reviewed chat is archived
|
|
41
|
-
*
|
|
40
|
+
* clears its typing status and posts nothing. A sent reply of a reviewed chat is archived in
|
|
41
|
+
* `archive`, since the archive's recorder leaves those to the channel; without `archive`, the
|
|
42
|
+
* channel archives the replies it sends itself, as WhatsApp's does. Works for channels built on
|
|
42
43
|
* eve's Chat SDK and Slack channels, whose handlers live on `channel.adapter`.
|
|
43
44
|
*/
|
|
44
|
-
export declare function withReviewedReplies<Channel extends object>(channel: Channel, review: () => ReplyReview, archive
|
|
45
|
+
export declare function withReviewedReplies<Channel extends object>(channel: Channel, review: () => ReplyReview, archive?: () => ChatArchive): Channel;
|
|
45
46
|
/** What a channel needs to review its replies; read per reply, as eve binds the mount late. */
|
|
46
47
|
export interface ChannelReviewOptions {
|
|
47
48
|
/** `review` of `agent/segmentstream.json`; without it every reply is sent. */
|
|
@@ -6,11 +6,27 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { _t as chatChannel, gt as chatAddressOf, i as memberIdOf } from "../../../_chunks/principal-Gd5SR1Wv.mjs";
|
|
8
8
|
import { chatArchive, chatEvent } from "../chat-archive.mjs";
|
|
9
|
+
import { stampedPrivateChat } from "../chat-recorder.mjs";
|
|
9
10
|
import { appOrigin } from "../environment.mjs";
|
|
10
11
|
import { agentReviews } from "./client.mjs";
|
|
11
12
|
import { heldReply, repliesReviewed, reviewOf, reviewOutcome } from "./hold.mjs";
|
|
12
13
|
import { judgeReply, readChat } from "./judge.mjs";
|
|
13
14
|
const VERDICTS_REMEMBERED = 512;
|
|
15
|
+
function reviewedChat(principal) {
|
|
16
|
+
const chat = chatAddressOf(principal);
|
|
17
|
+
const stamped = stampedPrivateChat(principal);
|
|
18
|
+
return chat === void 0 ? void 0 : stamped !== void 0 ? {
|
|
19
|
+
provider: stamped.provider,
|
|
20
|
+
chatId: stamped.chatId,
|
|
21
|
+
chatType: stamped.chatType,
|
|
22
|
+
threadId: stamped.threadId
|
|
23
|
+
} : {
|
|
24
|
+
provider: chatChannel(chat),
|
|
25
|
+
chatId: chat.chatId,
|
|
26
|
+
chatType: chat.kind === "group" ? "group" : "private",
|
|
27
|
+
threadId: chat.threadId === "" ? null : chat.threadId
|
|
28
|
+
};
|
|
29
|
+
}
|
|
14
30
|
function replyReview(options) {
|
|
15
31
|
const verdicts = new Map();
|
|
16
32
|
const remember = (key, outcome) => {
|
|
@@ -27,12 +43,7 @@ function replyReview(options) {
|
|
|
27
43
|
async sendOrHold(input) {
|
|
28
44
|
const review = reviewOf(options.settings(), input.principal);
|
|
29
45
|
if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
|
|
30
|
-
const
|
|
31
|
-
const coordinates = chat === void 0 ? void 0 : {
|
|
32
|
-
provider: chatChannel(chat),
|
|
33
|
-
chatId: chat.chatId,
|
|
34
|
-
threadId: chat.threadId === "" ? null : chat.threadId
|
|
35
|
-
};
|
|
46
|
+
const coordinates = reviewedChat(input.principal);
|
|
36
47
|
const key = `${input.sessionId}:${input.partId}`;
|
|
37
48
|
const outcome = verdicts.get(key) ?? remember(key, await reviewOutcome(review, async (criteria) => judgeReply({
|
|
38
49
|
decide: options.decide,
|
|
@@ -50,7 +61,6 @@ function replyReview(options) {
|
|
|
50
61
|
await options.archive.append(chatEvent({
|
|
51
62
|
...coordinates,
|
|
52
63
|
eventId: `review:${input.sessionId}:${input.partId}`,
|
|
53
|
-
chatType: chat?.kind === "group" ? "group" : "private",
|
|
54
64
|
participantIds: memberId === void 0 ? [] : [memberId],
|
|
55
65
|
sessionId: input.sessionId,
|
|
56
66
|
turnId: input.turnId,
|
|
@@ -106,14 +116,11 @@ function withReviewedReplies(channel, review, archive) {
|
|
|
106
116
|
}
|
|
107
117
|
}, context);
|
|
108
118
|
await completed(event, context);
|
|
109
|
-
const chat =
|
|
119
|
+
const chat = reviewedChat(principal);
|
|
110
120
|
const memberId = memberIdOf(principal);
|
|
111
|
-
if (chat !== void 0) await archive().append(chatEvent({
|
|
121
|
+
if (chat !== void 0 && archive !== void 0) await archive().append(chatEvent({
|
|
122
|
+
...chat,
|
|
112
123
|
eventId: `review:${context.session.id}:${event.data.partId}:outbound`,
|
|
113
|
-
provider: chatChannel(chat),
|
|
114
|
-
chatId: chat.chatId,
|
|
115
|
-
chatType: chat.kind === "group" ? "group" : "private",
|
|
116
|
-
threadId: chat.threadId === "" ? null : chat.threadId,
|
|
117
124
|
participantIds: memberId === void 0 ? [] : [memberId],
|
|
118
125
|
sessionId: context.session.id,
|
|
119
126
|
turnId,
|
|
@@ -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-
|
|
13
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-BCD71wzL.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-
|
|
7
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-BCD71wzL.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-Gd5SR1Wv.mjs";
|
|
8
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
8
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-BCD71wzL.mjs";
|
|
9
9
|
import { object } from "../confirmation-description.mjs";
|
|
10
10
|
var AttachmentLifecycleNotPermitted = class extends Error {
|
|
11
11
|
code = "attachment_lifecycle_not_permitted";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { WhatsAppAdapter } from "@chat-adapter/whatsapp";
|
|
2
|
-
import { type Message, type PostableCard, type WebhookOptions } from "chat";
|
|
1
|
+
import { WhatsAppAdapter, type WhatsAppRawMessage } from "@chat-adapter/whatsapp";
|
|
2
|
+
import { type AdapterPostableMessage, type Message, type PostableCard, type RawMessage, type WebhookOptions } from "chat";
|
|
3
3
|
import type { SessionAuthContext } from "eve/context";
|
|
4
4
|
import { type ChatSdkChannel } from "eve/channels/chat-sdk";
|
|
5
5
|
import type { AdmissionSettings, ChatModelChoice, WhatsAppSettings } from "../../config.js";
|
|
@@ -28,9 +28,13 @@ import { type WhatsAppEcho } from "./echoes.js";
|
|
|
28
28
|
* transcribed and every file is stored as the member's attachment before the turn. eve keeps the
|
|
29
29
|
* file parts of the other files and downloads them through this adapter when the turn starts.
|
|
30
30
|
*
|
|
31
|
+
* Each message of the agent's reply is archived in the person's chat as the channel posts it, with
|
|
32
|
+
* WhatsApp's id of it, so a failure Meta reports later for it reads in the chat's history.
|
|
33
|
+
*
|
|
31
34
|
* What the business writes from the WhatsApp Business app on a number in Coexistence reaches the
|
|
32
35
|
* 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.
|
|
36
|
+
* message, which the inbox shows and the agent reads in its next turn, and starts no turn. A
|
|
37
|
+
* message the archive already holds by its id, such as the agent's own, is not recorded again.
|
|
34
38
|
*
|
|
35
39
|
* Only paired members are answered. A sender nobody paired gets the workspace's
|
|
36
40
|
* `replies.pairingRequired` text with a button labelled `replies.pairingButton` that opens the
|
|
@@ -44,6 +48,16 @@ export declare const WHATSAPP_PROXY_ORIGIN = "https://whatsapp.segmentstream.inv
|
|
|
44
48
|
export declare class WhatsAppProxyRouteError extends Error {
|
|
45
49
|
readonly name = "WhatsAppProxyRouteError";
|
|
46
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Archives each message of the agent's reply as the channel posts it, with WhatsApp's id of it, in
|
|
53
|
+
* the person's chat: the recorder leaves this channel's replies to it, so a held reply, which is
|
|
54
|
+
* never posted, is not archived either. A reply longer than one WhatsApp message is several, each
|
|
55
|
+
* archived with its own text and id. Only the reply's own post counts, not eve's notice that it
|
|
56
|
+
* could not deliver the reply. eve's Chat SDK bridge keeps what it posted to itself, and the Chat
|
|
57
|
+
* SDK adapter answers a post with its last message only, so the adapter collects each message's id
|
|
58
|
+
* as WhatsApp accepts it.
|
|
59
|
+
*/
|
|
60
|
+
export declare function withRecordedReplies<Channel extends object>(channel: Channel, archive: () => ChatArchive): Channel;
|
|
47
61
|
export interface WhatsAppChannelOptions {
|
|
48
62
|
/** The WhatsApp channel `name` the mount declares, or `null` when it declares no such channel. */
|
|
49
63
|
readonly settings: (name: string) => WhatsAppSettings | null;
|
|
@@ -67,6 +81,8 @@ export interface WhatsAppChannelOptions {
|
|
|
67
81
|
};
|
|
68
82
|
/** Where members' files are stored as attachments; tests pass their own. */
|
|
69
83
|
readonly attachments?: AgentAttachments;
|
|
84
|
+
/** The chat archive; tests pass their own. */
|
|
85
|
+
readonly archive?: ChatArchive;
|
|
70
86
|
readonly transcribe?: Transcriber;
|
|
71
87
|
readonly describeImage?: ImageDescriber;
|
|
72
88
|
readonly modelCapabilities?: CapabilityLookup;
|
|
@@ -91,6 +107,12 @@ export declare class ProxiedWhatsAppAdapter extends WhatsAppAdapter {
|
|
|
91
107
|
/** The platform signs each relayed body with the project's agent webhook secret. */
|
|
92
108
|
protected verifySignature(body: string, signature: string | null): boolean;
|
|
93
109
|
protected graphApiRequest<T = unknown>(path: string, body: unknown): Promise<T>;
|
|
110
|
+
/**
|
|
111
|
+
* The Chat SDK adapter's post. While eve delivers a reply ({@link withRecordedReplies}), its first
|
|
112
|
+
* post is the reply, whose messages are collected; a later one, such as eve's notice that it
|
|
113
|
+
* could not deliver the reply, is not.
|
|
114
|
+
*/
|
|
115
|
+
postMessage(threadId: string, message: AdapterPostableMessage): Promise<RawMessage<WhatsAppRawMessage>>;
|
|
94
116
|
/** Uploads are not admitted by the connection; messages send media by link. */
|
|
95
117
|
protected graphApiUpload<T = unknown>(): Promise<T>;
|
|
96
118
|
/** The media's URL by `GET /media/{id}`, then its bytes through the connection's `media` API. */
|
|
@@ -24,6 +24,7 @@ import { chatArchive } from "../chat-archive.mjs";
|
|
|
24
24
|
import { recordHandledMessage } from "../chat-messages.mjs";
|
|
25
25
|
import { recordEchoes, whatsappEchoes } from "./echoes.mjs";
|
|
26
26
|
import { withPlainLinks } from "./links.mjs";
|
|
27
|
+
import { collectSent, noteSent, recordSent } from "./sent.mjs";
|
|
27
28
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
28
29
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
29
30
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
@@ -59,6 +60,39 @@ function withDurableTyping(channel) {
|
|
|
59
60
|
}
|
|
60
61
|
};
|
|
61
62
|
}
|
|
63
|
+
const replyDelivery = new AsyncLocalStorage();
|
|
64
|
+
function withRecordedReplies(channel, archive) {
|
|
65
|
+
const adapter = channel.adapter;
|
|
66
|
+
const completed = adapter?.["content.completed"];
|
|
67
|
+
if (adapter === void 0 || completed === void 0) return channel;
|
|
68
|
+
const handler = async (event, context) => {
|
|
69
|
+
if (event.data.kind !== "text" || event.data.phase !== "reply") return completed(event, context);
|
|
70
|
+
const delivery = {
|
|
71
|
+
sent: [],
|
|
72
|
+
posted: false
|
|
73
|
+
};
|
|
74
|
+
const record = () => recordSent(archive(), {
|
|
75
|
+
principal: context.session.auth.current,
|
|
76
|
+
sessionId: context.session.id,
|
|
77
|
+
turnId: event.scope?.turnId ?? context.session.turn?.id ?? null,
|
|
78
|
+
messages: delivery.sent
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
await replyDelivery.run(delivery, () => completed(event, context));
|
|
82
|
+
} catch (error) {
|
|
83
|
+
await record().catch((cause) => report("reply_record_failed", cause));
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
await record();
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
...channel,
|
|
90
|
+
adapter: {
|
|
91
|
+
...adapter,
|
|
92
|
+
"content.completed": handler
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
62
96
|
var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
|
|
63
97
|
#runtime;
|
|
64
98
|
constructor(runtime) {
|
|
@@ -109,13 +143,21 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
|
|
|
109
143
|
return timingSafeEqual(digest(expected), digest(signature.trim().toLowerCase()));
|
|
110
144
|
}
|
|
111
145
|
async graphApiRequest(path, body) {
|
|
112
|
-
|
|
146
|
+
const answer = await this.#graph({
|
|
113
147
|
api: "graph",
|
|
114
148
|
method: "POST",
|
|
115
149
|
path: proxyPath(path),
|
|
116
150
|
headers: [["content-type", "application/json"]],
|
|
117
151
|
body: new TextEncoder().encode(JSON.stringify(body))
|
|
118
152
|
}, "WhatsApp API error");
|
|
153
|
+
noteSent(path, body, answer);
|
|
154
|
+
return answer;
|
|
155
|
+
}
|
|
156
|
+
async postMessage(threadId, message) {
|
|
157
|
+
const reply = replyDelivery.getStore();
|
|
158
|
+
if (reply === void 0 || reply.posted) return super.postMessage(threadId, message);
|
|
159
|
+
reply.posted = true;
|
|
160
|
+
return collectSent(reply.sent, () => super.postMessage(threadId, message));
|
|
119
161
|
}
|
|
120
162
|
async graphApiUpload() {
|
|
121
163
|
throw new WhatsAppProxyRouteError("The WhatsApp connection does not admit media uploads; send media by link.");
|
|
@@ -204,7 +246,7 @@ function segmentstreamWhatsApp(options) {
|
|
|
204
246
|
const token = options.token ?? runtimeToken;
|
|
205
247
|
const proxies = new Map();
|
|
206
248
|
let identities = options.identities;
|
|
207
|
-
let archive;
|
|
249
|
+
let archive = options.archive;
|
|
208
250
|
const chats = () => archive ??= chatArchive({
|
|
209
251
|
environment,
|
|
210
252
|
token,
|
|
@@ -313,13 +355,13 @@ function segmentstreamWhatsApp(options) {
|
|
|
313
355
|
...media.context.length === 0 ? {} : { context: media.context }
|
|
314
356
|
});
|
|
315
357
|
});
|
|
316
|
-
const
|
|
358
|
+
const recorded = withRecordedReplies(withDurableTyping(bridge.channel), chats);
|
|
317
359
|
const reviewed = options.review === void 0 ? void 0 : channelReview(options.review, {
|
|
318
360
|
environment,
|
|
319
361
|
token,
|
|
320
362
|
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
321
363
|
});
|
|
322
|
-
const channel = reviewed === void 0 ?
|
|
364
|
+
const channel = reviewed === void 0 ? recorded : withReviewedReplies(recorded, () => reviewed.review);
|
|
323
365
|
return {
|
|
324
366
|
...withSessionChannels("whatsapp", channel),
|
|
325
367
|
routes: withNamedRoutes("whatsapp", channel.routes.flatMap((route) => route.transport === "websocket" ? [] : [route]), (name) => options.settings(name) !== null)
|
|
@@ -424,4 +466,4 @@ function pairingMessage(text, label, url) {
|
|
|
424
466
|
fallbackText: fallback
|
|
425
467
|
};
|
|
426
468
|
}
|
|
427
|
-
export { ProxiedWhatsAppAdapter, WHATSAPP_AUTHENTICATOR, WHATSAPP_PROXY_ORIGIN, WhatsAppProxyRouteError, pairingMessage, proxyPath, receive, segmentstreamWhatsApp, whatsappPrincipal };
|
|
469
|
+
export { ProxiedWhatsAppAdapter, WHATSAPP_AUTHENTICATOR, WHATSAPP_PROXY_ORIGIN, WhatsAppProxyRouteError, pairingMessage, proxyPath, receive, segmentstreamWhatsApp, whatsappPrincipal, withRecordedReplies };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { SessionAuthContext } from "eve/context";
|
|
2
2
|
import { type AttachmentSendFailure, type AttachmentSendRefusal } from "../attachments-send.js";
|
|
3
|
+
import { type ChatArchive } from "../chat-archive.js";
|
|
3
4
|
import { type Environment } from "../environment.js";
|
|
4
5
|
import type { RuntimeToken } from "../runtime-token.js";
|
|
5
6
|
import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
|
|
@@ -8,9 +9,10 @@ import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
|
|
|
8
9
|
* the WhatsApp channel's connection by the Chat SDK adapter the channel replies with, the caption
|
|
9
10
|
* on the first. The connection admits no media uploads, so WhatsApp fetches each file by the
|
|
10
11
|
* ontology's download grant, a link valid for about a minute: JPEG and PNG images go as images,
|
|
11
|
-
* other files as WhatsApp's types for them, within WhatsApp's size for each.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
12
|
+
* other files as WhatsApp's types for them, within WhatsApp's size for each. Each message sent is
|
|
13
|
+
* archived in the person's chat with WhatsApp's id of it, so a file WhatsApp reports later it could
|
|
14
|
+
* not fetch, in the message's status, reads failed in the chat's history. The checks and failures
|
|
15
|
+
* are every channel's (`../attachments-send.ts`).
|
|
14
16
|
*/
|
|
15
17
|
/** What became of one requested file. */
|
|
16
18
|
export interface WhatsAppSentFile extends Partial<AttachmentSendFailure> {
|
|
@@ -26,10 +28,14 @@ export declare function sendWhatsAppAttachments(options: {
|
|
|
26
28
|
readonly input: SendAttachmentsInput;
|
|
27
29
|
readonly principal: SessionAuthContext | null;
|
|
28
30
|
readonly sessionId: string;
|
|
31
|
+
/** The turn that sends the files, which their archived messages carry. */
|
|
32
|
+
readonly turnId?: string | null;
|
|
29
33
|
/** The connection of the WhatsApp channel the chat is on, such as `channels.whatsapp.connection`. */
|
|
30
34
|
readonly connection: string | undefined;
|
|
31
35
|
readonly environment?: Environment;
|
|
32
36
|
readonly token?: RuntimeToken;
|
|
33
37
|
readonly fetch?: typeof fetch;
|
|
38
|
+
/** The chat archive; tests pass their own. */
|
|
39
|
+
readonly archive?: ChatArchive;
|
|
34
40
|
}): Promise<WhatsAppSendResult>;
|
|
35
41
|
export {};
|
|
@@ -6,11 +6,13 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { _ as AttachmentError } from "../../../_chunks/principal-Gd5SR1Wv.mjs";
|
|
8
8
|
import { sendStoredAttachments } from "../attachments-send.mjs";
|
|
9
|
+
import { chatArchive } from "../chat-archive.mjs";
|
|
9
10
|
import { connectionProxy } from "../connection-proxy.mjs";
|
|
10
11
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
11
12
|
import { proxyEnvironment } from "../environment.mjs";
|
|
12
13
|
import { StoredFileError, storedFileGrant } from "../sent-files.mjs";
|
|
13
14
|
import { ProxiedWhatsAppAdapter } from "./adapter.mjs";
|
|
15
|
+
import { collectSent, recordSent } from "./sent.mjs";
|
|
14
16
|
import { randomUUID } from "node:crypto";
|
|
15
17
|
import { WhatsAppApiError } from "@chat-adapter/whatsapp";
|
|
16
18
|
function reportWhatsAppError(operation, error, secrets) {
|
|
@@ -40,6 +42,11 @@ async function sendWhatsAppAttachments(options) {
|
|
|
40
42
|
report: (operation, error, _metadata, secrets) => reportWhatsAppError(operation, error, secrets),
|
|
41
43
|
async send(context) {
|
|
42
44
|
const { input, chat, owner, origin, fetch, token, secrets, failed } = context;
|
|
45
|
+
const archive = options.archive ?? chatArchive({
|
|
46
|
+
environment: context.environment,
|
|
47
|
+
token,
|
|
48
|
+
fetch
|
|
49
|
+
});
|
|
43
50
|
const proxy = connectionProxy({
|
|
44
51
|
environment: proxyEnvironment(context.environment),
|
|
45
52
|
connection: context.connection,
|
|
@@ -87,8 +94,9 @@ async function sendWhatsAppAttachments(options) {
|
|
|
87
94
|
id: reference.id,
|
|
88
95
|
filename: grant.filename
|
|
89
96
|
};
|
|
97
|
+
const messages = [];
|
|
90
98
|
try {
|
|
91
|
-
const sent = await adapter.postMessage(chat.chatId, {
|
|
99
|
+
const sent = await collectSent(messages, () => adapter.postMessage(chat.chatId, {
|
|
92
100
|
markdown: caption ?? "",
|
|
93
101
|
attachments: [{
|
|
94
102
|
type: grant.contentType.startsWith("image/") ? "image" : "file",
|
|
@@ -97,7 +105,7 @@ async function sendWhatsAppAttachments(options) {
|
|
|
97
105
|
mimeType: grant.contentType,
|
|
98
106
|
size: grant.size
|
|
99
107
|
}]
|
|
100
|
-
});
|
|
108
|
+
}));
|
|
101
109
|
results[index] = {
|
|
102
110
|
...results[index],
|
|
103
111
|
whatsappMessageId: sent.id
|
|
@@ -109,6 +117,21 @@ async function sendWhatsAppAttachments(options) {
|
|
|
109
117
|
...failed(sendFailure(error), "attachment_upload_failed")
|
|
110
118
|
};
|
|
111
119
|
}
|
|
120
|
+
try {
|
|
121
|
+
await recordSent(archive, {
|
|
122
|
+
principal: context.principal,
|
|
123
|
+
sessionId: options.sessionId,
|
|
124
|
+
turnId: options.turnId ?? null,
|
|
125
|
+
messages,
|
|
126
|
+
file: {
|
|
127
|
+
name: grant.filename,
|
|
128
|
+
mimeType: grant.contentType,
|
|
129
|
+
size: grant.size
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
} catch (error) {
|
|
133
|
+
reportWhatsAppError("attachment_record_failed", error, secrets);
|
|
134
|
+
}
|
|
112
135
|
}
|
|
113
136
|
return { files: results };
|
|
114
137
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "eve/context";
|
|
2
|
+
import { type ChatArchive } from "../chat-archive.js";
|
|
3
|
+
import type { RecordedFile } from "../chat-messages.js";
|
|
4
|
+
/**
|
|
5
|
+
* What the agent sends in a person's WhatsApp chat (`docs/agent-chat-storage.md`): each message of
|
|
6
|
+
* its reply, and each message `attachments_send` sends, is archived as the agent's outbound message
|
|
7
|
+
* with WhatsApp's id of it (`wamid.…`). A failure Meta reports later for that message then reads in
|
|
8
|
+
* the chat's history, and the message reported back as an echo is not recorded again.
|
|
9
|
+
*/
|
|
10
|
+
/** A message WhatsApp accepted from the adapter. */
|
|
11
|
+
export interface WhatsAppSentMessage {
|
|
12
|
+
/** WhatsApp's id of the message, `wamid.…`. */
|
|
13
|
+
readonly id: string;
|
|
14
|
+
/** Meta's type of the message: `text`, `interactive`, or a file's, such as `image`. */
|
|
15
|
+
readonly type: string;
|
|
16
|
+
/** Its text, a file's caption or an interactive message's body; null without one. */
|
|
17
|
+
readonly text: string | null;
|
|
18
|
+
}
|
|
19
|
+
/** Runs `work`, adding each message WhatsApp accepts from the adapter meanwhile to `sent`. */
|
|
20
|
+
export declare function collectSent<T>(sent: WhatsAppSentMessage[], work: () => Promise<T>): Promise<T>;
|
|
21
|
+
/**
|
|
22
|
+
* Notes a message the adapter sent, from its Graph request to `/messages` and WhatsApp's answer,
|
|
23
|
+
* where messages are being collected. A read receipt or a typing indicator is no message.
|
|
24
|
+
*/
|
|
25
|
+
export declare function noteSent(path: string, body: unknown, answer: unknown): void;
|
|
26
|
+
/**
|
|
27
|
+
* Archives messages the agent sent in the person's WhatsApp chat, under the chat the recorder keeps
|
|
28
|
+
* the person's messages in, each once by WhatsApp's id of it; a message of a file's type carries
|
|
29
|
+
* `file`. Nothing is archived for a session without the person's chat, whose replies the recorder
|
|
30
|
+
* keeps.
|
|
31
|
+
*/
|
|
32
|
+
export declare function recordSent(archive: ChatArchive, input: {
|
|
33
|
+
readonly principal: SessionAuthContext | null | undefined;
|
|
34
|
+
readonly sessionId: string;
|
|
35
|
+
readonly turnId: string | null;
|
|
36
|
+
readonly messages: ReadonlyArray<WhatsAppSentMessage>;
|
|
37
|
+
readonly file?: RecordedFile;
|
|
38
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,73 @@
|
|
|
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 { channelKey } from "../channel-scope.mjs";
|
|
8
|
+
import { AGENT_SENDER, chatEvent } from "../chat-archive.mjs";
|
|
9
|
+
import { stampedPrivateChat } from "../chat-recorder.mjs";
|
|
10
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
|
+
const collected = new AsyncLocalStorage();
|
|
12
|
+
function collectSent(sent, work) {
|
|
13
|
+
return collected.run(sent, work);
|
|
14
|
+
}
|
|
15
|
+
function record(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
17
|
+
}
|
|
18
|
+
function text(value) {
|
|
19
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
20
|
+
}
|
|
21
|
+
function noteSent(path, body, answer) {
|
|
22
|
+
const sent = collected.getStore();
|
|
23
|
+
if (sent === void 0 || !path.endsWith("/messages")) return;
|
|
24
|
+
const request = record(body);
|
|
25
|
+
const type = text(request.type);
|
|
26
|
+
const messages = record(answer).messages;
|
|
27
|
+
const id = text(record(Array.isArray(messages) ? messages[0] : void 0).id);
|
|
28
|
+
if (type === null || id === null) return;
|
|
29
|
+
sent.push({
|
|
30
|
+
id,
|
|
31
|
+
type,
|
|
32
|
+
text: type === "text" ? text(record(request.text).body) : type === "interactive" ? text(record(record(request.interactive).body).text) : text(record(request[type]).caption)
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const FILE_TYPES = new Set([
|
|
36
|
+
"image",
|
|
37
|
+
"video",
|
|
38
|
+
"audio",
|
|
39
|
+
"document",
|
|
40
|
+
"sticker"
|
|
41
|
+
]);
|
|
42
|
+
async function recordSent(archive, input) {
|
|
43
|
+
const chat = stampedPrivateChat(input.principal);
|
|
44
|
+
if (chat === void 0) return;
|
|
45
|
+
for (const message of input.messages) {
|
|
46
|
+
const eventId = channelKey("whatsapp", chat.provider, `whatsapp:sent:${message.id}`);
|
|
47
|
+
const file = FILE_TYPES.has(message.type) ? input.file : void 0;
|
|
48
|
+
await archive.append(chatEvent({
|
|
49
|
+
eventId,
|
|
50
|
+
provider: chat.provider,
|
|
51
|
+
chatId: chat.chatId,
|
|
52
|
+
chatType: "private",
|
|
53
|
+
threadId: chat.threadId,
|
|
54
|
+
participantIds: chat.participantIds,
|
|
55
|
+
sessionId: input.sessionId,
|
|
56
|
+
turnId: input.turnId,
|
|
57
|
+
kind: "outbound",
|
|
58
|
+
text: message.text,
|
|
59
|
+
messageId: message.id,
|
|
60
|
+
senderId: AGENT_SENDER,
|
|
61
|
+
senderIsBot: true,
|
|
62
|
+
status: "completed",
|
|
63
|
+
attachments: file === void 0 ? [] : [{
|
|
64
|
+
id: `${eventId}:file:0`,
|
|
65
|
+
kind: "file",
|
|
66
|
+
...file.name === void 0 ? {} : { filename: file.name },
|
|
67
|
+
...file.mimeType === void 0 ? {} : { contentType: file.mimeType },
|
|
68
|
+
...file.size === void 0 ? {} : { size: file.size }
|
|
69
|
+
}]
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export { collectSent, noteSent, recordSent };
|
|
@@ -76,6 +76,7 @@ const tool = defineTool({
|
|
|
76
76
|
connection: channelOf(channels, "email", name)?.connection
|
|
77
77
|
}) : provider === "whatsapp" ? await sendWhatsAppAttachments({
|
|
78
78
|
...options,
|
|
79
|
+
turnId: ctx.session.turn.id,
|
|
79
80
|
connection: channelOf(channels, "whatsapp", name)?.connection
|
|
80
81
|
}) : provider === "custom" ? await sendChannelAttachments({
|
|
81
82
|
...options,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/agent",
|
|
3
|
-
"version": "0.66.
|
|
3
|
+
"version": "0.66.3",
|
|
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.139.
|
|
83
|
+
"@segmentstream/ontology": "0.139.3",
|
|
84
84
|
"@vercel/oidc": "^3.8.4",
|
|
85
85
|
"ai": "^7.0.172",
|
|
86
86
|
"chat": "4.42.0",
|