@segmentstream/agent 0.36.3 → 0.37.1
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 +23 -4
- package/dist/_chunks/{build-metadata-D3ytCxvV.mjs → build-metadata-C0Kz75P3.mjs} +1 -1
- package/dist/_chunks/{principal-UlkbLrgQ.mjs → principal-BIX7T6Hh.mjs} +1 -1
- package/dist/extension/hooks/authorization.mjs +1 -1
- package/dist/extension/instructions.md +6 -4
- package/dist/extension/lib/actor.mjs +1 -1
- package/dist/extension/lib/attachment-tools.mjs +1 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/chat-post-confirmation.d.ts +3 -1
- package/dist/extension/lib/chat-post-confirmation.mjs +8 -5
- package/dist/extension/lib/{telegram/chats.d.ts → chats.d.ts} +14 -4
- package/dist/extension/lib/{telegram/chats.mjs → chats.mjs} +33 -17
- package/dist/extension/lib/confirmations.d.ts +3 -4
- package/dist/extension/lib/confirmations.mjs +16 -11
- package/dist/extension/lib/conversation-runtime.mjs +1 -1
- package/dist/extension/lib/conversation.d.ts +33 -0
- package/dist/extension/lib/conversation.mjs +55 -0
- package/dist/extension/lib/ontology-connection.mjs +11 -4
- package/dist/extension/lib/ontology-file-call.mjs +1 -1
- package/dist/extension/lib/ontology-tools.mjs +1 -1
- package/dist/extension/lib/runtime-envelope.d.ts +5 -1
- package/dist/extension/lib/runtime-envelope.mjs +1 -1
- package/dist/extension/lib/slack/adapter.d.ts +43 -2
- package/dist/extension/lib/slack/adapter.mjs +201 -39
- package/dist/extension/lib/stored-files.mjs +1 -1
- package/dist/extension/lib/telegram/adapter.mjs +7 -4
- package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
- package/dist/extension/lib/telegram/callbacks.mjs +1 -1
- package/dist/extension/lib/telegram/chat-post-card.d.ts +11 -0
- package/dist/extension/lib/telegram/chat-post-card.mjs +27 -12
- package/dist/extension/lib/telegram/confirmations.mjs +1 -1
- package/dist/extension/lib/telegram/conversations.d.ts +1 -1
- package/dist/extension/lib/telegram/files.mjs +1 -1
- package/dist/extension/lib/telegram/health.d.ts +1 -1
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/inbound.d.ts +1 -1
- package/dist/extension/lib/telegram/inbound.mjs +2 -2
- package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
- package/dist/extension/lib/telegram/membership.d.ts +1 -1
- package/dist/extension/lib/telegram/principal.mjs +1 -1
- package/dist/extension/lib/telegram/structured.mjs +1 -1
- package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
- package/dist/extension/lib/whatsapp/adapter.d.ts +2 -0
- package/dist/extension/lib/whatsapp/adapter.mjs +8 -1
- package/dist/extension/model.mjs +1 -1
- package/dist/extension/tools/attachments_promote.mjs +1 -1
- package/dist/extension/tools/questions_ask.mjs +4 -1
- package/package.json +2 -2
|
@@ -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 { s as RUNTIME_SOURCE_PROTOCOL, c as compatibleRuntimeEnvelope, l as principalRuntimeSource, u as runtimeEnvelope, d as telegramRuntimeSource } from "../../_chunks/principal-
|
|
7
|
+
export { s as RUNTIME_SOURCE_PROTOCOL, c as compatibleRuntimeEnvelope, l as principalRuntimeSource, u as runtimeEnvelope, d as telegramRuntimeSource } from "../../_chunks/principal-BIX7T6Hh.mjs";
|
|
@@ -2,6 +2,7 @@ import { type SlackChannel, type SlackInboundMessageContext, type SlackMentionRe
|
|
|
2
2
|
import type { SessionAuthContext } from "eve/context";
|
|
3
3
|
import type { AdmissionSettings, SlackSettings } from "../../config.js";
|
|
4
4
|
import type { GroupPolicy } from "../group-routing/policy.js";
|
|
5
|
+
import { type AgentChats } from "../chats.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";
|
|
@@ -13,11 +14,16 @@ import { type RuntimeToken } from "../runtime-token.js";
|
|
|
13
14
|
* which checks them with the app's signing secret and relays them here signed as Slack signs, with
|
|
14
15
|
* the project's `SEGMENTSTREAM_AGENT_WEBHOOK_SECRET`. Every Web API call and file download goes
|
|
15
16
|
* through the connection proxy, which adds the bot token: no Slack credential enters this process.
|
|
17
|
+
* Only a download Slack redirects to another host is fetched there directly, without a credential.
|
|
16
18
|
*
|
|
17
19
|
* eve does the rest: mentions and direct messages start a turn in a thread, the thread's later
|
|
18
20
|
* replies continue it, and approvals and questions are buttons. Only paired members are answered;
|
|
19
21
|
* anyone else gets the workspace's `replies.pairingRequired` text and a link to the app's
|
|
20
22
|
* `/agent/connect`, privately.
|
|
23
|
+
*
|
|
24
|
+
* The channels the agent is in are reported to the ontology's `agent_chat` registry, titled as
|
|
25
|
+
* Slack names them, when a paired member writes there and when the agent joins, leaves or sees one
|
|
26
|
+
* renamed. Direct and group direct messages are never reported.
|
|
21
27
|
*/
|
|
22
28
|
/** The authenticator of a Slack session's principal. */
|
|
23
29
|
export declare const SLACK_AUTHENTICATOR = "segmentstream-slack";
|
|
@@ -40,9 +46,33 @@ export interface SlackChannelOptions {
|
|
|
40
46
|
readonly fetch?: typeof fetch;
|
|
41
47
|
/** The ontology's pairing routes; tests pass a fake. */
|
|
42
48
|
readonly identities?: AgentIdentities;
|
|
49
|
+
/** The chat registry the channels are reported to; tests pass their own. */
|
|
50
|
+
readonly chats?: AgentChats;
|
|
43
51
|
/** Seconds since the epoch; tests pass a fixed clock. */
|
|
44
52
|
readonly now?: () => number;
|
|
45
53
|
}
|
|
54
|
+
/** One Slack Web API call: the method's name and its arguments, answered with Slack's JSON. */
|
|
55
|
+
export type SlackRequest = (method: string, body: Readonly<Record<string, string>>) => Promise<unknown>;
|
|
56
|
+
/**
|
|
57
|
+
* A channel's name as `conversations.info` gives it, for the chat registry. Nothing for a direct or
|
|
58
|
+
* group direct message, for a channel the agent is not in unless `left`, or when Slack does not
|
|
59
|
+
* answer, such as before the connection is authorized for `channels:read` and `groups:read`: an
|
|
60
|
+
* id is never a title.
|
|
61
|
+
*/
|
|
62
|
+
export declare function slackChannelTitle(request: SlackRequest, channelId: string, options?: {
|
|
63
|
+
readonly left?: boolean;
|
|
64
|
+
}): Promise<string | undefined>;
|
|
65
|
+
/**
|
|
66
|
+
* Reports what a membership event says about a channel to the chat registry: the agent joining it
|
|
67
|
+
* or leaving it, a paired member joining or leaving it, or its new name. eve routes no turn for
|
|
68
|
+
* these events, so the route reports them once their signature is checked.
|
|
69
|
+
*/
|
|
70
|
+
export declare function reportMembership(input: {
|
|
71
|
+
readonly envelope: unknown;
|
|
72
|
+
readonly chats: AgentChats;
|
|
73
|
+
readonly identities: AgentIdentities;
|
|
74
|
+
readonly request: SlackRequest;
|
|
75
|
+
}): Promise<void>;
|
|
46
76
|
/** The principal of a paired member's Slack session, as the Telegram channel stamps one. */
|
|
47
77
|
export declare function slackPrincipal(member: PairedMember, user: string): SessionAuthContext;
|
|
48
78
|
/**
|
|
@@ -53,8 +83,15 @@ export declare function relayedRequestVerifier(secret: () => string | undefined,
|
|
|
53
83
|
/**
|
|
54
84
|
* eve's Slack transport carried by the connection proxy: a Web API method becomes a `web` call
|
|
55
85
|
* and a file download a `files` call. The placeholder bot token never leaves this process.
|
|
86
|
+
*
|
|
87
|
+
* Redirects are followed as `fetch` follows them, which the proxy does not do for this connection:
|
|
88
|
+
* Slack answers a file's `url_private` with a redirect. A location under Slack's API or files is
|
|
89
|
+
* requested through the proxy again, which adds the bot token as before; any other HTTPS location
|
|
90
|
+
* is fetched directly with no credential, as `fetch` drops the authorization on a redirect to
|
|
91
|
+
* another origin. Every hop, wherever it answered from, is checked the same way and counts toward
|
|
92
|
+
* the same limit. A 303 continues with a GET and no body.
|
|
56
93
|
*/
|
|
57
|
-
export declare function proxiedSlackFetch(proxy: () => ConnectionProxy): typeof fetch;
|
|
94
|
+
export declare function proxiedSlackFetch(proxy: () => ConnectionProxy, directFetch?: typeof fetch): typeof fetch;
|
|
58
95
|
/** Builds the channel. Everything it reads from the mount is read per request. */
|
|
59
96
|
export declare function segmentstreamSlack(options: SlackChannelOptions): SlackChannel;
|
|
60
97
|
/**
|
|
@@ -73,10 +110,14 @@ export declare function followsThreadReply(input: {
|
|
|
73
110
|
* privately answering anyone else with the workspace's reply, if it has one.
|
|
74
111
|
*/
|
|
75
112
|
export declare function receive(input: {
|
|
76
|
-
readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit">;
|
|
113
|
+
readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit" | "slack">;
|
|
77
114
|
readonly message: Pick<SlackMessage, "author" | "text" | "attachments">;
|
|
78
115
|
readonly direct: boolean;
|
|
79
116
|
readonly admission: AdmissionSettings;
|
|
80
117
|
readonly identities: AgentIdentities;
|
|
81
118
|
readonly environment: Environment;
|
|
119
|
+
/** The chat registry a channel a paired member writes in is reported to. */
|
|
120
|
+
readonly chats?: AgentChats;
|
|
121
|
+
/** Keeps the report alive after the turn starts; without it the report is awaited. */
|
|
122
|
+
readonly waitUntil?: (task: Promise<unknown>) => void;
|
|
82
123
|
}): Promise<SlackMentionResult>;
|
|
@@ -5,23 +5,86 @@ const __filename = __eveFileURLToPath(import.meta.url);
|
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { admitMessage, localizedText } from "../admission.mjs";
|
|
8
|
+
import { agentChats } from "../chats.mjs";
|
|
8
9
|
import { withButtonDecision } from "../confirmation-buttons.mjs";
|
|
10
|
+
import { withConversation } from "../conversation.mjs";
|
|
9
11
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
10
12
|
import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
|
|
11
13
|
import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
|
|
12
14
|
import { agentIdentities } from "../identities.mjs";
|
|
13
15
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
14
16
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
17
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
18
|
import { slackChannel } from "eve/channels/slack";
|
|
16
19
|
const SLACK_AUTHENTICATOR = "segmentstream-slack";
|
|
17
20
|
const SLACK_API = "https://slack.com/api/";
|
|
18
21
|
const SLACK_FILES = "https://files.slack.com/";
|
|
19
22
|
const PLACEHOLDER = "xoxb-segmentstream-connection";
|
|
20
23
|
const MAXIMUM_SKEW_SECONDS = 300;
|
|
24
|
+
const MEMBERSHIP_EVENTS = new Set([
|
|
25
|
+
"member_joined_channel",
|
|
26
|
+
"member_left_channel",
|
|
27
|
+
"channel_rename",
|
|
28
|
+
"group_rename"
|
|
29
|
+
]);
|
|
30
|
+
const requestWork = new AsyncLocalStorage();
|
|
21
31
|
const THREAD_GUIDANCE = "You are part of this Slack thread, so you see replies people send each other. This reply doesn't mention you. Answer only if it's meant for you; otherwise call `no_reply`.";
|
|
22
32
|
var SlackProxyRouteError = class extends Error {
|
|
23
33
|
name = "SlackProxyRouteError";
|
|
24
34
|
};
|
|
35
|
+
function record(value) {
|
|
36
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
37
|
+
}
|
|
38
|
+
async function slackChannelTitle(request, channelId, options = {}) {
|
|
39
|
+
const reply = record(await request("conversations.info", { channel: channelId }));
|
|
40
|
+
const channel = record(reply.channel);
|
|
41
|
+
return reply.ok === true && channel.id === channelId && channel.is_im !== true && channel.is_mpim !== true && (options.left === true || channel.is_member === true) && typeof channel.name === "string" && channel.name.trim() !== "" ? channel.name : void 0;
|
|
42
|
+
}
|
|
43
|
+
async function reportMembership(input) {
|
|
44
|
+
const envelope = record(input.envelope);
|
|
45
|
+
const event = record(envelope.event);
|
|
46
|
+
const bot = (Array.isArray(envelope.authorizations) ? envelope.authorizations : []).map(record).find((authorization) => authorization.is_bot === true)?.user_id;
|
|
47
|
+
const renamed = record(event.channel);
|
|
48
|
+
const chatId = typeof event.channel === "string" ? event.channel : renamed.id;
|
|
49
|
+
const user = event.user;
|
|
50
|
+
if (envelope.type !== "event_callback" || typeof event.type !== "string" || !MEMBERSHIP_EVENTS.has(event.type) || typeof chatId !== "string" || chatId === "") return;
|
|
51
|
+
const title = () => slackChannelTitle(input.request, chatId);
|
|
52
|
+
if (event.type === "channel_rename" || event.type === "group_rename") {
|
|
53
|
+
await input.chats.joined({
|
|
54
|
+
chatId,
|
|
55
|
+
title
|
|
56
|
+
});
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (typeof user !== "string" || user === "") return;
|
|
60
|
+
const joined = event.type === "member_joined_channel";
|
|
61
|
+
if (typeof bot === "string" && user === bot) {
|
|
62
|
+
if (joined) await input.chats.joined({
|
|
63
|
+
chatId,
|
|
64
|
+
title
|
|
65
|
+
});
|
|
66
|
+
else await input.chats.agentLeft({
|
|
67
|
+
chatId,
|
|
68
|
+
title: async () => await slackChannelTitle(input.request, chatId, { left: true }).catch(() => void 0) ?? input.chats.chat(chatId)?.title
|
|
69
|
+
});
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const lookup = await input.identities.lookup({
|
|
73
|
+
provider: "slack",
|
|
74
|
+
externalId: user
|
|
75
|
+
});
|
|
76
|
+
if (lookup.status !== "paired") return;
|
|
77
|
+
if (joined) await input.chats.seen({
|
|
78
|
+
chatId,
|
|
79
|
+
title,
|
|
80
|
+
memberId: lookup.member.id
|
|
81
|
+
});
|
|
82
|
+
else await input.chats.left({
|
|
83
|
+
chatId,
|
|
84
|
+
title,
|
|
85
|
+
memberId: lookup.member.id
|
|
86
|
+
});
|
|
87
|
+
}
|
|
25
88
|
function slackPrincipal(member, user) {
|
|
26
89
|
return {
|
|
27
90
|
authenticator: SLACK_AUTHENTICATOR,
|
|
@@ -49,35 +112,77 @@ function relayedRequestVerifier(secret, now = () => Date.now() / 1e3) {
|
|
|
49
112
|
return true;
|
|
50
113
|
};
|
|
51
114
|
}
|
|
52
|
-
|
|
115
|
+
const MAXIMUM_SLACK_REDIRECTS = 5;
|
|
116
|
+
const REDIRECT_STATUSES = new Set([
|
|
117
|
+
301,
|
|
118
|
+
302,
|
|
119
|
+
303,
|
|
120
|
+
307,
|
|
121
|
+
308
|
|
122
|
+
]);
|
|
123
|
+
const NULL_BODY_STATUSES = new Set([
|
|
124
|
+
101,
|
|
125
|
+
204,
|
|
126
|
+
205,
|
|
127
|
+
304
|
|
128
|
+
]);
|
|
129
|
+
function proxiedSlackFetch(proxy, directFetch = fetch) {
|
|
53
130
|
return async (input, init) => {
|
|
54
131
|
const request = new Request(input, init);
|
|
55
|
-
const url = new URL(request.url);
|
|
56
132
|
const headers = [...request.headers].filter(([name]) => name.toLowerCase() !== "authorization").map(([name, value]) => [name, value]);
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
let
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
133
|
+
let url = new URL(request.url);
|
|
134
|
+
let method = request.method.toUpperCase();
|
|
135
|
+
let body = new Uint8Array(await request.arrayBuffer());
|
|
136
|
+
for (let redirects = 0;; redirects += 1) {
|
|
137
|
+
const slack = url.href.startsWith(SLACK_API) || url.href.startsWith(SLACK_FILES);
|
|
138
|
+
let response;
|
|
139
|
+
if (slack) {
|
|
140
|
+
const reply = url.href.startsWith(SLACK_API) ? await proxy().request({
|
|
141
|
+
api: "web",
|
|
142
|
+
method,
|
|
143
|
+
path: `/${url.href.slice(22)}`,
|
|
144
|
+
headers,
|
|
145
|
+
body
|
|
146
|
+
}, request.signal) : await proxy().download({
|
|
147
|
+
api: "files",
|
|
148
|
+
method,
|
|
149
|
+
path: `/${url.href.slice(24)}`,
|
|
150
|
+
headers,
|
|
151
|
+
body
|
|
152
|
+
}, MAXIMUM_DOWNLOAD_BYTES, request.signal);
|
|
153
|
+
response = new Response(reply.body.byteLength === 0 || NULL_BODY_STATUSES.has(reply.status) ? null : Buffer.from(reply.body), {
|
|
154
|
+
status: reply.status,
|
|
155
|
+
headers: reply.headers.map(([name, value]) => [name, value])
|
|
156
|
+
});
|
|
157
|
+
} else if (redirects === 0) throw new SlackProxyRouteError("The Slack channel reaches only Slack's API and files.");
|
|
158
|
+
else if (method !== "GET" && method !== "HEAD") throw new SlackProxyRouteError("Slack redirected a call with a body to another host.");
|
|
159
|
+
else response = await directFetch(url, {
|
|
160
|
+
method,
|
|
161
|
+
redirect: "manual",
|
|
162
|
+
signal: request.signal
|
|
163
|
+
});
|
|
164
|
+
const location = response.headers.get("location");
|
|
165
|
+
if (!REDIRECT_STATUSES.has(response.status) || location === null || redirects === MAXIMUM_SLACK_REDIRECTS) return response;
|
|
166
|
+
const next = followable(location, url);
|
|
167
|
+
if (next === void 0) throw new SlackProxyRouteError("Slack redirected the call to an address it cannot follow.");
|
|
168
|
+
await response.body?.cancel();
|
|
169
|
+
if (response.status === 303) {
|
|
170
|
+
method = "GET";
|
|
171
|
+
body = new Uint8Array();
|
|
172
|
+
}
|
|
173
|
+
url = next;
|
|
174
|
+
}
|
|
79
175
|
};
|
|
80
176
|
}
|
|
177
|
+
function followable(location, base) {
|
|
178
|
+
let next;
|
|
179
|
+
try {
|
|
180
|
+
next = new URL(location, base);
|
|
181
|
+
} catch {
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
return next.protocol === "https:" && next.username === "" && next.password === "" ? next : void 0;
|
|
185
|
+
}
|
|
81
186
|
function segmentstreamSlack(options) {
|
|
82
187
|
const environment = options.environment ?? process.env;
|
|
83
188
|
const token = options.token ?? runtimeToken;
|
|
@@ -103,6 +208,19 @@ function segmentstreamSlack(options) {
|
|
|
103
208
|
token,
|
|
104
209
|
...options.fetch === void 0 ? {} : { fetch: options.fetch }
|
|
105
210
|
});
|
|
211
|
+
const chats = options.chats ?? agentChats({
|
|
212
|
+
provider: "slack",
|
|
213
|
+
identities: pairing
|
|
214
|
+
});
|
|
215
|
+
const slackFetch = proxiedSlackFetch(proxy);
|
|
216
|
+
const request = async (method, body) => {
|
|
217
|
+
return (await slackFetch(`${SLACK_API}${method}`, {
|
|
218
|
+
method: "POST",
|
|
219
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
220
|
+
body: new URLSearchParams(body).toString()
|
|
221
|
+
})).json();
|
|
222
|
+
};
|
|
223
|
+
const verify = relayedRequestVerifier(() => webhookSecret(environment), options.now ?? (() => Date.now() / 1e3));
|
|
106
224
|
async function pairedPrincipal(user) {
|
|
107
225
|
const lookup = await pairing().lookup({
|
|
108
226
|
provider: "slack",
|
|
@@ -110,23 +228,45 @@ function segmentstreamSlack(options) {
|
|
|
110
228
|
});
|
|
111
229
|
return lookup.status === "paired" ? slackPrincipal(lookup.member, user) : null;
|
|
112
230
|
}
|
|
113
|
-
const admit = (direct) => (ctx, message) =>
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
231
|
+
const admit = (direct) => (ctx, message) => {
|
|
232
|
+
const waitUntil = requestWork.getStore();
|
|
233
|
+
return receive({
|
|
234
|
+
ctx,
|
|
235
|
+
message,
|
|
236
|
+
direct,
|
|
237
|
+
admission: options.admission(),
|
|
238
|
+
identities: pairing(),
|
|
239
|
+
environment,
|
|
240
|
+
chats,
|
|
241
|
+
...waitUntil === void 0 ? {} : { waitUntil }
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
const observe = async (relayed, waitUntil) => {
|
|
245
|
+
let envelope;
|
|
246
|
+
try {
|
|
247
|
+
const body = await relayed.clone().text();
|
|
248
|
+
envelope = JSON.parse(body);
|
|
249
|
+
if (!MEMBERSHIP_EVENTS.has(String(record(record(envelope).event).type))) return;
|
|
250
|
+
verify(relayed, body);
|
|
251
|
+
} catch {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
waitUntil(reportMembership({
|
|
255
|
+
envelope,
|
|
256
|
+
chats,
|
|
257
|
+
identities: pairing(),
|
|
258
|
+
request
|
|
259
|
+
}).catch((error) => report("membership_report_failed", error)));
|
|
260
|
+
};
|
|
121
261
|
const channel = slackChannel({
|
|
122
262
|
credentials: {
|
|
123
263
|
botToken: PLACEHOLDER,
|
|
124
|
-
webhookVerifier:
|
|
264
|
+
webhookVerifier: verify
|
|
125
265
|
},
|
|
126
266
|
api: {
|
|
127
267
|
apiBaseUrl: SLACK_API,
|
|
128
268
|
fileBaseUrl: SLACK_FILES,
|
|
129
|
-
fetch:
|
|
269
|
+
fetch: slackFetch
|
|
130
270
|
},
|
|
131
271
|
onAppMention: admit(false),
|
|
132
272
|
onDirectMessage: admit(true),
|
|
@@ -151,7 +291,7 @@ function segmentstreamSlack(options) {
|
|
|
151
291
|
});
|
|
152
292
|
return {
|
|
153
293
|
...channel,
|
|
154
|
-
routes: channel.routes.map((route) => gatedRoute(route, options, environment))
|
|
294
|
+
routes: channel.routes.map((route) => gatedRoute(route, options, environment, observe))
|
|
155
295
|
};
|
|
156
296
|
}
|
|
157
297
|
async function followsThreadReply(input) {
|
|
@@ -159,11 +299,16 @@ async function followsThreadReply(input) {
|
|
|
159
299
|
if (message.author?.isBot !== false || message.threadTs === message.ts || input.mode === "mention") return false;
|
|
160
300
|
return ctx.edit !== void 0 || await ctx.isSubscribed();
|
|
161
301
|
}
|
|
162
|
-
function gatedRoute(route, options, environment) {
|
|
302
|
+
function gatedRoute(route, options, environment, observe) {
|
|
163
303
|
if (route.transport === "websocket") return route;
|
|
164
304
|
return {
|
|
165
305
|
...route,
|
|
166
|
-
handler: async (request, args) =>
|
|
306
|
+
handler: async (request, args) => {
|
|
307
|
+
if (!channelsEnabled(environment) || options.settings() === null || webhookSecret(environment) === void 0) return new Response(null, { status: 404 });
|
|
308
|
+
const waitUntil = (task) => args.waitUntil(task);
|
|
309
|
+
await observe(request, waitUntil);
|
|
310
|
+
return requestWork.run(waitUntil, () => route.handler(request, args));
|
|
311
|
+
}
|
|
167
312
|
};
|
|
168
313
|
}
|
|
169
314
|
async function receive(input) {
|
|
@@ -189,7 +334,24 @@ async function receive(input) {
|
|
|
189
334
|
});
|
|
190
335
|
switch (resolution.status) {
|
|
191
336
|
case "existing":
|
|
192
|
-
case "created":
|
|
337
|
+
case "created":
|
|
338
|
+
if (turn && !input.direct && input.chats !== void 0) {
|
|
339
|
+
const channelId = ctx.slack.channelId;
|
|
340
|
+
const reported = input.chats.seen({
|
|
341
|
+
chatId: channelId,
|
|
342
|
+
title: () => slackChannelTitle((method, body) => ctx.slack.request(method, body), channelId),
|
|
343
|
+
memberId: resolution.member.id
|
|
344
|
+
});
|
|
345
|
+
if (input.waitUntil === void 0) await reported;
|
|
346
|
+
else input.waitUntil(reported);
|
|
347
|
+
}
|
|
348
|
+
return turn ? { auth: withConversation(slackPrincipal(resolution.member, user), {
|
|
349
|
+
provider: "slack",
|
|
350
|
+
chatId: ctx.slack.channelId,
|
|
351
|
+
threadId: ctx.slack.threadTs,
|
|
352
|
+
kind: input.direct ? "private" : "group",
|
|
353
|
+
...input.direct ? { peer: user } : {}
|
|
354
|
+
}) } : null;
|
|
193
355
|
case "pairing_required": {
|
|
194
356
|
const text = localizedText(admission.replies.pairingRequired);
|
|
195
357
|
if (text !== void 0 && ctx.edit === void 0) {
|
|
@@ -236,4 +398,4 @@ function report(operation, error) {
|
|
|
236
398
|
function digest(value) {
|
|
237
399
|
return createHash("sha256").update(value, "utf8").digest();
|
|
238
400
|
}
|
|
239
|
-
export { SLACK_AUTHENTICATOR, SlackProxyRouteError, followsThreadReply, proxiedSlackFetch, receive, relayedRequestVerifier, segmentstreamSlack, slackPrincipal };
|
|
401
|
+
export { SLACK_AUTHENTICATOR, SlackProxyRouteError, followsThreadReply, proxiedSlackFetch, receive, relayedRequestVerifier, reportMembership, segmentstreamSlack, slackChannelTitle, slackPrincipal };
|
|
@@ -6,7 +6,7 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { object } from "./confirmation-description.mjs";
|
|
8
8
|
import { OntologyFileUnavailable, ontologyTools } from "./ontology-tools.mjs";
|
|
9
|
-
import { i as memberIdOf } from "../../_chunks/principal-
|
|
9
|
+
import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
|
|
10
10
|
import { member } from "./actor.mjs";
|
|
11
11
|
import { redactDiagnostic } from "./diagnostics.mjs";
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
@@ -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-C0Kz75P3.mjs";
|
|
14
14
|
import { attachmentLifecycle } from "./lifecycle.mjs";
|
|
15
15
|
import { manifestOf } from "../../config.mjs";
|
|
16
16
|
import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
|
|
@@ -27,10 +27,10 @@ import { botIdentityCache } from "./bot.mjs";
|
|
|
27
27
|
import { handleConfirmationCallback, telegramConfirmationEvents } from "./confirmations.mjs";
|
|
28
28
|
import { confirmationLocale } from "./confirmation-text.mjs";
|
|
29
29
|
import { d as failureText, h as withDeliveryLocale, i as withReplacedText, m as safeTelegramFetch, n as currentInboundRequest, o as currentLocale, p as reportTelegramError, r as runInboundRequest, t as InboundRequest } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
|
|
30
|
-
import { n as conversationLanguage, o as telegramPrincipal } from "../../../_chunks/principal-
|
|
30
|
+
import { n as conversationLanguage, o as telegramPrincipal } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
31
31
|
import { gatewayImageDescriber } from "./images.mjs";
|
|
32
32
|
import { gatewayMediaCapabilities, planMedia } from "./media-policy.mjs";
|
|
33
|
-
import { agentChats } from "
|
|
33
|
+
import { agentChats } from "../chats.mjs";
|
|
34
34
|
import { handleInboundMessage } from "./inbound.mjs";
|
|
35
35
|
import { recoverableSessions } from "./session-recovery.mjs";
|
|
36
36
|
import { TELEGRAM_PLACEHOLDER_TOKEN, TELEGRAM_PROXY_ORIGIN, telegramProxyFetch } from "./proxy-fetch.mjs";
|
|
@@ -120,7 +120,10 @@ function segmentstreamTelegram(options) {
|
|
|
120
120
|
});
|
|
121
121
|
return identities;
|
|
122
122
|
}
|
|
123
|
-
const chats = agentChats({
|
|
123
|
+
const chats = agentChats({
|
|
124
|
+
provider: "telegram",
|
|
125
|
+
identities: pairing
|
|
126
|
+
});
|
|
124
127
|
const capture = telegramConversationCapture({
|
|
125
128
|
archive,
|
|
126
129
|
identities: pairing,
|
|
@@ -12,7 +12,7 @@ import { fetchFileGrant, transientFileStatus } from "../file-grant.mjs";
|
|
|
12
12
|
import { appOrigin, channelsEnabled, proxyEnvironment } from "../environment.mjs";
|
|
13
13
|
import { ACT_AS_HEADER } from "../actor.mjs";
|
|
14
14
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
15
|
-
import "../../../_chunks/principal-
|
|
15
|
+
import "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
16
16
|
import { confirmationLocale } from "./confirmation-text.mjs";
|
|
17
17
|
import { inTelegramSendQueue, telegramSendScope } from "./send-queue.mjs";
|
|
18
18
|
import { d as failureText, f as formattingRefused, l as customerMessage, p as reportTelegramError } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
|
|
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
|
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { object } from "../confirmation-description.mjs";
|
|
8
|
-
import { d as telegramRuntimeSource, i as memberIdOf, o as telegramPrincipal, u as runtimeEnvelope } from "../../../_chunks/principal-
|
|
8
|
+
import { d as telegramRuntimeSource, i as memberIdOf, o as telegramPrincipal, u as runtimeEnvelope } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
9
9
|
import { n as currentInboundRequest, p as reportTelegramError } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
|
|
10
10
|
import { formatAddress, parseAddress, scopedAddress } from "./sessions.mjs";
|
|
11
11
|
import { telegramText } from "./texts.mjs";
|
|
@@ -4,6 +4,17 @@ import type { ConfirmationDescription } from "../confirmation-description.js";
|
|
|
4
4
|
export declare function withChatPostCard<T>(text: string, run: () => T, links?: readonly string[]): T;
|
|
5
5
|
export declare function isExactChatPostCard(text: string): boolean;
|
|
6
6
|
export declare function chatPostCardLinks(text: string): readonly string[] | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* The same card as plain text, for a channel that shows eve's own approval card: the message is
|
|
9
|
+
* the member's exact Markdown and the attribution the ontology adds, as the destination receives
|
|
10
|
+
* them. Never cut: the channel's length check refuses a card that does not fit.
|
|
11
|
+
*/
|
|
12
|
+
export declare function chatPostPrompt(description: ConfirmationDescription, copy?: ConfirmationCopy): string;
|
|
13
|
+
/**
|
|
14
|
+
* The Telegram card. A Telegram destination's message is its exact MarkdownV2, as the chat shows
|
|
15
|
+
* it; another provider's is shown as the member's exact Markdown and the attribution, as literal
|
|
16
|
+
* text, since its rendering is not Telegram's.
|
|
17
|
+
*/
|
|
7
18
|
export declare function chatPostCard(description: ConfirmationDescription, copy?: ConfirmationCopy): ConfirmationText;
|
|
8
19
|
/** Status/receipt strings are data outside the already rendered preview. */
|
|
9
20
|
export declare function chatPostCardStatus(text: string, status: string): string;
|
|
@@ -25,27 +25,42 @@ function chatPostCardLinks(text) {
|
|
|
25
25
|
const card = exactText.getStore();
|
|
26
26
|
return card?.text === text ? card.links : void 0;
|
|
27
27
|
}
|
|
28
|
-
function
|
|
28
|
+
function chatPostHeading(description, copy) {
|
|
29
29
|
const preview = description.chatPost;
|
|
30
30
|
if (preview === void 0) throw new Error("An exact chat preview is required.");
|
|
31
31
|
const base = renderConfirmation(description, copy);
|
|
32
|
-
const
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
32
|
+
const group = preview.provider === "telegram" ? preview.externalId.startsWith("-") : !preview.chatId.startsWith(`${preview.provider}:private:`);
|
|
33
|
+
const destination = telegramText("chatPost", group ? "previewGroup" : "previewPrivate")?.replace(/\{(recipient|signature|provider)\}/gu, (_, key) => key === "recipient" ? preview.title : key === "signature" ? preview.attribution : preview.provider);
|
|
34
|
+
return {
|
|
35
|
+
preview,
|
|
36
|
+
base,
|
|
37
|
+
lines: [
|
|
38
|
+
base.text,
|
|
39
|
+
destination ?? `${preview.title} (${preview.provider})`,
|
|
40
|
+
...preview.replyTo === null ? [] : [preview.replyTo]
|
|
41
|
+
]
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function chatPostPrompt(description, copy) {
|
|
45
|
+
const { preview, lines } = chatPostHeading(description, copy);
|
|
46
|
+
return `${lines.join("\n")}\n\n${preview.text}${preview.attributionSeparator ?? "\n\n"}${preview.attribution}`;
|
|
47
|
+
}
|
|
48
|
+
function chatPostCard(description, copy) {
|
|
49
|
+
const { preview, base, lines } = chatPostHeading(description, copy);
|
|
50
|
+
const separator = preview.attributionSeparator ?? "\n\n";
|
|
51
|
+
const literal = `${preview.text}${separator}${preview.attribution}`;
|
|
52
|
+
const message = preview.provider === "telegram" ? preview.finalText : escapeMarkdownV2(literal);
|
|
53
|
+
const text = lines.map(escapeMarkdownV2).join("\n") + `\n\n${message}`;
|
|
38
54
|
const receiptSpace = RECEIPT_DATA_SPACE + Math.max(...["sent", "uncertain"].map((status) => escapeMarkdownV2(telegramText("chatPost", status) ?? "").length)) + escapeMarkdownV2(telegramText("chatPost", "historyNotRecorded") ?? "").length;
|
|
39
55
|
if (text.length > 4096 - receiptSpace) throw new Error("The full message and receipt cannot fit in one Telegram confirmation. Make a shorter draft.");
|
|
40
56
|
return {
|
|
41
57
|
...base,
|
|
42
58
|
text,
|
|
43
|
-
previewLinks: [
|
|
44
|
-
...telegramTextLinks(`${preview.title}\n${preview.replyTo ?? ""}`),
|
|
59
|
+
previewLinks: [...telegramTextLinks(`${preview.title}\n${preview.replyTo ?? ""}`), ...preview.provider === "telegram" ? [
|
|
45
60
|
...telegramMarkdownLinks(preview.text),
|
|
46
|
-
...telegramTextLinks(
|
|
61
|
+
...telegramTextLinks(separator),
|
|
47
62
|
...telegramTextLinks(preview.attribution)
|
|
48
|
-
]
|
|
63
|
+
] : telegramTextLinks(literal)]
|
|
49
64
|
};
|
|
50
65
|
}
|
|
51
66
|
function chatPostCardStatus(text, status) {
|
|
@@ -61,4 +76,4 @@ function chatPostReceipt(output) {
|
|
|
61
76
|
...value.history_recorded ? [] : [telegramText("chatPost", "historyNotRecorded")]
|
|
62
77
|
].filter((line) => line !== void 0).join("\n");
|
|
63
78
|
}
|
|
64
|
-
export { chatPostCard, chatPostCardLinks, chatPostCardStatus, chatPostReceipt, isExactChatPostCard, withChatPostCard };
|
|
79
|
+
export { chatPostCard, chatPostCardLinks, chatPostCardStatus, chatPostPrompt, chatPostReceipt, isExactChatPostCard, withChatPostCard };
|
|
@@ -14,7 +14,7 @@ import { chatPostCard, chatPostCardStatus, chatPostReceipt, withChatPostCard } f
|
|
|
14
14
|
import { answerMarker, isPendingQuestion, pendingQuestions, questionKey } from "../questions.mjs";
|
|
15
15
|
import { n as currentInboundRequest, p as reportTelegramError } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
|
|
16
16
|
import { confirmationStatus, renderConfirmation, withConfirmationText } from "./confirmation-text.mjs";
|
|
17
|
-
import { i as memberIdOf, o as telegramPrincipal } from "../../../_chunks/principal-
|
|
17
|
+
import { i as memberIdOf, o as telegramPrincipal } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
18
18
|
import { formatAddress, scopedAddress } from "./sessions.mjs";
|
|
19
19
|
import { createHash } from "node:crypto";
|
|
20
20
|
import { telegramTextLinks } from "@segmentstream/ontology/telegram";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { StructuredMessage } from "./structured.js";
|
|
2
2
|
import type { AgentIdentities } from "../identities.js";
|
|
3
3
|
import { type Conversations } from "../conversations.js";
|
|
4
|
-
import type { AgentChats } from "
|
|
4
|
+
import type { AgentChats } from "../chats.js";
|
|
5
5
|
import type { DecodedAttachment } from "./attachment-description.js";
|
|
6
6
|
import type { AddressingReason, RouteDecider, RouteDecision } from "./router.js";
|
|
7
7
|
/** A crashed routing attempt can be reclaimed; the per-message turn claim still fences dispatch. */
|
|
@@ -6,7 +6,7 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { MAXIMUM_ATTACHMENT_BYTES, attachmentUrl } from "../attachments.mjs";
|
|
8
8
|
import { d as failureText, p as reportTelegramError } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
|
|
9
|
-
import { n as conversationLanguage } from "../../../_chunks/principal-
|
|
9
|
+
import { n as conversationLanguage } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
10
10
|
import { describableImage, describeReceivedImage } from "./images.mjs";
|
|
11
11
|
function telegramConversation(chatId) {
|
|
12
12
|
return `telegram:${chatId}`;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type RouteDefinition } from "eve/channels";
|
|
2
2
|
import type { TelegramChannelState } from "eve/channels/telegram";
|
|
3
3
|
import type { RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
4
|
-
import type { AgentChats } from "
|
|
4
|
+
import type { AgentChats } from "../chats.js";
|
|
5
5
|
export declare const HEALTH_ROUTE = "/eve/v1/telegram/health";
|
|
6
6
|
/** Runtime-only, per-instance health. It never exposes credentials or private provider bodies. */
|
|
7
7
|
export declare function healthRoute(input: {
|
|
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
|
|
|
4
4
|
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
|
-
import { t as agentBuild } from "../../../_chunks/build-metadata-
|
|
7
|
+
import { t as agentBuild } from "../../../_chunks/build-metadata-C0Kz75P3.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";
|
|
@@ -8,7 +8,7 @@ import type { AdmissionSettings, SessionSettings, TelegramPolicy } from "../../c
|
|
|
8
8
|
import type { AgentAttachments } from "../attachments.js";
|
|
9
9
|
import type { AgentIdentities, PairedMember } from "../identities.js";
|
|
10
10
|
import type { BotIdentityLookup } from "./bot.js";
|
|
11
|
-
import { type AgentChats } from "
|
|
11
|
+
import { type AgentChats } from "../chats.js";
|
|
12
12
|
import type { InboundRequest } from "./inbound-request.js";
|
|
13
13
|
import type { ImageDescriber } from "./images.js";
|
|
14
14
|
import type { MediaPlan } from "./media-policy.js";
|
|
@@ -6,7 +6,7 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { WorkspaceActionAlreadyDispatched } from "./workspace-action.mjs";
|
|
8
8
|
import { structuredMessage } from "./structured.mjs";
|
|
9
|
-
import { d as telegramRuntimeSource, n as conversationLanguage, o as telegramPrincipal, u as runtimeEnvelope } from "../../../_chunks/principal-
|
|
9
|
+
import { d as telegramRuntimeSource, n as conversationLanguage, o as telegramPrincipal, u as runtimeEnvelope } from "../../../_chunks/principal-BIX7T6Hh.mjs";
|
|
10
10
|
import { routingBurst } from "../group-routing/burst.mjs";
|
|
11
11
|
import { telegramSignals } from "./signals.mjs";
|
|
12
12
|
import { addressingReason, conversationKey, otherRecipient } from "../group-routing/signals.mjs";
|
|
@@ -14,7 +14,7 @@ import { effectiveGroupPolicy, groupPolicy } from "../group-routing/policy.mjs";
|
|
|
14
14
|
import { questionInvitation } from "../group-routing/engagement.mjs";
|
|
15
15
|
import { AttachmentLifecycleNotPermitted } from "./lifecycle.mjs";
|
|
16
16
|
import { admitMessage, localizedText } from "../admission.mjs";
|
|
17
|
-
import { chatContext } from "
|
|
17
|
+
import { chatContext } from "../chats.mjs";
|
|
18
18
|
import { questionAddress, questionFromHistory } from "./confirmations.mjs";
|
|
19
19
|
import { answerMarker } from "../questions.mjs";
|
|
20
20
|
import { attachmentsContext, inboundAttachments, stageFiles } from "./files.mjs";
|