@segmentstream/agent 0.36.2 → 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 (50) hide show
  1. package/README.md +23 -4
  2. package/dist/_chunks/{build-metadata-Cmrq0o5K.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/confirmation-buttons.d.ts +22 -0
  14. package/dist/extension/lib/confirmation-buttons.mjs +44 -0
  15. package/dist/extension/lib/confirmations.d.ts +5 -4
  16. package/dist/extension/lib/confirmations.mjs +27 -11
  17. package/dist/extension/lib/conversation-runtime.mjs +1 -1
  18. package/dist/extension/lib/conversation.d.ts +33 -0
  19. package/dist/extension/lib/conversation.mjs +55 -0
  20. package/dist/extension/lib/ontology-connection.mjs +11 -4
  21. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  22. package/dist/extension/lib/ontology-tools.mjs +1 -1
  23. package/dist/extension/lib/runtime-envelope.d.ts +5 -1
  24. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  25. package/dist/extension/lib/slack/adapter.d.ts +34 -1
  26. package/dist/extension/lib/slack/adapter.mjs +138 -16
  27. package/dist/extension/lib/stored-files.mjs +1 -1
  28. package/dist/extension/lib/telegram/adapter.mjs +7 -4
  29. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  30. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  31. package/dist/extension/lib/telegram/chat-post-card.d.ts +11 -0
  32. package/dist/extension/lib/telegram/chat-post-card.mjs +27 -12
  33. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  34. package/dist/extension/lib/telegram/conversations.d.ts +1 -1
  35. package/dist/extension/lib/telegram/files.mjs +1 -1
  36. package/dist/extension/lib/telegram/health.d.ts +1 -1
  37. package/dist/extension/lib/telegram/health.mjs +1 -1
  38. package/dist/extension/lib/telegram/inbound.d.ts +1 -1
  39. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  40. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  41. package/dist/extension/lib/telegram/membership.d.ts +1 -1
  42. package/dist/extension/lib/telegram/principal.mjs +1 -1
  43. package/dist/extension/lib/telegram/structured.mjs +1 -1
  44. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  45. package/dist/extension/lib/whatsapp/adapter.d.ts +2 -0
  46. package/dist/extension/lib/whatsapp/adapter.mjs +14 -2
  47. package/dist/extension/model.mjs +1 -1
  48. package/dist/extension/tools/attachments_promote.mjs +1 -1
  49. package/dist/extension/tools/questions_ask.mjs +1 -1
  50. package/package.json +2 -2
package/README.md CHANGED
@@ -451,8 +451,17 @@ The SDK adds no text to the prompt.
451
451
  no turn and drops the old chat from the memo. The `<chat>` block carries at most 1000
452
452
  characters of `whenToUse`.
453
453
  - **Cross-chat drafts.** The agent uses `chat_post_message` through its existing ontology
454
- connection. The exact full text, destination and authenticated attribution appear on a deterministic
455
- Confirm / Edit / Cancel card in the requesting group or DM. Only the requester can use it; the
454
+ connection, from a Telegram, Slack or WhatsApp conversation, into a Telegram chat or, when the
455
+ ontology declares `chat.slack`, a Slack channel or a member's Slack DM, or, when it declares
456
+ `chat.whatsapp`, another member's WhatsApp chat with the workspace's number (only inside Meta's
457
+ 24-hour customer-service window). The Slack channel reports
458
+ the channels a paired member writes in, and those it joins, leaves or sees renamed, to the
459
+ `agent_chat` registry under their `conversations.info` names; it never reports direct or group
460
+ direct messages, and reports nothing until the connection holds `channels:read` and
461
+ `groups:read`, which a workspace adds to its `SlackConnection`'s scopes to offer channels. The Telegram card shows a Slack or WhatsApp post's exact text and attribution as
462
+ literal text. The exact full text, destination and
463
+ authenticated attribution appear on a deterministic card in the requesting group or DM: Telegram's
464
+ own Confirm / Edit / Cancel card, or eve's approval card with Approve / Deny elsewhere. Only the requester can use it; the
456
465
  card expires after ten minutes. Edit cancels the original call and asks for a revision. Oversize
457
466
  previews are refused, and uncertain delivery is never automatically retried. Sent receipts retain
458
467
  the preview and show a Telegram link when available; archive failure is distinct from send failure.
@@ -695,14 +704,24 @@ missing/incomplete preview metadata is denied. The versioned connection has its
695
704
 
696
705
  The runtime reads `me` for the server-derived `attribution`, and `chat_list({ chat })` for exactly
697
706
  one eligible destination: `{ items: [{ id, title, provider, external_id }], next_cursor: null }`.
698
- Provider is currently `telegram`. The final plain text is `text + separator + attribution`, with a blank line as the neutral separator;
707
+ Provider is `telegram`, `slack` or `whatsapp`; the agent refuses a destination on any other
708
+ provider when it describes the post, as agents before Slack and WhatsApp destinations refuse
709
+ theirs, and refuses a `reply_to` for WhatsApp. The final text is computed as the ontology renders
710
+ it: Telegram's MarkdownV2, `renderSlack` from `@segmentstream/ontology/slack`, or `renderWhatsApp`
711
+ from `@segmentstream/ontology/whatsapp`. The final plain text is `text + separator + attribution`, with a blank line as the neutral separator;
699
712
  `reply_to` is optional. A preview digest is SHA-256 of the JSON array of chat ID, provider,
700
713
  external ID, title, attribution, text, final text and nullable reply target, in that order.
701
714
  The target/attribution are resolved again immediately before executing the frozen call.
702
715
 
703
716
  The SDK constructs model-hidden `_segmentstream` metadata for approved runtime posts.
704
717
  It contains `version: 1`, `session_id` and `call_id`. A consumed, unexpired chat approval additionally
705
- supplies `operation_id`, source provider/chat/topic coordinates and `expected: { chat_id, digest }`.
718
+ supplies `operation_id`, the source conversation and `expected: { chat_id, digest }`. A Telegram
719
+ source carries its chat, topic and message references. A Slack or WhatsApp source carries only
720
+ `{ provider, chat_id, thread_id, kind, peer? }`: `kind` is `private` for a member's own direct
721
+ conversation, whose `peer` is the member's id on the provider. The ontology refuses a source on a
722
+ channel other than the member's verified pairing, and a post into the conversation it came from,
723
+ including a private destination naming the same person. An ontology without this source form
724
+ refuses a Slack or WhatsApp source before sending.
706
725
  The operation ID is `hq:` plus SHA-256 of the JSON array `[session_id, call_id]`; it stays stable
707
726
  on replay and changes for a revision. The model cannot provide an idempotency key or this envelope.
708
727
  The ontology must authenticate runtime provenance, consume/remove the envelope before strict 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
- var version = "0.36.2";
7
+ var version = "0.37.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -64,7 +64,7 @@ function runtimeEnvelope(input = {}) {
64
64
  }
65
65
  function compatibleRuntimeEnvelope(envelope, extended) {
66
66
  const source = envelope.source;
67
- return extended || source === void 0 ? envelope : {
67
+ return extended || source === void 0 || source.provider !== "telegram" ? envelope : {
68
68
  ...envelope,
69
69
  source: {
70
70
  provider: source.provider,
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
8
  import { localizedText } from "../lib/admission.mjs";
9
9
  import { confirmationLocale } from "../lib/telegram/confirmation-text.mjs";
10
- import "../../_chunks/principal-UlkbLrgQ.mjs";
10
+ import "../../_chunks/principal-BIX7T6Hh.mjs";
11
11
  import { defineHook } from "eve/hooks";
12
12
  var authorization_default = defineHook({ events: { "interaction.opened": (event, context) => {
13
13
  const principal = context.session.auth.current;
@@ -99,9 +99,9 @@ rejection or perform actions.
99
99
  without a message; write no text in that turn, because any text you write is sent.
100
100
  - To post in another chat, find the destination with `chat_list` and colleagues with `user_find`.
101
101
  Read `chat_history` or `chat_search` only when permitted, then compose the exact draft and call
102
- `chat_post_message`. The runtime supplies the operation key. Its Confirm / Edit / Cancel card
103
- shows the full attributed text in the requesting chat; only the requester can act on it and it
104
- expires after ten minutes. A text acknowledgement cannot approve a post. After Edit, ask what
102
+ `chat_post_message`. The runtime supplies the operation key. Its confirmation card shows the full
103
+ attributed text in the requesting chat, whichever channel it is (Telegram also offers Edit);
104
+ only the requester can act on it and it expires after ten minutes. A text acknowledgement cannot approve a post. After Edit, ask what
105
105
  to change and make a new call/card for the revision; the cancelled call cannot be reused.
106
106
  An uncertain delivery must never be automatically resent, including through a fresh call/key.
107
107
  For a reply in the current chat, answer normally. If chat posting is unavailable, say so.
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { AGENT_TASK_HEADER, agentTaskIdOf, taskSecret } from "./agent-task.mjs";
8
- import { i as memberIdOf, r as identityProviderOf } from "../../_chunks/principal-UlkbLrgQ.mjs";
8
+ import { i as memberIdOf, r as identityProviderOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
9
9
  import { defineDynamic } from "eve/tools";
10
10
  const ACT_AS_HEADER = "X-SegmentStream-Act-As";
11
11
  function member(memberId) {
@@ -10,7 +10,7 @@ import { readSheets, typedTable } from "./attachment-tables.mjs";
10
10
  import { appOrigin } from "./environment.mjs";
11
11
  import { runtimeToken } from "./runtime-token.mjs";
12
12
  import { telegramConversation } from "./telegram/files.mjs";
13
- import { i as memberIdOf } from "../../_chunks/principal-UlkbLrgQ.mjs";
13
+ import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
14
14
  const MAXIMUM_TEXT_CHARACTERS = 5e4;
15
15
  const MAXIMUM_INLINE_BYTES = 5242880;
16
16
  var AttachmentOwnerError = class extends Error {
@@ -4,4 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- export { t as agentBuild } from "../../_chunks/build-metadata-Cmrq0o5K.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-CnjDv9p8.mjs";
@@ -4,9 +4,11 @@ export declare const CHAT_POST_PROTOCOL = "segmentstream/chat-post";
4
4
  export declare const CHAT_POST_ENVELOPE = "_segmentstream";
5
5
  /** The ontology's chat posting tool, without the connection's namespace. */
6
6
  export declare const CHAT_POST_TOOL = "chat_post_message";
7
+ /** The providers whose chats this agent describes posts to; it refuses a destination elsewhere. */
8
+ export type ChatPostProvider = "telegram" | "slack" | "whatsapp";
7
9
  export interface ChatPostPreview {
8
10
  readonly chatId: string;
9
- readonly provider: "telegram";
11
+ readonly provider: ChatPostProvider;
10
12
  readonly externalId: string;
11
13
  readonly title: string;
12
14
  readonly attribution: string;
@@ -7,6 +7,8 @@ __eveCreateRequire(import.meta.url);
7
7
  import { object } from "./confirmation-description.mjs";
8
8
  import { createHash } from "node:crypto";
9
9
  import { TelegramFormatConverter, escapeMarkdownV2 } from "@chat-adapter/telegram";
10
+ import { renderSlack } from "@segmentstream/ontology/slack";
11
+ import { renderWhatsApp } from "@segmentstream/ontology/whatsapp";
10
12
  const CHAT_POST_PROTOCOL = "segmentstream/chat-post";
11
13
  const CHAT_POST_ENVELOPE = "_segmentstream";
12
14
  const CHAT_POST_TOOL = "chat_post_message";
@@ -46,21 +48,22 @@ function describeChatPost(input) {
46
48
  target.title,
47
49
  target.external_id,
48
50
  caller.attribution
49
- ].every((value) => typeof value === "string" && value.length > 0) || target.provider !== "telegram" || target.id !== values.chat && target.title !== values.chat) throw new Error("An unambiguous destination and a complete exact chat preview are required.");
50
- const footer = escapeMarkdownV2(caller.attribution);
51
+ ].every((value) => typeof value === "string" && value.length > 0) || target.provider !== "telegram" && target.provider !== "slack" && target.provider !== "whatsapp" || target.provider === "whatsapp" && values.reply_to !== void 0 || target.id !== values.chat && target.title !== values.chat) throw new Error("An unambiguous destination and a complete exact chat preview are required.");
52
+ const attribution = caller.attribution;
51
53
  const separator = typeof caller.attribution_separator === "string" ? caller.attribution_separator : "\n\n";
54
+ const finalText = target.provider === "telegram" ? `${converter.fromMarkdown(values.text)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_` : target.provider === "slack" ? renderSlack(values.text, attribution, separator) : renderWhatsApp(values.text, attribution, separator);
52
55
  return {
53
56
  action: "",
54
57
  fields: [],
55
58
  chatPost: {
56
59
  chatId: target.id,
57
- provider: "telegram",
60
+ provider: target.provider,
58
61
  externalId: target.external_id,
59
62
  title: target.title,
60
- attribution: caller.attribution,
63
+ attribution,
61
64
  ...separator === "\n\n" ? {} : { attributionSeparator: separator },
62
65
  text: values.text,
63
- finalText: `${converter.fromMarkdown(values.text)}${escapeMarkdownV2(separator)}_${footer}_`,
66
+ finalText,
64
67
  replyTo: typeof values.reply_to === "string" ? values.reply_to : null
65
68
  }
66
69
  };
@@ -1,14 +1,22 @@
1
- import { type AgentChat, type AgentIdentities } from "../identities.js";
1
+ import { type AgentChat, type AgentIdentities } from "./identities.js";
2
2
  /** How long a chat's report stands before the next message reports it again. */
3
3
  export declare const REPORT_INTERVAL_MS: number;
4
4
  export declare const REPORT_FAILURE_THRESHOLD = 3;
5
+ /**
6
+ * A chat's name on the provider, or how to look it up, which runs only when a report is due. A
7
+ * lookup that finds no name reports nothing until the chat is next due.
8
+ */
9
+ export type ChatTitle = string | (() => Promise<string | undefined>);
5
10
  export interface ChatReport {
6
11
  readonly chatId: string;
7
- readonly title: string;
12
+ readonly title: ChatTitle;
8
13
  readonly memberId?: string;
9
14
  }
10
15
  export interface AgentChats {
11
- /** The bot joined/rejoined: report immediately even if this chat was recently remembered. */
16
+ /**
17
+ * The bot joined or rejoined, or the chat was renamed: report immediately even if this chat was
18
+ * recently remembered.
19
+ */
12
20
  joined(report: ChatReport): Promise<void>;
13
21
  /** Process-local report diagnostics for the authenticated channel health route. */
14
22
  health(): {
@@ -33,7 +41,7 @@ export interface AgentChats {
33
41
  */
34
42
  agentLeft(report: {
35
43
  readonly chatId: string;
36
- readonly title: string;
44
+ readonly title: ChatTitle;
37
45
  }): Promise<void>;
38
46
  /**
39
47
  * Reports that the group `migratedFrom` became the supergroup `chatId`, so the registry moves its
@@ -56,6 +64,8 @@ export interface ChatReportFailure {
56
64
  readonly requestId: string | null;
57
65
  }
58
66
  export declare function agentChats(input: {
67
+ /** The provider whose chats these are, as the registry records them. */
68
+ readonly provider: string;
59
69
  readonly identities: () => AgentIdentities;
60
70
  readonly now?: () => number;
61
71
  readonly log?: (message: string, error: unknown) => void;
@@ -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 { AgentIdentityError } from "../identities.mjs";
8
- import { redactDiagnostic } from "../diagnostics.mjs";
7
+ import { AgentIdentityError } from "./identities.mjs";
8
+ import { redactDiagnostic } from "./diagnostics.mjs";
9
9
  const MAXIMUM_WHEN_TO_USE_LENGTH = 1e3;
10
10
  const REPORT_INTERVAL_MS = 6e5;
11
11
  const REPORT_FAILURE_THRESHOLD = 3;
@@ -32,11 +32,27 @@ function agentChats(input) {
32
32
  if (previous === void 0) chats.delete(chatId);
33
33
  else chats.set(chatId, previous);
34
34
  }
35
- async function report(chatId, fallback, body) {
35
+ async function titleOf(chatId, title) {
36
+ if (typeof title === "string") return title;
37
+ try {
38
+ return await title();
39
+ } catch (error) {
40
+ log("The agent could not look up the chat's title.", {
41
+ event: `segmentstream.${input.provider}.registry_title_unavailable`,
42
+ chatId,
43
+ error: redactDiagnostic(error, new Set())
44
+ });
45
+ return;
46
+ }
47
+ }
48
+ async function report(chatId, fallback, { title: titled, ...body }) {
49
+ const title = await titleOf(chatId, titled);
50
+ if (title === void 0) return "untitled";
36
51
  try {
37
52
  const chat = await input.identities().seenChat({
38
- provider: "telegram",
53
+ provider: input.provider,
39
54
  externalId: chatId,
55
+ title,
40
56
  ...body
41
57
  });
42
58
  remember(chatId, {
@@ -46,11 +62,11 @@ function agentChats(input) {
46
62
  const previousFailure = failures.get(chatId);
47
63
  failures.delete(chatId);
48
64
  if ((previousFailure?.consecutiveFailures ?? 0) >= 3) logRecovery("The agent's chat registry report recovered.", {
49
- event: "segmentstream.telegram.registry_recovered",
65
+ event: `segmentstream.${input.provider}.registry_recovered`,
50
66
  chatId,
51
67
  consecutiveFailures: previousFailure.consecutiveFailures
52
68
  });
53
- return true;
69
+ return "reported";
54
70
  } catch (error) {
55
71
  totalFailures += 1;
56
72
  const failure = {
@@ -65,14 +81,14 @@ function agentChats(input) {
65
81
  failures.set(chatId, failure);
66
82
  if (failures.size > MAXIMUM_CHATS) failures.delete(failures.keys().next().value);
67
83
  const detail = {
68
- event: "segmentstream.telegram.registry_report_failed",
84
+ event: `segmentstream.${input.provider}.registry_report_failed`,
69
85
  ...failure,
70
86
  totalFailures,
71
87
  error: redactDiagnostic(error, new Set())
72
88
  };
73
89
  if (failure.consecutiveFailures < 3) log("The agent could not report the chat to the ontology's registry.", detail);
74
90
  else if (failure.consecutiveFailures === 3) logError("The agent's chat registry reports repeatedly failed.", detail);
75
- return false;
91
+ return "failed";
76
92
  }
77
93
  }
78
94
  return {
@@ -84,7 +100,7 @@ function agentChats(input) {
84
100
  chat: known?.chat
85
101
  };
86
102
  remember(chatId, remembered);
87
- if (!await report(chatId, remembered, { title })) restore(chatId, remembered, known);
103
+ if (await report(chatId, remembered, { title }) === "failed") restore(chatId, remembered, known);
88
104
  },
89
105
  health() {
90
106
  const failedChats = [...failures.values()];
@@ -111,14 +127,14 @@ function agentChats(input) {
111
127
  };
112
128
  remember(chatId, written);
113
129
  const task = (async () => {
114
- if (!await report(chatId, {
130
+ if (await report(chatId, {
115
131
  reportedAt: at,
116
132
  members,
117
133
  chat: void 0
118
134
  }, {
119
135
  title,
120
136
  ...memberId === void 0 ? {} : { memberId }
121
- })) restore(chatId, written, known);
137
+ }) === "failed") restore(chatId, written, known);
122
138
  })();
123
139
  inFlight.set(chatId, task);
124
140
  try {
@@ -135,10 +151,10 @@ function agentChats(input) {
135
151
  chat: known?.chat
136
152
  };
137
153
  remember(chatId, remembered);
138
- if (!await report(chatId, remembered, {
154
+ if (await report(chatId, remembered, {
139
155
  title,
140
156
  leftMemberId: memberId
141
- })) restore(chatId, remembered, known);
157
+ }) === "failed") restore(chatId, remembered, known);
142
158
  },
143
159
  async agentLeft({ chatId, title }) {
144
160
  const known = chats.get(chatId);
@@ -148,10 +164,10 @@ function agentChats(input) {
148
164
  chat: known?.chat
149
165
  };
150
166
  remember(chatId, remembered);
151
- if (!await report(chatId, remembered, {
167
+ if (await report(chatId, remembered, {
152
168
  title,
153
169
  agentLeft: true
154
- })) restore(chatId, remembered, known);
170
+ }) === "failed") restore(chatId, remembered, known);
155
171
  },
156
172
  async migrated({ chatId, title, migratedFrom }) {
157
173
  const old = chats.get(migratedFrom);
@@ -163,10 +179,10 @@ function agentChats(input) {
163
179
  };
164
180
  chats.delete(migratedFrom);
165
181
  remember(chatId, remembered);
166
- if (!await report(chatId, remembered, {
182
+ if (await report(chatId, remembered, {
167
183
  title,
168
184
  migratedFrom
169
- })) {
185
+ }) === "failed") {
170
186
  restore(chatId, remembered, known);
171
187
  if (old !== void 0 && !chats.has(migratedFrom)) remember(migratedFrom, old);
172
188
  }
@@ -0,0 +1,22 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ /** Whether the card's whole text fits the channel's approval card; a card is never cut. */
3
+ export declare function promptFits(identityProvider: unknown, text: string): boolean;
4
+ /** One answer a channel decoded from a click on eve's own input buttons. */
5
+ export interface ButtonAnswer {
6
+ readonly interactionId: string;
7
+ readonly optionId?: string;
8
+ }
9
+ /**
10
+ * The responder's principal, stamped with the decision a click on a confirmation's own button
11
+ * carried, as the Telegram callback stamps it. The response policy accepts an approval or a
12
+ * cancellation only with this stamp, so a typed message never decides a confirmation.
13
+ *
14
+ * Only a click that answers exactly one request with approve or deny is stamped; anything else,
15
+ * such as a question's answers, keeps the plain principal.
16
+ */
17
+ export declare function withButtonDecision(principal: SessionAuthContext, answers: readonly ButtonAnswer[]): SessionAuthContext;
18
+ /**
19
+ * The answer in a Chat SDK action for one of eve's own input buttons. eve names each button
20
+ * `<prefix><encoded interaction id>:<encoded option id>` and carries the option id as its value.
21
+ */
22
+ export declare function chatSdkButtonAnswer(actionId: string, value: string | undefined, prefix?: string): ButtonAnswer | undefined;
@@ -0,0 +1,44 @@
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 { APPROVE_OPTION_ID, DENY_OPTION_ID } from "eve/events";
8
+ const PROMPT_LIMITS = {
9
+ whatsapp: 1e3,
10
+ slack: 2900
11
+ };
12
+ function promptFits(identityProvider, text) {
13
+ const limit = typeof identityProvider === "string" ? PROMPT_LIMITS[identityProvider] : void 0;
14
+ return limit === void 0 || text.length <= limit;
15
+ }
16
+ function withButtonDecision(principal, answers) {
17
+ const [answer] = answers;
18
+ if (answers.length !== 1 || answer === void 0 || answer.optionId !== APPROVE_OPTION_ID && answer.optionId !== DENY_OPTION_ID) return principal;
19
+ return {
20
+ ...principal,
21
+ attributes: {
22
+ ...principal.attributes,
23
+ confirmationRequestId: answer.interactionId,
24
+ confirmationDecision: answer.optionId === DENY_OPTION_ID ? "cancel" : "approve"
25
+ }
26
+ };
27
+ }
28
+ function chatSdkButtonAnswer(actionId, value, prefix = "eve_input:") {
29
+ if (!actionId.startsWith(prefix)) return;
30
+ const rest = actionId.slice(prefix.length);
31
+ const separator = rest.indexOf(":");
32
+ if (separator <= 0) return;
33
+ try {
34
+ const interactionId = decodeURIComponent(rest.slice(0, separator));
35
+ const optionId = decodeURIComponent(rest.slice(separator + 1));
36
+ return value === void 0 || value === optionId ? {
37
+ interactionId,
38
+ optionId
39
+ } : void 0;
40
+ } catch {
41
+ return;
42
+ }
43
+ }
44
+ export { chatSdkButtonAnswer, promptFits, withButtonDecision };
@@ -2,6 +2,7 @@ import { type StateHandle } from "eve/context";
2
2
  import type { ApprovalConfiguration } from "eve/tools/approval";
3
3
  import { type OntologyActor } from "./actor.js";
4
4
  import { type ConfirmationDescription } from "./confirmation-description.js";
5
+ import { type Conversation } from "./conversation.js";
5
6
  import { type ConfirmationCopy } from "./telegram/confirmation-text.js";
6
7
  import { type TelegramTexts } from "./telegram/texts.js";
7
8
  export declare const CONFIRMATION_TTL_MS: number;
@@ -26,10 +27,10 @@ export interface Confirmation {
26
27
  readonly status: "pending" | "approved" | "consumed" | "cancelled";
27
28
  readonly description?: ConfirmationDescription;
28
29
  readonly copy?: ConfirmationCopy;
29
- readonly source?: {
30
- readonly chatId: string;
31
- readonly threadId: string;
32
- };
30
+ /** The card's text, which channels that show eve's own approval card show as its prompt. */
31
+ readonly prompt?: string;
32
+ /** A chat post's source conversation, pinned from the request to its execution. */
33
+ readonly source?: Conversation;
33
34
  readonly cancellationReason?: "edit" | "expired";
34
35
  }
35
36
  export declare const confirmations: StateHandle<Record<string, Confirmation>>;
@@ -5,11 +5,13 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { actorOf, member } from "./actor.mjs";
8
- import { i as memberIdOf } from "../../_chunks/principal-UlkbLrgQ.mjs";
8
+ import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
9
9
  import { ConfirmationRefused, UnsafeConfirmationTarget } from "./confirmation-description.mjs";
10
10
  import { chatPostDigest, isChatPost } from "./chat-post-confirmation.mjs";
11
+ import { promptFits } from "./confirmation-buttons.mjs";
12
+ import { conversationOf, isSameConversation } from "./conversation.mjs";
11
13
  import { confirmationCopy, confirmationCopyIssue, confirmationLocale, renderConfirmation } from "./telegram/confirmation-text.mjs";
12
- import { chatPostCard } from "./telegram/chat-post-card.mjs";
14
+ import { chatPostCard, chatPostPrompt } from "./telegram/chat-post-card.mjs";
13
15
  import { withTelegramTexts } from "./telegram/texts.mjs";
14
16
  import { createHash } from "node:crypto";
15
17
  import { defineState } from "eve/context";
@@ -27,6 +29,9 @@ function canonical(value) {
27
29
  function inputHash(input) {
28
30
  return createHash("sha256").update(canonical(input)).digest("hex");
29
31
  }
32
+ function isSameSource(saved, current) {
33
+ return current !== void 0 && saved.provider === current.provider && saved.chatId === current.chatId && saved.threadId === current.threadId;
34
+ }
30
35
  const confirmations = defineState("segmentstream.confirmations", () => ({}));
31
36
  function connectionHints(ctx) {
32
37
  const hints = ctx.toolAnnotations;
@@ -40,6 +45,13 @@ function actionApproval(options) {
40
45
  reason
41
46
  });
42
47
  return {
48
+ prompt({ callId }) {
49
+ try {
50
+ return state.get()[callId]?.prompt;
51
+ } catch {
52
+ return;
53
+ }
54
+ },
43
55
  async request(ctx) {
44
56
  const actor = actorOf(ctx.session.auth.current);
45
57
  if (actor?.kind === "task") {
@@ -79,17 +91,22 @@ function actionApproval(options) {
79
91
  let description;
80
92
  const missingCopy = () => denied((offered === void 0 ? "This action needs a confirmation card and the call has no _confirmation. " : `The call's _confirmation is invalid: ${confirmationCopyIssue(offered) ?? "it cannot be shown"}. `) + "Make the call again with _confirmation (for a file call, in its arguments file) in the chat's language: a plain single-line question naming the action and its key records and amounts (at most 300 characters), and short confirm, cancel, done, cancelled and failed labels without emoji.");
81
93
  if (posting && saved === void 0 && labels.confirmation === true && copy === void 0) return missingCopy();
94
+ let prompt;
95
+ const conversation = conversationOf(ctx.session.auth.current);
82
96
  if (posting) try {
83
97
  description = await options.describe?.(member(memberId), ctx.toolName, businessInput, hints);
84
98
  const preview = description?.chatPost;
85
- const source = ctx.session.auth.current?.attributes;
86
- if (description === void 0 || preview === void 0 || typeof source?.chatId !== "string" || source.chatId === preview.externalId) return denied("A complete preview for a different chat is required. Reply normally in this chat.");
99
+ if (description === void 0 || preview === void 0 || conversation === void 0 || isSameConversation(conversation, preview)) return denied("A complete preview for a different chat is required. Reply normally in this chat.");
87
100
  const previewDescription = {
88
101
  ...description,
89
102
  warning: labels.destructiveHint === true || labels.irreversibleHint === true
90
103
  };
91
- present(() => chatPostCard(previewDescription, copy));
92
- if (saved !== void 0 && (saved.description?.chatPost === void 0 || chatPostDigest(saved.description.chatPost) !== chatPostDigest(preview) || saved.source?.chatId !== source.chatId || saved.source.threadId !== String(source.messageThreadId ?? ""))) return denied("The destination or attribution changed. Make a new call and confirmation.");
104
+ if (conversation.provider === "telegram") present(() => chatPostCard(previewDescription, copy));
105
+ else {
106
+ prompt = present(() => chatPostPrompt(previewDescription, copy));
107
+ if (!promptFits(conversation.provider, prompt)) return denied("The full message does not fit this chat's confirmation card. Make a shorter draft.");
108
+ }
109
+ if (saved !== void 0 && (saved.description?.chatPost === void 0 || chatPostDigest(saved.description.chatPost) !== chatPostDigest(preview) || saved.source === void 0 || !isSameSource(saved.source, conversation))) return denied("The destination or attribution changed. Make a new call and confirmation.");
93
110
  } catch (error) {
94
111
  console.warn("The exact chat confirmation could not be prepared.", error);
95
112
  return denied("The full exact chat preview is unavailable or too long. Make a new call.");
@@ -121,10 +138,11 @@ function actionApproval(options) {
121
138
  warning: labels.destructiveHint === true || labels.irreversibleHint === true
122
139
  };
123
140
  try {
124
- if (!posting) present(() => renderConfirmation(description, copy));
141
+ if (!posting) prompt = present(() => renderConfirmation(description, copy)).text;
125
142
  } catch {
126
143
  return denied("The complete confirmation facts are unsafe or too long. Narrow the action input.");
127
144
  }
145
+ if (prompt !== void 0 && !promptFits(ctx.session.auth.current?.attributes.identityProvider, prompt)) return denied("The complete confirmation facts are too long for this chat's confirmation card. Narrow the action input.");
128
146
  state.update((all) => ({
129
147
  ...all,
130
148
  [ctx.callId]: {
@@ -135,10 +153,8 @@ function actionApproval(options) {
135
153
  status: "pending",
136
154
  ...copy === void 0 ? {} : { copy },
137
155
  ...description === void 0 ? {} : { description },
138
- ...posting ? { source: {
139
- chatId: String(ctx.session.auth.current?.attributes.chatId),
140
- threadId: String(ctx.session.auth.current?.attributes.messageThreadId ?? "")
141
- } } : {}
156
+ ...prompt === void 0 ? {} : { prompt },
157
+ ...posting && conversation !== void 0 ? { source: conversation } : {}
142
158
  }
143
159
  }));
144
160
  return "user-approval";
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { n as contentText, t as CONTENT_CAPS } from "../../_chunks/content-cDtVnr8Y.mjs";
8
8
  import { conversationEvent, conversations, sessionFailureEventId, summarizeArguments } from "./conversations.mjs";
9
9
  import { agentTaskIdOf } from "./agent-task.mjs";
10
- import { i as memberIdOf } from "../../_chunks/principal-UlkbLrgQ.mjs";
10
+ import { i as memberIdOf } from "../../_chunks/principal-BIX7T6Hh.mjs";
11
11
  import { parseAddress } from "./telegram/sessions.mjs";
12
12
  import { completionKind } from "./telegram/silent.mjs";
13
13
  import { recordModelServiceAlert } from "./model-service-alert.mjs";
@@ -0,0 +1,33 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ /**
3
+ * The conversation a member's message came from, the same way for every channel: the provider,
4
+ * its id for the conversation and thread, whether it is the member's own direct conversation, and
5
+ * there the member's id on the provider, which a private destination on that provider names.
6
+ */
7
+ export interface Conversation {
8
+ readonly provider: "telegram" | "slack" | "whatsapp";
9
+ readonly chatId: string;
10
+ /** `""` without a thread. */
11
+ readonly threadId: string;
12
+ readonly kind: "private" | "group";
13
+ readonly peer?: string;
14
+ }
15
+ /** The session attribute that carries a non-Telegram channel's conversation, as JSON. */
16
+ export declare const CONVERSATION_ATTRIBUTE = "segmentstreamConversation";
17
+ /** A channel's principal with the conversation its message came from. */
18
+ export declare function withConversation(principal: SessionAuthContext, conversation: Conversation): SessionAuthContext;
19
+ /**
20
+ * The conversation a session's principal speaks from, or undefined for one without a channel
21
+ * conversation, such as a task. Telegram's comes from the chat attributes its principal always
22
+ * carried, so sessions from before this attribute keep working.
23
+ */
24
+ export declare function conversationOf(principal?: SessionAuthContext | null): Conversation | undefined;
25
+ /**
26
+ * Whether a destination is the conversation itself. A private destination names its person, not
27
+ * the conversation: a Slack direct message is `D…` while its person is `U…`.
28
+ */
29
+ export declare function isSameConversation(conversation: Conversation, destination: {
30
+ readonly provider: string;
31
+ readonly externalId: string;
32
+ readonly kind?: string;
33
+ }): boolean;
@@ -0,0 +1,55 @@
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 "../../_chunks/principal-BIX7T6Hh.mjs";
8
+ const CONVERSATION_ATTRIBUTE = "segmentstreamConversation";
9
+ function withConversation(principal, conversation) {
10
+ return {
11
+ ...principal,
12
+ attributes: {
13
+ ...principal.attributes,
14
+ [CONVERSATION_ATTRIBUTE]: JSON.stringify(conversation)
15
+ }
16
+ };
17
+ }
18
+ function conversationOf(principal) {
19
+ if (principal === void 0 || principal === null) return;
20
+ const attributes = principal.attributes;
21
+ if (principal.authenticator === "segmentstream-telegram") {
22
+ const chatId = attributes.chatId;
23
+ return typeof chatId !== "string" || chatId === "" ? void 0 : {
24
+ provider: "telegram",
25
+ chatId,
26
+ threadId: String(attributes.messageThreadId ?? ""),
27
+ kind: chatId.startsWith("-") ? "group" : "private"
28
+ };
29
+ }
30
+ const value = attributes[CONVERSATION_ATTRIBUTE];
31
+ if (typeof value !== "string") return;
32
+ try {
33
+ return parsedConversation(JSON.parse(value), attributes.identityProvider);
34
+ } catch {
35
+ return;
36
+ }
37
+ }
38
+ function parsedConversation(value, provider) {
39
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
40
+ const item = value;
41
+ const text = (field, empty = false) => typeof field === "string" && (empty || field !== "") && field.length <= 512;
42
+ if (item.provider !== "slack" && item.provider !== "whatsapp" || item.provider !== provider || !text(item.chatId) || !text(item.threadId, true) || item.kind !== "private" && item.kind !== "group" || item.peer !== void 0 && !text(item.peer)) return;
43
+ return {
44
+ provider: item.provider,
45
+ chatId: item.chatId,
46
+ threadId: item.threadId,
47
+ kind: item.kind,
48
+ ...item.peer === void 0 ? {} : { peer: item.peer }
49
+ };
50
+ }
51
+ function isSameConversation(conversation, destination) {
52
+ if (conversation.provider !== destination.provider) return false;
53
+ return conversation.chatId === destination.externalId || conversation.provider !== "telegram" && conversation.kind === "private" && conversation.peer === destination.externalId;
54
+ }
55
+ export { CONVERSATION_ATTRIBUTE, conversationOf, isSameConversation, withConversation };