@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.
Files changed (48) hide show
  1. package/README.md +23 -4
  2. package/dist/_chunks/{build-metadata-D3ytCxvV.mjs → build-metadata-C0Kz75P3.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 +6 -4
  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 +43 -2
  24. package/dist/extension/lib/slack/adapter.mjs +201 -39
  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 +4 -1
  48. 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.3";
7
+ var version = "0.37.1";
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;
@@ -65,7 +65,9 @@ rejection or perform actions.
65
65
  question, use the answer and continue the pending task without asking for permission again.
66
66
  - Ask only when information is missing or ambiguous. In Telegram, use
67
67
  `segmentstream__questions_ask` with the question and pending task so the session keeps its intent,
68
- member and chat/topic. An answer to a pending question is never chatter and always gets a reply.
68
+ member and chat/topic. In Slack and WhatsApp, ask the question in your reply instead; the member's
69
+ answer continues the conversation. An answer to a pending question is never chatter and always
70
+ gets a reply.
69
71
  - New messages and uploads may arrive together or while you are working. Complete or explicitly
70
72
  report the status of every request and every supplied file. A later message adds work unless
71
73
  the member explicitly cancels or replaces the earlier task. If work is interrupted or blocked,
@@ -99,9 +101,9 @@ rejection or perform actions.
99
101
  without a message; write no text in that turn, because any text you write is sent.
100
102
  - To post in another chat, find the destination with `chat_list` and colleagues with `user_find`.
101
103
  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
104
+ `chat_post_message`. The runtime supplies the operation key. Its confirmation card shows the full
105
+ attributed text in the requesting chat, whichever channel it is (Telegram also offers Edit);
106
+ 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
107
  to change and make a new call/card for the revision; the cancelled call cannot be reused.
106
108
  An uncertain delivery must never be automatically resent, including through a fresh call/key.
107
109
  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-D3ytCxvV.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-C0Kz75P3.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
  }
@@ -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;
@@ -28,10 +29,8 @@ export interface Confirmation {
28
29
  readonly copy?: ConfirmationCopy;
29
30
  /** The card's text, which channels that show eve's own approval card show as its prompt. */
30
31
  readonly prompt?: string;
31
- readonly source?: {
32
- readonly chatId: string;
33
- readonly threadId: string;
34
- };
32
+ /** A chat post's source conversation, pinned from the request to its execution. */
33
+ readonly source?: Conversation;
35
34
  readonly cancellationReason?: "edit" | "expired";
36
35
  }
37
36
  export declare const confirmations: StateHandle<Record<string, Confirmation>>;
@@ -5,12 +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
11
  import { promptFits } from "./confirmation-buttons.mjs";
12
+ import { conversationOf, isSameConversation } from "./conversation.mjs";
12
13
  import { confirmationCopy, confirmationCopyIssue, confirmationLocale, renderConfirmation } from "./telegram/confirmation-text.mjs";
13
- import { chatPostCard } from "./telegram/chat-post-card.mjs";
14
+ import { chatPostCard, chatPostPrompt } from "./telegram/chat-post-card.mjs";
14
15
  import { withTelegramTexts } from "./telegram/texts.mjs";
15
16
  import { createHash } from "node:crypto";
16
17
  import { defineState } from "eve/context";
@@ -28,6 +29,9 @@ function canonical(value) {
28
29
  function inputHash(input) {
29
30
  return createHash("sha256").update(canonical(input)).digest("hex");
30
31
  }
32
+ function isSameSource(saved, current) {
33
+ return current !== void 0 && saved.provider === current.provider && saved.chatId === current.chatId && saved.threadId === current.threadId;
34
+ }
31
35
  const confirmations = defineState("segmentstream.confirmations", () => ({}));
32
36
  function connectionHints(ctx) {
33
37
  const hints = ctx.toolAnnotations;
@@ -87,17 +91,22 @@ function actionApproval(options) {
87
91
  let description;
88
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.");
89
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);
90
96
  if (posting) try {
91
97
  description = await options.describe?.(member(memberId), ctx.toolName, businessInput, hints);
92
98
  const preview = description?.chatPost;
93
- const source = ctx.session.auth.current?.attributes;
94
- 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.");
95
100
  const previewDescription = {
96
101
  ...description,
97
102
  warning: labels.destructiveHint === true || labels.irreversibleHint === true
98
103
  };
99
- present(() => chatPostCard(previewDescription, copy));
100
- 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.");
101
110
  } catch (error) {
102
111
  console.warn("The exact chat confirmation could not be prepared.", error);
103
112
  return denied("The full exact chat preview is unavailable or too long. Make a new call.");
@@ -128,7 +137,6 @@ function actionApproval(options) {
128
137
  ...description,
129
138
  warning: labels.destructiveHint === true || labels.irreversibleHint === true
130
139
  };
131
- let prompt;
132
140
  try {
133
141
  if (!posting) prompt = present(() => renderConfirmation(description, copy)).text;
134
142
  } catch {
@@ -146,10 +154,7 @@ function actionApproval(options) {
146
154
  ...copy === void 0 ? {} : { copy },
147
155
  ...description === void 0 ? {} : { description },
148
156
  ...prompt === void 0 ? {} : { prompt },
149
- ...posting ? { source: {
150
- chatId: String(ctx.session.auth.current?.attributes.chatId),
151
- threadId: String(ctx.session.auth.current?.attributes.messageThreadId ?? "")
152
- } } : {}
157
+ ...posting && conversation !== void 0 ? { source: conversation } : {}
153
158
  }
154
159
  }));
155
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 };
@@ -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 { c as compatibleRuntimeEnvelope, u as runtimeEnvelope } from "../../_chunks/principal-UlkbLrgQ.mjs";
7
+ import { c as compatibleRuntimeEnvelope, u as runtimeEnvelope } from "../../_chunks/principal-BIX7T6Hh.mjs";
8
8
  import { appOrigin } from "./environment.mjs";
9
9
  import { actionApproval, confirmations } from "./confirmations.mjs";
10
10
  import { CHAT_POST_ENVELOPE, CHAT_POST_TOOL, chatPostDigest, chatPostOperationId, isChatPost } from "./chat-post-confirmation.mjs";
@@ -76,14 +76,21 @@ function ontologyConnection(input) {
76
76
  const saved = confirmations.get()[ctx.callId];
77
77
  const preview = saved?.description?.chatPost;
78
78
  if (saved?.status !== "consumed" || saved.memberId !== memberId || saved.action.split("__").at(-1) !== ctx.toolName || saved.expiresAt <= Date.now() || preview === void 0 || saved.source === void 0) throw new Error("Exact chat posting requires the original unexpired confirmed call.");
79
+ const source = saved.source;
79
80
  return {
80
81
  ...base,
81
82
  operation_id: chatPostOperationId(ctx.session.id, ctx.callId),
82
- source: {
83
+ source: source.provider === "telegram" ? {
83
84
  provider: "telegram",
84
- chat_id: saved.source.chatId,
85
- thread_id: saved.source.threadId,
85
+ chat_id: source.chatId,
86
+ thread_id: source.threadId,
86
87
  ...base.source
88
+ } : {
89
+ provider: source.provider,
90
+ chat_id: source.chatId,
91
+ thread_id: source.threadId,
92
+ kind: source.kind,
93
+ ...source.peer === void 0 ? {} : { peer: source.peer }
87
94
  },
88
95
  expected: {
89
96
  chat_id: preview.chatId,
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { actionApproval, confirmations, inputHash } from "./confirmations.mjs";
8
8
  import { isChatPost } from "./chat-post-confirmation.mjs";
9
9
  import { ontologyTools } from "./ontology-tools.mjs";
10
- import { u as runtimeEnvelope } from "../../_chunks/principal-UlkbLrgQ.mjs";
10
+ import { u as runtimeEnvelope } from "../../_chunks/principal-BIX7T6Hh.mjs";
11
11
  import { sandboxFile } from "./sandbox-session.mjs";
12
12
  import { saveOntologyResult } from "./ontology-result-file.mjs";
13
13
  import { actorKey, actorOf } from "./actor.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 { c as compatibleRuntimeEnvelope, s as RUNTIME_SOURCE_PROTOCOL, u as runtimeEnvelope } from "../../_chunks/principal-UlkbLrgQ.mjs";
7
+ import { c as compatibleRuntimeEnvelope, s as RUNTIME_SOURCE_PROTOCOL, u as runtimeEnvelope } from "../../_chunks/principal-BIX7T6Hh.mjs";
8
8
  import "./agent-task.mjs";
9
9
  import { actorHeaders, actorKey, actorOf } from "./actor.mjs";
10
10
  import { CONFIRMATION_FACTS, CONFIRMATION_PREVIEW_METHOD, ConfirmationRefused, confirmationCard, describeConfirmation, factsConfirmation, object } from "./confirmation-description.mjs";
@@ -2,6 +2,10 @@ import type { RuntimeSource } from "@segmentstream/ontology";
2
2
  import type { SessionAuthContext } from "eve/context";
3
3
  import type { TelegramMessage } from "eve/channels/telegram";
4
4
  import type { StagedFile } from "./telegram/inbound-request.js";
5
+ /** A Telegram message's source, with the references only Telegram carries. */
6
+ export type TelegramRuntimeSource = Extract<RuntimeSource, {
7
+ readonly provider: "telegram";
8
+ }>;
5
9
  export type RuntimeEnvelope = {
6
10
  readonly version: 1;
7
11
  readonly session_id: string;
@@ -14,7 +18,7 @@ export type RuntimeEnvelope = {
14
18
  };
15
19
  };
16
20
  /** The source comes from the verified Telegram message and admitted storage results. */
17
- export declare function telegramRuntimeSource(message: Pick<TelegramMessage, "chat" | "messageId" | "messageThreadId" | "replyToMessage" | "from" | "raw" | "attachments">, files?: ReadonlyMap<string, StagedFile>, callbackQueryId?: string): RuntimeSource;
21
+ export declare function telegramRuntimeSource(message: Pick<TelegramMessage, "chat" | "messageId" | "messageThreadId" | "replyToMessage" | "from" | "raw" | "attachments">, files?: ReadonlyMap<string, StagedFile>, callbackQueryId?: string): TelegramRuntimeSource;
18
22
  /** Session auth is SDK-owned; no tool argument is read while rebuilding provenance. */
19
23
  export declare function principalRuntimeSource(principal?: SessionAuthContext | null): RuntimeSource | undefined;
20
24
  export declare function runtimeEnvelope(input?: {