@segmentstream/agent 0.36.3 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +23 -4
  2. package/dist/_chunks/{build-metadata-D3ytCxvV.mjs → build-metadata-CnjDv9p8.mjs} +1 -1
  3. package/dist/_chunks/{principal-UlkbLrgQ.mjs → principal-BIX7T6Hh.mjs} +1 -1
  4. package/dist/extension/hooks/authorization.mjs +1 -1
  5. package/dist/extension/instructions.md +3 -3
  6. package/dist/extension/lib/actor.mjs +1 -1
  7. package/dist/extension/lib/attachment-tools.mjs +1 -1
  8. package/dist/extension/lib/build-metadata.mjs +1 -1
  9. package/dist/extension/lib/chat-post-confirmation.d.ts +3 -1
  10. package/dist/extension/lib/chat-post-confirmation.mjs +8 -5
  11. package/dist/extension/lib/{telegram/chats.d.ts → chats.d.ts} +14 -4
  12. package/dist/extension/lib/{telegram/chats.mjs → chats.mjs} +33 -17
  13. package/dist/extension/lib/confirmations.d.ts +3 -4
  14. package/dist/extension/lib/confirmations.mjs +16 -11
  15. package/dist/extension/lib/conversation-runtime.mjs +1 -1
  16. package/dist/extension/lib/conversation.d.ts +33 -0
  17. package/dist/extension/lib/conversation.mjs +55 -0
  18. package/dist/extension/lib/ontology-connection.mjs +11 -4
  19. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  20. package/dist/extension/lib/ontology-tools.mjs +1 -1
  21. package/dist/extension/lib/runtime-envelope.d.ts +5 -1
  22. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  23. package/dist/extension/lib/slack/adapter.d.ts +34 -1
  24. package/dist/extension/lib/slack/adapter.mjs +135 -15
  25. package/dist/extension/lib/stored-files.mjs +1 -1
  26. package/dist/extension/lib/telegram/adapter.mjs +7 -4
  27. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  28. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  29. package/dist/extension/lib/telegram/chat-post-card.d.ts +11 -0
  30. package/dist/extension/lib/telegram/chat-post-card.mjs +27 -12
  31. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  32. package/dist/extension/lib/telegram/conversations.d.ts +1 -1
  33. package/dist/extension/lib/telegram/files.mjs +1 -1
  34. package/dist/extension/lib/telegram/health.d.ts +1 -1
  35. package/dist/extension/lib/telegram/health.mjs +1 -1
  36. package/dist/extension/lib/telegram/inbound.d.ts +1 -1
  37. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  38. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  39. package/dist/extension/lib/telegram/membership.d.ts +1 -1
  40. package/dist/extension/lib/telegram/principal.mjs +1 -1
  41. package/dist/extension/lib/telegram/structured.mjs +1 -1
  42. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  43. package/dist/extension/lib/whatsapp/adapter.d.ts +2 -0
  44. package/dist/extension/lib/whatsapp/adapter.mjs +8 -1
  45. package/dist/extension/model.mjs +1 -1
  46. package/dist/extension/tools/attachments_promote.mjs +1 -1
  47. package/dist/extension/tools/questions_ask.mjs +1 -1
  48. package/package.json +2 -2
@@ -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";
@@ -18,6 +19,10 @@ import { type RuntimeToken } from "../runtime-token.js";
18
19
  * replies continue it, and approvals and questions are buttons. Only paired members are answered;
19
20
  * anyone else gets the workspace's `replies.pairingRequired` text and a link to the app's
20
21
  * `/agent/connect`, privately.
22
+ *
23
+ * The channels the agent is in are reported to the ontology's `agent_chat` registry, titled as
24
+ * Slack names them, when a paired member writes there and when the agent joins, leaves or sees one
25
+ * renamed. Direct and group direct messages are never reported.
21
26
  */
22
27
  /** The authenticator of a Slack session's principal. */
23
28
  export declare const SLACK_AUTHENTICATOR = "segmentstream-slack";
@@ -40,9 +45,33 @@ export interface SlackChannelOptions {
40
45
  readonly fetch?: typeof fetch;
41
46
  /** The ontology's pairing routes; tests pass a fake. */
42
47
  readonly identities?: AgentIdentities;
48
+ /** The chat registry the channels are reported to; tests pass their own. */
49
+ readonly chats?: AgentChats;
43
50
  /** Seconds since the epoch; tests pass a fixed clock. */
44
51
  readonly now?: () => number;
45
52
  }
53
+ /** One Slack Web API call: the method's name and its arguments, answered with Slack's JSON. */
54
+ export type SlackRequest = (method: string, body: Readonly<Record<string, string>>) => Promise<unknown>;
55
+ /**
56
+ * A channel's name as `conversations.info` gives it, for the chat registry. Nothing for a direct or
57
+ * group direct message, for a channel the agent is not in unless `left`, or when Slack does not
58
+ * answer, such as before the connection is authorized for `channels:read` and `groups:read`: an
59
+ * id is never a title.
60
+ */
61
+ export declare function slackChannelTitle(request: SlackRequest, channelId: string, options?: {
62
+ readonly left?: boolean;
63
+ }): Promise<string | undefined>;
64
+ /**
65
+ * Reports what a membership event says about a channel to the chat registry: the agent joining it
66
+ * or leaving it, a paired member joining or leaving it, or its new name. eve routes no turn for
67
+ * these events, so the route reports them once their signature is checked.
68
+ */
69
+ export declare function reportMembership(input: {
70
+ readonly envelope: unknown;
71
+ readonly chats: AgentChats;
72
+ readonly identities: AgentIdentities;
73
+ readonly request: SlackRequest;
74
+ }): Promise<void>;
46
75
  /** The principal of a paired member's Slack session, as the Telegram channel stamps one. */
47
76
  export declare function slackPrincipal(member: PairedMember, user: string): SessionAuthContext;
48
77
  /**
@@ -73,10 +102,14 @@ export declare function followsThreadReply(input: {
73
102
  * privately answering anyone else with the workspace's reply, if it has one.
74
103
  */
75
104
  export declare function receive(input: {
76
- readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit">;
105
+ readonly ctx: Pick<SlackInboundMessageContext, "thread" | "edit" | "slack">;
77
106
  readonly message: Pick<SlackMessage, "author" | "text" | "attachments">;
78
107
  readonly direct: boolean;
79
108
  readonly admission: AdmissionSettings;
80
109
  readonly identities: AgentIdentities;
81
110
  readonly environment: Environment;
111
+ /** The chat registry a channel a paired member writes in is reported to. */
112
+ readonly chats?: AgentChats;
113
+ /** Keeps the report alive after the turn starts; without it the report is awaited. */
114
+ readonly waitUntil?: (task: Promise<unknown>) => void;
82
115
  }): 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,
@@ -103,6 +166,19 @@ function segmentstreamSlack(options) {
103
166
  token,
104
167
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
105
168
  });
169
+ const chats = options.chats ?? agentChats({
170
+ provider: "slack",
171
+ identities: pairing
172
+ });
173
+ const slackFetch = proxiedSlackFetch(proxy);
174
+ const request = async (method, body) => {
175
+ return (await slackFetch(`${SLACK_API}${method}`, {
176
+ method: "POST",
177
+ headers: { "content-type": "application/x-www-form-urlencoded" },
178
+ body: new URLSearchParams(body).toString()
179
+ })).json();
180
+ };
181
+ const verify = relayedRequestVerifier(() => webhookSecret(environment), options.now ?? (() => Date.now() / 1e3));
106
182
  async function pairedPrincipal(user) {
107
183
  const lookup = await pairing().lookup({
108
184
  provider: "slack",
@@ -110,23 +186,45 @@ function segmentstreamSlack(options) {
110
186
  });
111
187
  return lookup.status === "paired" ? slackPrincipal(lookup.member, user) : null;
112
188
  }
113
- const admit = (direct) => (ctx, message) => receive({
114
- ctx,
115
- message,
116
- direct,
117
- admission: options.admission(),
118
- identities: pairing(),
119
- environment
120
- });
189
+ const admit = (direct) => (ctx, message) => {
190
+ const waitUntil = requestWork.getStore();
191
+ return receive({
192
+ ctx,
193
+ message,
194
+ direct,
195
+ admission: options.admission(),
196
+ identities: pairing(),
197
+ environment,
198
+ chats,
199
+ ...waitUntil === void 0 ? {} : { waitUntil }
200
+ });
201
+ };
202
+ const observe = async (relayed, waitUntil) => {
203
+ let envelope;
204
+ try {
205
+ const body = await relayed.clone().text();
206
+ envelope = JSON.parse(body);
207
+ if (!MEMBERSHIP_EVENTS.has(String(record(record(envelope).event).type))) return;
208
+ verify(relayed, body);
209
+ } catch {
210
+ return;
211
+ }
212
+ waitUntil(reportMembership({
213
+ envelope,
214
+ chats,
215
+ identities: pairing(),
216
+ request
217
+ }).catch((error) => report("membership_report_failed", error)));
218
+ };
121
219
  const channel = slackChannel({
122
220
  credentials: {
123
221
  botToken: PLACEHOLDER,
124
- webhookVerifier: relayedRequestVerifier(() => webhookSecret(environment), options.now ?? (() => Date.now() / 1e3))
222
+ webhookVerifier: verify
125
223
  },
126
224
  api: {
127
225
  apiBaseUrl: SLACK_API,
128
226
  fileBaseUrl: SLACK_FILES,
129
- fetch: proxiedSlackFetch(proxy)
227
+ fetch: slackFetch
130
228
  },
131
229
  onAppMention: admit(false),
132
230
  onDirectMessage: admit(true),
@@ -151,7 +249,7 @@ function segmentstreamSlack(options) {
151
249
  });
152
250
  return {
153
251
  ...channel,
154
- routes: channel.routes.map((route) => gatedRoute(route, options, environment))
252
+ routes: channel.routes.map((route) => gatedRoute(route, options, environment, observe))
155
253
  };
156
254
  }
157
255
  async function followsThreadReply(input) {
@@ -159,11 +257,16 @@ async function followsThreadReply(input) {
159
257
  if (message.author?.isBot !== false || message.threadTs === message.ts || input.mode === "mention") return false;
160
258
  return ctx.edit !== void 0 || await ctx.isSubscribed();
161
259
  }
162
- function gatedRoute(route, options, environment) {
260
+ function gatedRoute(route, options, environment, observe) {
163
261
  if (route.transport === "websocket") return route;
164
262
  return {
165
263
  ...route,
166
- handler: async (request, args) => channelsEnabled(environment) && options.settings() !== null && webhookSecret(environment) !== void 0 ? route.handler(request, args) : new Response(null, { status: 404 })
264
+ handler: async (request, args) => {
265
+ if (!channelsEnabled(environment) || options.settings() === null || webhookSecret(environment) === void 0) return new Response(null, { status: 404 });
266
+ const waitUntil = (task) => args.waitUntil(task);
267
+ await observe(request, waitUntil);
268
+ return requestWork.run(waitUntil, () => route.handler(request, args));
269
+ }
167
270
  };
168
271
  }
169
272
  async function receive(input) {
@@ -189,7 +292,24 @@ async function receive(input) {
189
292
  });
190
293
  switch (resolution.status) {
191
294
  case "existing":
192
- case "created": return turn ? { auth: slackPrincipal(resolution.member, user) } : null;
295
+ case "created":
296
+ if (turn && !input.direct && input.chats !== void 0) {
297
+ const channelId = ctx.slack.channelId;
298
+ const reported = input.chats.seen({
299
+ chatId: channelId,
300
+ title: () => slackChannelTitle((method, body) => ctx.slack.request(method, body), channelId),
301
+ memberId: resolution.member.id
302
+ });
303
+ if (input.waitUntil === void 0) await reported;
304
+ else input.waitUntil(reported);
305
+ }
306
+ return turn ? { auth: withConversation(slackPrincipal(resolution.member, user), {
307
+ provider: "slack",
308
+ chatId: ctx.slack.channelId,
309
+ threadId: ctx.slack.threadTs,
310
+ kind: input.direct ? "private" : "group",
311
+ ...input.direct ? { peer: user } : {}
312
+ }) } : null;
193
313
  case "pairing_required": {
194
314
  const text = localizedText(admission.replies.pairingRequired);
195
315
  if (text !== void 0 && ctx.edit === void 0) {
@@ -236,4 +356,4 @@ function report(operation, error) {
236
356
  function digest(value) {
237
357
  return createHash("sha256").update(value, "utf8").digest();
238
358
  }
239
- export { SLACK_AUTHENTICATOR, SlackProxyRouteError, followsThreadReply, proxiedSlackFetch, receive, relayedRequestVerifier, segmentstreamSlack, slackPrincipal };
359
+ 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-UlkbLrgQ.mjs";
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-D3ytCxvV.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CnjDv9p8.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-UlkbLrgQ.mjs";
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 "./chats.mjs";
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({ identities: pairing });
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-UlkbLrgQ.mjs";
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-UlkbLrgQ.mjs";
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 chatPostCard(description, copy) {
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 destination = telegramText("chatPost", preview.externalId.startsWith("-") ? "previewGroup" : "previewPrivate")?.replace(/\{(recipient|signature|provider)\}/gu, (_, key) => key === "recipient" ? preview.title : key === "signature" ? preview.attribution : preview.provider);
33
- const text = [
34
- base.text,
35
- destination ?? `${preview.title} (${preview.provider})`,
36
- ...preview.replyTo === null ? [] : [preview.replyTo]
37
- ].map(escapeMarkdownV2).join("\n") + `\n\n${preview.finalText}`;
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(preview.attributionSeparator ?? "\n\n"),
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-UlkbLrgQ.mjs";
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 "./chats.js";
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-UlkbLrgQ.mjs";
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 "./chats.js";
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-D3ytCxvV.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-CnjDv9p8.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 "./chats.js";
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-UlkbLrgQ.mjs";
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 "./chats.mjs";
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";
@@ -4,8 +4,8 @@ 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 { d as telegramRuntimeSource, l as principalRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-UlkbLrgQ.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-D3ytCxvV.mjs";
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-CnjDv9p8.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,5 +1,5 @@
1
1
  import type { AgentIdentities } from "../identities.js";
2
- import type { AgentChats } from "./chats.js";
2
+ import type { AgentChats } from "../chats.js";
3
3
  /** Membership updates have no message for Eve to route. Report them at the verified webhook boundary. */
4
4
  export declare function reportMembership(input: {
5
5
  readonly update: Record<string, unknown>;
@@ -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 TELEGRAM_AUTHENTICATOR, n as conversationLanguage, r as identityProviderOf, i as memberIdOf, a as rolesOf, o as telegramPrincipal } from "../../../_chunks/principal-UlkbLrgQ.mjs";
7
+ export { t as TELEGRAM_AUTHENTICATOR, n as conversationLanguage, r as identityProviderOf, i as memberIdOf, a as rolesOf, o as telegramPrincipal } from "../../../_chunks/principal-BIX7T6Hh.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 { d as telegramRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-UlkbLrgQ.mjs";
7
+ import { d as telegramRuntimeSource, u as runtimeEnvelope } from "../../../_chunks/principal-BIX7T6Hh.mjs";
8
8
  import { workspaceAction } from "./workspace-action.mjs";
9
9
  import { STRUCTURED_KINDS } from "./structured-settings.mjs";
10
10
  const record = (value) => {
@@ -8,7 +8,7 @@ import { telegramText } from "./texts.mjs";
8
8
  import { confirmationLocale } from "./confirmation-text.mjs";
9
9
  import { recordSessionFailure } from "./conversations.mjs";
10
10
  import { c as customerCopy, d as failureText, o as currentLocale, p as reportTelegramError, s as currentThreadId } from "../../../_chunks/inbound-request-DgQB4g1J.mjs";
11
- import { i as memberIdOf } from "../../../_chunks/principal-UlkbLrgQ.mjs";
11
+ import { i as memberIdOf } from "../../../_chunks/principal-BIX7T6Hh.mjs";
12
12
  import { modelServiceFailure } from "../model-service-failure.mjs";
13
13
  function telegramFailureEvents(input) {
14
14
  return {
@@ -70,7 +70,9 @@ export declare function segmentstreamWhatsApp(options: WhatsAppChannelOptions):
70
70
  * after answering anyone else with the workspace's reply, if it has one.
71
71
  */
72
72
  export declare function receive(input: {
73
+ /** The Chat SDK thread: its id names the conversation, one person's chat with the number. */
73
74
  readonly thread: {
75
+ readonly id: string;
74
76
  readonly post: (text: string) => Promise<unknown>;
75
77
  };
76
78
  readonly message: Pick<Message, "author" | "text" | "attachments">;
@@ -6,6 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { admitMessage, localizedText } from "../admission.mjs";
8
8
  import { chatSdkButtonAnswer, withButtonDecision } from "../confirmation-buttons.mjs";
9
+ import { withConversation } from "../conversation.mjs";
9
10
  import { redactDiagnostic } from "../diagnostics.mjs";
10
11
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
11
12
  import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
@@ -201,7 +202,13 @@ async function receive(input) {
201
202
  });
202
203
  switch (resolution.status) {
203
204
  case "existing":
204
- case "created": return turn ? whatsappPrincipal(resolution.member, sender) : void 0;
205
+ case "created": return turn ? withConversation(whatsappPrincipal(resolution.member, sender), {
206
+ provider: "whatsapp",
207
+ chatId: thread.id,
208
+ threadId: "",
209
+ kind: "private",
210
+ peer: sender
211
+ }) : void 0;
205
212
  case "pairing_required": {
206
213
  const text = localizedText(admission.replies.pairingRequired);
207
214
  if (text !== void 0) {
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { chatModelChoiceOf } from "./config.mjs";
8
8
  import { isPreview } from "./lib/environment.mjs";
9
- import { a as rolesOf } from "../_chunks/principal-UlkbLrgQ.mjs";
9
+ import { a as rolesOf } from "../_chunks/principal-BIX7T6Hh.mjs";
10
10
  import { defineDynamic } from "eve";
11
11
  import { runs } from "eve/events";
12
12
  function chooseModel(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 { u as runtimeEnvelope } from "../../_chunks/principal-UlkbLrgQ.mjs";
7
+ import { u as runtimeEnvelope } from "../../_chunks/principal-BIX7T6Hh.mjs";
8
8
  import segmentstream from "../extension.mjs";
9
9
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
10
10
  import { actionApproval } from "../lib/confirmations.mjs";
@@ -8,7 +8,7 @@ import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7
8
8
  import { agentTaskIdOf, agentTaskSessions } from "../lib/agent-task.mjs";
9
9
  import { stringArgument } from "../lib/attachment-tools.mjs";
10
10
  import { pendingQuestions, questionKey } from "../lib/questions.mjs";
11
- import { i as memberIdOf } from "../../_chunks/principal-UlkbLrgQ.mjs";
11
+ import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
12
12
  import { defineTool } from "eve/tools";
13
13
  var questions_ask_default = defineTool({
14
14
  availableInSubagents: false,