@segmentstream/agent 0.40.1 → 0.42.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/README.md +12 -0
- package/dist/_chunks/{build-metadata-D8Vmcz9g.mjs → build-metadata-CUyA2hlu.mjs} +1 -1
- package/dist/extension/channels/telegram.mjs +5 -1
- package/dist/extension/channels/whatsapp.mjs +7 -1
- package/dist/extension/config.d.ts +24 -0
- package/dist/extension/config.mjs +6 -2
- package/dist/extension/conventions.d.ts +5 -2
- package/dist/extension/conventions.mjs +32 -0
- package/dist/extension/hooks/conversations.mjs +4 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/conversation-runtime.d.ts +6 -1
- package/dist/extension/lib/conversation-runtime.mjs +2 -2
- package/dist/extension/lib/identities.d.ts +6 -0
- package/dist/extension/lib/identities.mjs +1 -1
- package/dist/extension/lib/review/client.d.ts +13 -0
- package/dist/extension/lib/review/client.mjs +58 -0
- package/dist/extension/lib/review/hold.d.ts +64 -0
- package/dist/extension/lib/review/hold.mjs +59 -0
- package/dist/extension/lib/review/judge.d.ts +58 -0
- package/dist/extension/lib/review/judge.mjs +67 -0
- package/dist/extension/lib/review/reply.d.ts +65 -0
- package/dist/extension/lib/review/reply.mjs +159 -0
- package/dist/extension/lib/telegram/adapter.d.ts +6 -0
- package/dist/extension/lib/telegram/adapter.mjs +12 -2
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/lib/telegram/silent.d.ts +4 -2
- package/dist/extension/lib/telegram/silent.mjs +10 -1
- package/dist/extension/lib/whatsapp/adapter.d.ts +13 -3
- package/dist/extension/lib/whatsapp/adapter.mjs +21 -4
- package/dist/extension/review.d.ts +65 -0
- package/dist/extension/review.mjs +171 -0
- package/package.json +2 -2
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "eve/context";
|
|
2
|
+
import type { ConversationsSettings } from "../../review.js";
|
|
3
|
+
import { type Conversations } from "../conversations.js";
|
|
4
|
+
import { type Environment } from "../environment.js";
|
|
5
|
+
import type { RuntimeToken } from "../runtime-token.js";
|
|
6
|
+
import { type HoldReply } from "./hold.js";
|
|
7
|
+
import { type ReviewDecideFunction } from "./judge.js";
|
|
8
|
+
/**
|
|
9
|
+
* Review of a channel's final replies: the reply of a conversation whose review is not `never` is
|
|
10
|
+
* judged or held before the channel sends it, and held replies become `agent_review` records. The
|
|
11
|
+
* archive keeps each verdict for operators: a held reply is never recorded as sent.
|
|
12
|
+
*/
|
|
13
|
+
export interface ReplyReview {
|
|
14
|
+
/** Whether replies to `principal` are reviewed: their review is not `never`. */
|
|
15
|
+
reviewed(principal: SessionAuthContext | null | undefined): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Whether the channel may send `text` now: true for a conversation that is not reviewed, or a
|
|
18
|
+
* reply the judge passed; false once the reply is held for review. Throws when it could not be
|
|
19
|
+
* held, so the reply is neither sent nor lost silently.
|
|
20
|
+
*/
|
|
21
|
+
sendOrHold(input: {
|
|
22
|
+
readonly principal: SessionAuthContext | null | undefined;
|
|
23
|
+
readonly sessionId: string;
|
|
24
|
+
readonly turnId: string | null;
|
|
25
|
+
readonly partId: string;
|
|
26
|
+
readonly text: string;
|
|
27
|
+
}): Promise<boolean>;
|
|
28
|
+
}
|
|
29
|
+
export declare function replyReview(options: {
|
|
30
|
+
readonly settings: () => ConversationsSettings | undefined;
|
|
31
|
+
readonly decide: ReviewDecideFunction;
|
|
32
|
+
/** The decision model, `models.decision`. */
|
|
33
|
+
readonly model: () => string;
|
|
34
|
+
readonly archive: Conversations;
|
|
35
|
+
readonly hold: HoldReply;
|
|
36
|
+
}): ReplyReview;
|
|
37
|
+
/**
|
|
38
|
+
* An eve channel whose final replies are reviewed: its `content.completed` handler sends a reply
|
|
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 conversation is archived
|
|
41
|
+
* here, since the archive's recorder leaves those to the channel. Works for channels built on
|
|
42
|
+
* eve's Chat SDK and Slack channels, whose handlers live on `channel.adapter`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function withReviewedReplies<Channel extends object>(channel: Channel, review: () => ReplyReview, archive: () => Conversations): Channel;
|
|
45
|
+
/** What a channel needs to review its replies; read per reply, as eve binds the mount late. */
|
|
46
|
+
export interface ChannelReviewOptions {
|
|
47
|
+
/** `conversations` of `agent/segmentstream.json`; without it every reply is sent. */
|
|
48
|
+
readonly settings: () => ConversationsSettings | undefined;
|
|
49
|
+
readonly decide: ReviewDecideFunction;
|
|
50
|
+
/** The decision model, `models.decision`. */
|
|
51
|
+
readonly model: () => string;
|
|
52
|
+
/** Holds a reply for review; tests pass a fake. */
|
|
53
|
+
readonly hold?: HoldReply;
|
|
54
|
+
/** The conversation archive; tests pass a fake. */
|
|
55
|
+
readonly archive?: Conversations;
|
|
56
|
+
}
|
|
57
|
+
/** A channel's {@link ReplyReview}, reporting held replies to the workspace's ontology service. */
|
|
58
|
+
export declare function channelReview(options: ChannelReviewOptions, runtime: {
|
|
59
|
+
readonly environment: Environment;
|
|
60
|
+
readonly token: RuntimeToken;
|
|
61
|
+
readonly fetch?: typeof fetch;
|
|
62
|
+
}): {
|
|
63
|
+
readonly review: ReplyReview;
|
|
64
|
+
readonly archive: Conversations;
|
|
65
|
+
};
|
|
@@ -0,0 +1,159 @@
|
|
|
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 { conversationOf } from "../conversation.mjs";
|
|
8
|
+
import { conversationEvent, conversations } from "../conversations.mjs";
|
|
9
|
+
import { appOrigin } from "../environment.mjs";
|
|
10
|
+
import { agentReviews } from "./client.mjs";
|
|
11
|
+
import { i as memberIdOf } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
12
|
+
import { heldReply, repliesReviewed, reviewOf, reviewOutcome } from "./hold.mjs";
|
|
13
|
+
import { judgeReply, readConversation } from "./judge.mjs";
|
|
14
|
+
const VERDICTS_REMEMBERED = 512;
|
|
15
|
+
function replyReview(options) {
|
|
16
|
+
const verdicts = new Map();
|
|
17
|
+
const remember = (key, outcome) => {
|
|
18
|
+
verdicts.delete(key);
|
|
19
|
+
verdicts.set(key, outcome);
|
|
20
|
+
for (const oldest of verdicts.keys()) {
|
|
21
|
+
if (verdicts.size <= VERDICTS_REMEMBERED) break;
|
|
22
|
+
verdicts.delete(oldest);
|
|
23
|
+
}
|
|
24
|
+
return outcome;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
reviewed: (principal) => repliesReviewed(options.settings(), principal),
|
|
28
|
+
async sendOrHold(input) {
|
|
29
|
+
const review = reviewOf(options.settings(), input.principal);
|
|
30
|
+
if (!repliesReviewed(options.settings(), input.principal) || review.mode === "never") return true;
|
|
31
|
+
const conversation = conversationOf(input.principal);
|
|
32
|
+
const coordinates = conversation === void 0 ? void 0 : {
|
|
33
|
+
provider: conversation.provider,
|
|
34
|
+
chatId: conversation.chatId,
|
|
35
|
+
threadId: conversation.threadId === "" ? null : conversation.threadId
|
|
36
|
+
};
|
|
37
|
+
const key = `${input.sessionId}:${input.partId}`;
|
|
38
|
+
const outcome = verdicts.get(key) ?? remember(key, await reviewOutcome(review, async (criteria) => judgeReply({
|
|
39
|
+
decide: options.decide,
|
|
40
|
+
model: options.model(),
|
|
41
|
+
conversation: coordinates === void 0 ? [] : await readConversation(options.archive, coordinates),
|
|
42
|
+
reply: input.text,
|
|
43
|
+
...criteria === void 0 ? {} : { criteria }
|
|
44
|
+
}), (error) => console.error("[segmentstream] reply review judge failed; the reply is held", {
|
|
45
|
+
sessionId: input.sessionId,
|
|
46
|
+
error
|
|
47
|
+
})));
|
|
48
|
+
const record = async (reason, summary) => {
|
|
49
|
+
if (coordinates === void 0) return;
|
|
50
|
+
const memberId = memberIdOf(input.principal);
|
|
51
|
+
await options.archive.append(conversationEvent({
|
|
52
|
+
...coordinates,
|
|
53
|
+
eventId: `review:${input.sessionId}:${input.partId}`,
|
|
54
|
+
chatType: conversation?.kind === "group" ? "group" : "private",
|
|
55
|
+
participantIds: memberId === void 0 ? [] : [memberId],
|
|
56
|
+
sessionId: input.sessionId,
|
|
57
|
+
turnId: input.turnId,
|
|
58
|
+
kind: "decision",
|
|
59
|
+
decision: reason === "review_passed" ? "reply" : "silent",
|
|
60
|
+
reason,
|
|
61
|
+
argsSummary: JSON.stringify(summary)
|
|
62
|
+
}));
|
|
63
|
+
};
|
|
64
|
+
if (outcome.send) {
|
|
65
|
+
await record("review_passed", {
|
|
66
|
+
mode: review.mode,
|
|
67
|
+
confidence: outcome.confidence ?? null,
|
|
68
|
+
...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
|
|
69
|
+
});
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
const held = heldReply({
|
|
73
|
+
...input,
|
|
74
|
+
outcome
|
|
75
|
+
});
|
|
76
|
+
if (held === void 0) throw new Error("A reply under review has no conversation or member to be held for.");
|
|
77
|
+
await options.hold(held);
|
|
78
|
+
await record("review_held", {
|
|
79
|
+
mode: outcome.mode,
|
|
80
|
+
confidence: outcome.confidence,
|
|
81
|
+
...review.mode === "whenUnsure" ? { minConfidence: review.minConfidence } : {}
|
|
82
|
+
});
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function withReviewedReplies(channel, review, archive) {
|
|
88
|
+
const adapter = channel.adapter;
|
|
89
|
+
const completed = adapter?.["content.completed"];
|
|
90
|
+
if (adapter === void 0 || completed === void 0) return channel;
|
|
91
|
+
const handler = async (event, context) => {
|
|
92
|
+
const principal = context.session.auth.current;
|
|
93
|
+
const text = typeof event.data.value === "string" ? event.data.value : "";
|
|
94
|
+
if (event.data.kind !== "text" || event.data.phase !== "reply" || event.data.interrupted === true || text.trim() === "" || !review().reviewed(principal)) return completed(event, context);
|
|
95
|
+
const turnId = event.scope?.turnId ?? context.session.turn?.id ?? null;
|
|
96
|
+
if (!await review().sendOrHold({
|
|
97
|
+
principal,
|
|
98
|
+
sessionId: context.session.id,
|
|
99
|
+
turnId,
|
|
100
|
+
partId: event.data.partId,
|
|
101
|
+
text
|
|
102
|
+
})) return completed({
|
|
103
|
+
...event,
|
|
104
|
+
data: {
|
|
105
|
+
...event.data,
|
|
106
|
+
value: ""
|
|
107
|
+
}
|
|
108
|
+
}, context);
|
|
109
|
+
await completed(event, context);
|
|
110
|
+
const conversation = conversationOf(principal);
|
|
111
|
+
const memberId = memberIdOf(principal);
|
|
112
|
+
if (conversation !== void 0) await archive().append(conversationEvent({
|
|
113
|
+
eventId: `review:${context.session.id}:${event.data.partId}:outbound`,
|
|
114
|
+
provider: conversation.provider,
|
|
115
|
+
chatId: conversation.chatId,
|
|
116
|
+
chatType: conversation.kind === "group" ? "group" : "private",
|
|
117
|
+
threadId: conversation.threadId === "" ? null : conversation.threadId,
|
|
118
|
+
participantIds: memberId === void 0 ? [] : [memberId],
|
|
119
|
+
sessionId: context.session.id,
|
|
120
|
+
turnId,
|
|
121
|
+
kind: "outbound",
|
|
122
|
+
text,
|
|
123
|
+
senderId: "agent",
|
|
124
|
+
senderIsBot: true,
|
|
125
|
+
status: "completed"
|
|
126
|
+
}));
|
|
127
|
+
};
|
|
128
|
+
return {
|
|
129
|
+
...channel,
|
|
130
|
+
adapter: {
|
|
131
|
+
...adapter,
|
|
132
|
+
"content.completed": handler
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function channelReview(options, runtime) {
|
|
137
|
+
const transport = {
|
|
138
|
+
token: runtime.token,
|
|
139
|
+
...runtime.fetch === void 0 ? {} : { fetch: runtime.fetch }
|
|
140
|
+
};
|
|
141
|
+
const archive = options.archive ?? conversations({
|
|
142
|
+
environment: runtime.environment,
|
|
143
|
+
...transport
|
|
144
|
+
});
|
|
145
|
+
return {
|
|
146
|
+
archive,
|
|
147
|
+
review: replyReview({
|
|
148
|
+
settings: options.settings,
|
|
149
|
+
decide: options.decide,
|
|
150
|
+
model: options.model,
|
|
151
|
+
archive,
|
|
152
|
+
hold: options.hold ?? ((reply) => agentReviews({
|
|
153
|
+
origin: appOrigin(runtime.environment),
|
|
154
|
+
...transport
|
|
155
|
+
})(reply))
|
|
156
|
+
})
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
export { channelReview, replyReview, withReviewedReplies };
|
|
@@ -11,6 +11,7 @@ import { type ImageDescriber } from "./images.js";
|
|
|
11
11
|
import { type CapabilityLookup } from "./media-policy.js";
|
|
12
12
|
import { type DecideFunction } from "./router.js";
|
|
13
13
|
import { type HistoryReader } from "./sessions.js";
|
|
14
|
+
import { type ChannelReviewOptions } from "../review/reply.js";
|
|
14
15
|
import { type Transcriber } from "./voice.js";
|
|
15
16
|
/**
|
|
16
17
|
* The SegmentStream Telegram adapter: eve's `telegramChannel`, with its credentials, identity,
|
|
@@ -48,6 +49,11 @@ export interface TelegramAdapterOptions {
|
|
|
48
49
|
/** The attachment store; tests pass a fake. */
|
|
49
50
|
readonly attachments?: AgentAttachments;
|
|
50
51
|
readonly conversations?: Conversations;
|
|
52
|
+
/**
|
|
53
|
+
* `conversations` of `agent/segmentstream.json`: who sends the agent's replies. Without it the
|
|
54
|
+
* agent sends every reply itself.
|
|
55
|
+
*/
|
|
56
|
+
readonly review?: Omit<ChannelReviewOptions, "model" | "archive">;
|
|
51
57
|
}
|
|
52
58
|
/** The Telegram channel of the extension. */
|
|
53
59
|
export declare function segmentstreamTelegram(options: TelegramAdapterOptions): TelegramChannel;
|
|
@@ -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-CUyA2hlu.mjs";
|
|
14
14
|
import { attachmentLifecycle } from "./lifecycle.mjs";
|
|
15
15
|
import { manifestOf } from "../../config.mjs";
|
|
16
16
|
import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
|
|
@@ -38,6 +38,7 @@ import { healthRoute } from "./health.mjs";
|
|
|
38
38
|
import { decisionRouter } from "../group-routing/router.mjs";
|
|
39
39
|
import { scopedAddress } from "./sessions.mjs";
|
|
40
40
|
import { interimTexts, isNoReplyCall, replyDelivery } from "./silent.mjs";
|
|
41
|
+
import { channelReview } from "../review/reply.mjs";
|
|
41
42
|
import { telegramSendScope } from "./send-queue.mjs";
|
|
42
43
|
import { telegramFailureEvents } from "./turn-errors.mjs";
|
|
43
44
|
import { withDeliveryDiagnostics } from "./delivery-diagnostics.mjs";
|
|
@@ -91,6 +92,15 @@ function segmentstreamTelegram(options) {
|
|
|
91
92
|
const bot = botIdentityCache();
|
|
92
93
|
const proxies = new Map();
|
|
93
94
|
const interimDelivered = interimTexts();
|
|
95
|
+
const review = options.review === void 0 ? void 0 : channelReview({
|
|
96
|
+
...options.review,
|
|
97
|
+
model: () => options.models().decision,
|
|
98
|
+
archive
|
|
99
|
+
}, {
|
|
100
|
+
environment,
|
|
101
|
+
token,
|
|
102
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
103
|
+
}).review;
|
|
94
104
|
let identities;
|
|
95
105
|
let verify = options.verify;
|
|
96
106
|
function settings() {
|
|
@@ -424,7 +434,7 @@ function segmentstreamTelegram(options) {
|
|
|
424
434
|
await replyDelivery(() => telegramSendScope(environment, settings().connection), {
|
|
425
435
|
enabled: () => settings().interimMessages === true,
|
|
426
436
|
delivered: interimDelivered
|
|
427
|
-
})(event, context);
|
|
437
|
+
}, review)(event, context);
|
|
428
438
|
}
|
|
429
439
|
}
|
|
430
440
|
});
|
|
@@ -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-CUyA2hlu.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 { d as telegramRuntimeSource, l as principalRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
8
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
8
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-CUyA2hlu.mjs";
|
|
9
9
|
import { n as currentInboundRequest } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
|
|
10
10
|
import { object } from "../confirmation-description.mjs";
|
|
11
11
|
import { needsConfirmation } from "../confirmations.mjs";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TelegramChannelEvents } from "eve/channels/telegram";
|
|
2
|
+
import type { ReplyReview } from "../review/reply.js";
|
|
2
3
|
/**
|
|
3
4
|
* Whether a call is `no_reply`: the extension's mount (`segmentstream__no_reply`) or a workspace's
|
|
4
5
|
* own `eve add tool/no_reply`. A connection's tool of that name (`mount__connection__no_reply`)
|
|
@@ -33,8 +34,9 @@ export interface InterimMessages {
|
|
|
33
34
|
* none either unless `interim` is enabled: then their text is delivered exactly like a reply. The
|
|
34
35
|
* conversation archive records every delivery for routing and chat context. A text already
|
|
35
36
|
* delivered as an interim message in the same turn, whether a repeat or the final reply, is not
|
|
36
|
-
* delivered again.
|
|
37
|
+
* delivered again. With `review`, a conversation whose replies are reviewed gets no interim
|
|
38
|
+
* messages, and its final reply is sent only when the review allows it.
|
|
37
39
|
*/
|
|
38
|
-
export declare function replyDelivery(scope?: () => string, interim?: InterimMessages): MessageCompleted;
|
|
40
|
+
export declare function replyDelivery(scope?: () => string, interim?: InterimMessages, review?: ReplyReview): MessageCompleted;
|
|
39
41
|
export declare const deliverUnlessSilent: MessageCompleted;
|
|
40
42
|
export {};
|
|
@@ -39,7 +39,7 @@ function interimTexts(limit = 256) {
|
|
|
39
39
|
}
|
|
40
40
|
};
|
|
41
41
|
}
|
|
42
|
-
function replyDelivery(scope = () => "telegram", interim) {
|
|
42
|
+
function replyDelivery(scope = () => "telegram", interim, review) {
|
|
43
43
|
return async (event, context) => {
|
|
44
44
|
if (event.data.kind !== "text" || event.data.interrupted) return;
|
|
45
45
|
const channel = context.channel;
|
|
@@ -48,9 +48,18 @@ function replyDelivery(scope = () => "telegram", interim) {
|
|
|
48
48
|
const interimOn = interim?.enabled() === true;
|
|
49
49
|
const isInterim = kind === "tool_calls" && interimOn && completionKind(textValue) === "reply";
|
|
50
50
|
if (kind !== "reply" && !isInterim) return;
|
|
51
|
+
const reviewed = review?.reviewed(context.session?.auth.current) === true;
|
|
52
|
+
if (reviewed && isInterim) return;
|
|
51
53
|
const turn = interimOn && typeof event.scope?.turnId === "string" && event.scope?.turnId !== "" ? JSON.stringify([context.session?.id ?? "", event.scope?.turnId]) : void 0;
|
|
52
54
|
const key = textValue.trim();
|
|
53
55
|
if (turn !== void 0 && interim.delivered.has(turn, key)) return;
|
|
56
|
+
if (reviewed && !await review.sendOrHold({
|
|
57
|
+
principal: context.session?.auth.current,
|
|
58
|
+
sessionId: context.session?.id ?? "",
|
|
59
|
+
turnId: event.scope?.turnId ?? null,
|
|
60
|
+
partId: event.data.partId,
|
|
61
|
+
text: textValue
|
|
62
|
+
})) return;
|
|
54
63
|
const message = customerMessage(textValue, confirmationLocale(context.session?.auth.current ?? null, currentLocale()));
|
|
55
64
|
const replyTo = (context.session?.auth.current)?.attributes.replyToMessageId;
|
|
56
65
|
const replyParameters = typeof replyTo === "string" && /^[1-9]\d*$/u.test(replyTo) ? { reply_parameters: {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { WhatsAppAdapter } from "@chat-adapter/whatsapp";
|
|
2
|
-
import { type Message, type WebhookOptions } from "chat";
|
|
2
|
+
import { type Message, type PostableCard, type WebhookOptions } from "chat";
|
|
3
3
|
import type { SessionAuthContext } from "eve/context";
|
|
4
4
|
import type { AdmissionSettings, WhatsAppSettings } from "../../config.js";
|
|
5
|
+
import { type ChannelReviewOptions } from "../review/reply.js";
|
|
5
6
|
import { type ConnectionProxy } from "../connection-proxy.js";
|
|
6
7
|
import { type Environment } from "../environment.js";
|
|
7
8
|
import { type AgentIdentities, type PairedMember } from "../identities.js";
|
|
@@ -15,7 +16,8 @@ import { type RuntimeToken } from "../runtime-token.js";
|
|
|
15
16
|
* as `/phone`: no Meta token or number ID enters this process.
|
|
16
17
|
*
|
|
17
18
|
* Only paired members are answered. A sender nobody paired gets the workspace's
|
|
18
|
-
* `replies.pairingRequired` text
|
|
19
|
+
* `replies.pairingRequired` text with a button labelled `replies.pairingButton` that opens the
|
|
20
|
+
* app's `/agent/connect`, or the text followed by the link where the workspace sets no label.
|
|
19
21
|
*/
|
|
20
22
|
/** The authenticator of a WhatsApp session's principal. */
|
|
21
23
|
export declare const WHATSAPP_AUTHENTICATOR = "segmentstream-whatsapp";
|
|
@@ -35,6 +37,8 @@ export interface WhatsAppChannelOptions {
|
|
|
35
37
|
readonly fetch?: typeof fetch;
|
|
36
38
|
/** The ontology's pairing routes; tests pass a fake. */
|
|
37
39
|
readonly identities?: AgentIdentities;
|
|
40
|
+
/** Who sends the agent's replies, from `conversations`; without it every reply is sent. */
|
|
41
|
+
readonly review?: ChannelReviewOptions;
|
|
38
42
|
}
|
|
39
43
|
/** What the adapter reads per request: eve binds the mount after it loads the channel. */
|
|
40
44
|
interface WhatsAppRuntime {
|
|
@@ -73,11 +77,17 @@ export declare function receive(input: {
|
|
|
73
77
|
/** The Chat SDK thread: its id names the conversation, one person's chat with the number. */
|
|
74
78
|
readonly thread: {
|
|
75
79
|
readonly id: string;
|
|
76
|
-
readonly post: (
|
|
80
|
+
readonly post: (message: string | PostableCard) => Promise<unknown>;
|
|
77
81
|
};
|
|
78
82
|
readonly message: Pick<Message, "author" | "text" | "attachments">;
|
|
79
83
|
readonly admission: AdmissionSettings;
|
|
80
84
|
readonly identities: AgentIdentities;
|
|
81
85
|
readonly environment: Environment;
|
|
82
86
|
}): Promise<SessionAuthContext | undefined>;
|
|
87
|
+
/**
|
|
88
|
+
* The pairing reply: the workspace's text with a button opening the link, which WhatsApp shows as
|
|
89
|
+
* a call-to-action URL button, or the text followed by the link where the workspace labels no
|
|
90
|
+
* button. Every word is the workspace's; WhatsApp shows at most 20 characters of the label.
|
|
91
|
+
*/
|
|
92
|
+
export declare function pairingMessage(text: string, label: string | undefined, url: string): string | PostableCard;
|
|
83
93
|
export {};
|
|
@@ -7,6 +7,7 @@ __eveCreateRequire(import.meta.url);
|
|
|
7
7
|
import { admitMessage, localizedText } from "../admission.mjs";
|
|
8
8
|
import { chatSdkButtonAnswer, withButtonDecision } from "../confirmation-buttons.mjs";
|
|
9
9
|
import { withConversation } from "../conversation.mjs";
|
|
10
|
+
import { channelReview, withReviewedReplies } from "../review/reply.mjs";
|
|
10
11
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
11
12
|
import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
|
|
12
13
|
import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
|
|
@@ -15,7 +16,7 @@ import { runtimeToken } from "../runtime-token.mjs";
|
|
|
15
16
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
16
17
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
17
18
|
import { WhatsAppAdapter, WhatsAppApiError } from "@chat-adapter/whatsapp";
|
|
18
|
-
import { ConsoleLogger } from "chat";
|
|
19
|
+
import { Actions, Card, CardText, ConsoleLogger, LinkButton } from "chat";
|
|
19
20
|
import { chatSdkChannel, messageContentOf } from "eve/channels/chat-sdk";
|
|
20
21
|
const WHATSAPP_AUTHENTICATOR = "segmentstream-whatsapp";
|
|
21
22
|
const WHATSAPP_PROXY_ORIGIN = "https://whatsapp.segmentstream.invalid";
|
|
@@ -179,7 +180,13 @@ function segmentstreamWhatsApp(options) {
|
|
|
179
180
|
idempotencyKey: message.id,
|
|
180
181
|
auth: admitted
|
|
181
182
|
})).then(() => void 0));
|
|
182
|
-
return bridge.channel;
|
|
183
|
+
if (options.review === void 0) return bridge.channel;
|
|
184
|
+
const reviewed = channelReview(options.review, {
|
|
185
|
+
environment,
|
|
186
|
+
token,
|
|
187
|
+
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
188
|
+
});
|
|
189
|
+
return withReviewedReplies(bridge.channel, () => reviewed.review, () => reviewed.archive);
|
|
183
190
|
}
|
|
184
191
|
async function receive(input) {
|
|
185
192
|
const { thread, message, admission, identities } = input;
|
|
@@ -217,7 +224,7 @@ async function receive(input) {
|
|
|
217
224
|
externalId: sender,
|
|
218
225
|
...display === void 0 ? {} : { display }
|
|
219
226
|
})).code;
|
|
220
|
-
await thread.post(`${
|
|
227
|
+
await thread.post(pairingMessage(text, localizedText(admission.replies.pairingButton), `${appOrigin(input.environment)}/agent/connect?code=${encodeURIComponent(code)}`));
|
|
221
228
|
}
|
|
222
229
|
return;
|
|
223
230
|
}
|
|
@@ -246,4 +253,14 @@ async function receive(input) {
|
|
|
246
253
|
}
|
|
247
254
|
}
|
|
248
255
|
}
|
|
249
|
-
|
|
256
|
+
function pairingMessage(text, label, url) {
|
|
257
|
+
const fallback = `${text}\n\n${url}`;
|
|
258
|
+
return label === void 0 || label.trim() === "" ? fallback : {
|
|
259
|
+
card: Card({ children: [CardText(text), Actions([LinkButton({
|
|
260
|
+
url,
|
|
261
|
+
label
|
|
262
|
+
})])] }),
|
|
263
|
+
fallbackText: fallback
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
export { ProxiedWhatsAppAdapter, WHATSAPP_AUTHENTICATOR, WHATSAPP_PROXY_ORIGIN, WhatsAppProxyRouteError, pairingMessage, proxyPath, receive, segmentstreamWhatsApp, whatsappPrincipal };
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Review: who sends the agent's replies in a conversation. `conversations` in
|
|
3
|
+
* `agent/segmentstream.json` sets it per role of the person the agent replies to, the first role
|
|
4
|
+
* they hold winning in the order written, and a `default` for everyone else:
|
|
5
|
+
*
|
|
6
|
+
* - `never`: the agent sends its replies itself;
|
|
7
|
+
* - `always`: every reply waits for a member to approve, edit or reject it;
|
|
8
|
+
* - `whenUnsure`: a decision model judges each reply from the conversation and the criteria in
|
|
9
|
+
* `agent/review/<role>.md` (`default.md` for `default`); the agent sends it when the model gives
|
|
10
|
+
* at least `minConfidence` that staff would send it as written, and holds it otherwise.
|
|
11
|
+
*
|
|
12
|
+
* A held reply becomes an `agent_review` record in the workspace's ontology. The criteria are read
|
|
13
|
+
* as persona texts are: by the SDK when the agent is built, and put inline by the platform when it
|
|
14
|
+
* deploys.
|
|
15
|
+
*/
|
|
16
|
+
/** The directory beside `segmentstream.json` that holds the review criteria. */
|
|
17
|
+
export declare const REVIEW_DIRECTORY = "review";
|
|
18
|
+
/** The longest criteria the decision model reads; longer ones fail validation. */
|
|
19
|
+
export declare const MAXIMUM_CRITERIA_LENGTH = 8000;
|
|
20
|
+
/** The key of the settings for everyone no role matches, and the name of its criteria file. */
|
|
21
|
+
export declare const DEFAULT_CONVERSATION = "default";
|
|
22
|
+
export declare const REVIEW_MODES: readonly ["never", "always", "whenUnsure"];
|
|
23
|
+
export type ReviewMode = (typeof REVIEW_MODES)[number];
|
|
24
|
+
export type Review = {
|
|
25
|
+
readonly mode: "never";
|
|
26
|
+
} | {
|
|
27
|
+
readonly mode: "always";
|
|
28
|
+
} | {
|
|
29
|
+
readonly mode: "whenUnsure";
|
|
30
|
+
/** The probability, from 0 to 1, that staff would send the reply as written, to send it. */
|
|
31
|
+
readonly minConfidence: number;
|
|
32
|
+
/** `agent/review/<role>.md`: what staff check a reply for. Put inline, not written by hand. */
|
|
33
|
+
readonly criteria?: string;
|
|
34
|
+
};
|
|
35
|
+
export interface ConversationSettings {
|
|
36
|
+
readonly review: Review;
|
|
37
|
+
}
|
|
38
|
+
export interface ConversationsSettings {
|
|
39
|
+
/** Settings per role of the person the agent replies to; the first role they hold wins. */
|
|
40
|
+
readonly byRole: Readonly<Record<string, ConversationSettings>>;
|
|
41
|
+
/** Everyone no role matches, including a person with no roles. */
|
|
42
|
+
readonly default: ConversationSettings;
|
|
43
|
+
}
|
|
44
|
+
/** Without `conversations`, or for a key it leaves out: the agent sends its replies itself. */
|
|
45
|
+
export declare const SEND_REPLIES: ConversationSettings;
|
|
46
|
+
/** One validation failure, in Standard Schema's issue shape. */
|
|
47
|
+
interface Issue {
|
|
48
|
+
readonly message: string;
|
|
49
|
+
readonly path: ReadonlyArray<string>;
|
|
50
|
+
}
|
|
51
|
+
/** The path of a key's criteria, relative to the directory of `segmentstream.json`. */
|
|
52
|
+
export declare function reviewFile(key: string): string | undefined;
|
|
53
|
+
/** The settings for a person with `roles`: the first `byRole` entry they hold, or the default. */
|
|
54
|
+
export declare function conversationFor(settings: ConversationsSettings | undefined, roles: ReadonlyArray<string>): ConversationSettings;
|
|
55
|
+
/** Validates `conversations` of `agent/segmentstream.json`; `undefined` when absent. */
|
|
56
|
+
export declare function conversationsSettings(value: unknown, issues: Issue[]): ConversationsSettings | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* The keys `conversations` names whose reply a model judges, with each one's criteria file:
|
|
59
|
+
* `byRole`'s roles, then `default`.
|
|
60
|
+
*/
|
|
61
|
+
export declare function criteriaFiles(value: unknown): ReadonlyArray<{
|
|
62
|
+
readonly path: ReadonlyArray<string>;
|
|
63
|
+
readonly file: string;
|
|
64
|
+
}>;
|
|
65
|
+
export {};
|