@segmentstream/agent 0.68.1 → 0.69.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.69.1
4
+
5
+ Pins @segmentstream/ontology 0.144.0.
6
+
7
+ ## 0.69.0
8
+
9
+ Slack gets workspace callback actions, as Telegram has them. `channels.slack.callbacks: { entity,
10
+ action, contextVersion: 2 }` (on any channel of kind `slack`) names the routine action a press of a
11
+ Block Kit button whose `value` is `ws:<token>` calls, as the member paired with the Slack user who
12
+ pressed it. The action receives `{ token }`; its runtime source names the verified channel, thread,
13
+ pressed message and presser. Its result can acknowledge the press privately to the presser, edit
14
+ the pressed message (`edit.text`, `edit.blocks`) and queue one turn in the thread's session
15
+ (`context`). Someone not paired gets the workspace's pairing reply privately and nothing is called.
16
+ A token is at most 60 UTF-8 bytes in both channels, so one token serves both.
17
+
18
+ When a member first calls the agent into a Slack thread, the thread's earlier messages it records
19
+ now include messages of the agent's own Slack app the archive does not hold, such as a card the
20
+ workspace sent there through the connection: they are recorded as the workspace's, written by a
21
+ program, so the agent knows what a reply in the card's thread refers to.
22
+
3
23
  ## 0.68.1
4
24
 
5
25
  A member's typed answer settles an open usage-limit question in Telegram. While a chat's session waits on one, a message that is its answer (`1` or `2`, the option's id or label, or the workspace's `texts.usageLimit` button words, ignoring a leading mention and case) answers it as its buttons do and starts no turn. Eve resolved typed text against the question only in some deliveries, so in a group a typed `1` waited behind the question it was meant to answer.
@@ -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.68.1";
7
+ var version = "0.69.1";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -1,7 +1,7 @@
1
1
  import { type GroupPolicyInput } from "@segmentstream/ontology/groups";
2
2
  import { type GroupPolicy } from "./lib/group-routing/policy.js";
3
3
  import { type StructuredInbound } from "./lib/telegram/structured-settings.js";
4
- import type { WorkspaceActionHook } from "./lib/telegram/workspace-action.js";
4
+ import type { WorkspaceActionHook } from "./lib/workspace-action.js";
5
5
  import { type TelegramTexts } from "./lib/telegram/texts.js";
6
6
  import { type IdentifierPolicy } from "./lib/customer-text-safety.js";
7
7
  import type { AttachmentLifecycle } from "./lib/telegram/lifecycle.js";
@@ -272,6 +272,13 @@ export interface WhatsAppChannelInput {
272
272
  export interface SlackChannelInput {
273
273
  /** The key of the workspace's `SlackConnection`, such as `slack`. */
274
274
  readonly connection: string;
275
+ /**
276
+ * The routine action a press of a button the workspace sent calls, as the member who pressed
277
+ * it: a button whose `value` is `ws:<token>`. See `docs/agent.md`, "Workspace callback actions".
278
+ */
279
+ readonly callbacks?: Omit<WorkspaceActionHook, "contextVersion"> & {
280
+ readonly contextVersion: number;
281
+ };
275
282
  }
276
283
  /** `channels.email`, or a channel of kind `email`, as authored. */
277
284
  export interface EmailChannelInput {
@@ -552,6 +559,8 @@ export interface WhatsAppSettings {
552
559
  */
553
560
  export interface SlackSettings {
554
561
  readonly connection: string;
562
+ /** The action a press of a workspace button calls; without it such a press calls nothing. */
563
+ readonly callbacks?: WorkspaceActionHook;
555
564
  }
556
565
  /** The fewest and most minutes `checkAfterMinutes` may name, and its default. */
557
566
  export declare const EMAIL_CHECK_MINUTES: {
@@ -210,7 +210,11 @@ function slackSettings(value, issues, path = ["channels", "slack"]) {
210
210
  const slack = section({
211
211
  value,
212
212
  path,
213
- allowed: ["connection", "kind"],
213
+ allowed: [
214
+ "connection",
215
+ "kind",
216
+ "callbacks"
217
+ ],
214
218
  issues
215
219
  });
216
220
  if (slack === void 0) return null;
@@ -221,7 +225,11 @@ function slackSettings(value, issues, path = ["channels", "slack"]) {
221
225
  });
222
226
  return null;
223
227
  }
224
- return { connection: slack.connection };
228
+ const callbacks = workspaceHook(slack.callbacks, [...path, "callbacks"], issues);
229
+ return {
230
+ connection: slack.connection,
231
+ ...callbacks === void 0 ? {} : { callbacks }
232
+ };
225
233
  }
226
234
  const EMAIL_CHECK_MINUTES = {
227
235
  min: 10,
@@ -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-uZJeSn-O.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-B9V6_ebN.mjs";
@@ -31,7 +31,8 @@ import { type ChatArchive } from "../chat-archive.js";
31
31
  * replies continue it, and approvals and questions are buttons. Only paired members are answered;
32
32
  * anyone else gets the workspace's `replies.pairingRequired` text and a link to the app's
33
33
  * `/agent/connect`, privately. With `review`, a final reply its review holds is not posted:
34
- * approving it posts it in the same thread.
34
+ * approving it posts it in the same thread. A button the workspace sent with the value
35
+ * `ws:<token>` runs the action `callbacks` names as the member who pressed it.
35
36
  *
36
37
  * The channels the agent is in are reported to the ontology's `agent_chat` registry, titled as
37
38
  * Slack names them, when a paired member writes there and when the agent joins, leaves or sees one
@@ -19,6 +19,8 @@ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
19
19
  import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
20
20
  import { gatewayTranscriber } from "../inbound-media/speech.mjs";
21
21
  import { slackFileDownload, slackFiles } from "./files.mjs";
22
+ import { handleWorkspaceCallback } from "./callbacks.mjs";
23
+ import { pairingNotice } from "./pairing.mjs";
22
24
  import { recordThreadHistory } from "./thread-history.mjs";
23
25
  import { channelReview, withReviewedReplies } from "../review/reply.mjs";
24
26
  import { runtimeToken } from "../runtime-token.mjs";
@@ -336,7 +338,19 @@ function segmentstreamSlack(options) {
336
338
  const auth = await pairedPrincipal(submission.user.id);
337
339
  if (auth === null) return null;
338
340
  return { auth: submission.type === "block_actions" ? withButtonDecision(auth, submission.answers) : auth };
339
- }
341
+ },
342
+ onInteraction: (action, ctx) => handleWorkspaceCallback({
343
+ action,
344
+ ctx,
345
+ configuration: settings()?.callbacks,
346
+ admission: options.admission(),
347
+ identities: pairing(),
348
+ environment,
349
+ principal: slackPrincipal,
350
+ report,
351
+ token,
352
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
353
+ })
340
354
  });
341
355
  const reviewed = options.review === void 0 ? void 0 : channelReview(options.review, {
342
356
  environment,
@@ -494,15 +508,14 @@ async function receive(input) {
494
508
  context: [...media.context]
495
509
  };
496
510
  case "pairing_required": {
497
- const text = localizedText(admission.replies.pairingRequired);
498
- if (text !== void 0 && ctx.edit === void 0) {
499
- const code = (await identities.createPairing({
500
- provider: "slack",
501
- externalId: user,
502
- ...display === void 0 ? {} : { display }
503
- })).code;
504
- await notify(`${text}\n\n${appOrigin(input.environment)}/agent/connect?code=${encodeURIComponent(code)}`);
505
- }
511
+ const notice = ctx.edit === void 0 ? await pairingNotice({
512
+ admission,
513
+ identities,
514
+ environment: input.environment,
515
+ user,
516
+ ...display === void 0 ? {} : { display }
517
+ }) : void 0;
518
+ if (notice !== void 0) await notify(notice);
506
519
  return null;
507
520
  }
508
521
  case "refused": {
@@ -0,0 +1,31 @@
1
+ import type { SlackInteractionAction, SlackInteractionContext } from "eve/channels/slack";
2
+ import type { SessionAuthContext } from "eve/context";
3
+ import type { AdmissionSettings } from "../../config.js";
4
+ import type { Environment } from "../environment.js";
5
+ import type { AgentIdentities, PairedMember } from "../identities.js";
6
+ import type { RuntimeToken } from "../runtime-token.js";
7
+ import { type WorkspaceActionHook } from "../workspace-action.js";
8
+ /**
9
+ * A press of a button the workspace sent, whose `value` is `ws:<token>`: the routine action
10
+ * `channels.slack.callbacks` names runs as the member paired with the Slack user who pressed it,
11
+ * with the verified chat, thread, pressed message and presser as its runtime source. What the action
12
+ * returns can acknowledge the press privately to the presser, edit the pressed message and queue
13
+ * one turn in the thread's session. Anyone not paired gets the workspace's pairing reply, privately.
14
+ *
15
+ * There is no retry or token claim: expiry, audience checks, repeated presses and business
16
+ * idempotency belong to the workspace's action. A button with another value is not the
17
+ * workspace's to answer here and is left alone.
18
+ */
19
+ export declare function handleWorkspaceCallback(input: {
20
+ readonly action: SlackInteractionAction;
21
+ readonly ctx: Pick<SlackInteractionContext, "slack" | "send">;
22
+ readonly configuration: WorkspaceActionHook | undefined;
23
+ readonly admission: AdmissionSettings;
24
+ readonly identities: AgentIdentities;
25
+ readonly environment: Environment;
26
+ /** The session principal of a paired member's Slack account. */
27
+ readonly principal: (member: PairedMember, user: string) => SessionAuthContext;
28
+ readonly report: (operation: string, error: unknown) => void;
29
+ readonly token?: RuntimeToken;
30
+ readonly fetch?: typeof fetch;
31
+ }): Promise<void>;
@@ -0,0 +1,156 @@
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 { admitMessage } from "../admission.mjs";
8
+ import { It as runtimeEnvelope, bt as withChatAddress } from "../../../_chunks/principal-DYl7vqOp.mjs";
9
+ import { currentChannel } from "../channel-scope.mjs";
10
+ import { object } from "../confirmation-description.mjs";
11
+ import { workspaceAction, workspaceButtonToken } from "../workspace-action.mjs";
12
+ import { pairingNotice } from "./pairing.mjs";
13
+ import { randomUUID } from "node:crypto";
14
+ const DISPATCH_DEADLINE_MS = 1e4;
15
+ const ACKNOWLEDGEMENT_LIMIT = 200;
16
+ const CONTEXT_LIMIT = 16384;
17
+ const EDIT_TEXT_LIMIT = 4e4;
18
+ const EDIT_BLOCKS_LIMIT = 50;
19
+ const EDIT_PAYLOAD_LIMIT = 32768;
20
+ async function handleWorkspaceCallback(input) {
21
+ const { action, ctx, report } = input;
22
+ const token = workspaceButtonToken(action.value);
23
+ const messageTs = action.messageTs;
24
+ if (token === void 0 || messageTs === void 0) return;
25
+ if (input.configuration === void 0) {
26
+ report("workspace_callback_unconfigured", new Error("A workspace button was pressed in Slack, but channels.slack.callbacks is absent."));
27
+ return;
28
+ }
29
+ const user = action.user.id;
30
+ const channelId = ctx.slack.channelId;
31
+ const threadTs = ctx.slack.threadTs;
32
+ const direct = channelId.startsWith("D");
33
+ const privately = (text) => ctx.slack.request("chat.postEphemeral", {
34
+ channel: channelId,
35
+ user,
36
+ text,
37
+ ...threadTs === messageTs ? {} : { thread_ts: threadTs }
38
+ });
39
+ const lookup = await input.identities.lookup({
40
+ provider: "slack",
41
+ externalId: user
42
+ });
43
+ if (lookup.status !== "paired") {
44
+ if (lookup.status === "unknown") {
45
+ const display = action.user.username ?? action.user.name;
46
+ const notice = await pairingNotice({
47
+ admission: input.admission,
48
+ identities: input.identities,
49
+ environment: input.environment,
50
+ user,
51
+ ...display === void 0 ? {} : { display }
52
+ }).catch((error) => report("workspace_callback_pairing_failed", error));
53
+ if (typeof notice === "string") await privately(notice).catch((error) => report("workspace_callback_notice_failed", error));
54
+ }
55
+ return;
56
+ }
57
+ const channel = currentChannel("slack");
58
+ const address = {
59
+ provider: "slack",
60
+ ...channel === "slack" ? {} : { channel },
61
+ chatId: channelId,
62
+ threadId: threadTs,
63
+ kind: direct ? "private" : "group",
64
+ ...direct ? { peer: user } : {}
65
+ };
66
+ const principal = withChatAddress(input.principal(lookup.member, user), address);
67
+ const callId = action.triggerId ?? randomUUID();
68
+ const controller = new AbortController();
69
+ let timer;
70
+ let result;
71
+ try {
72
+ result = await Promise.race([workspaceAction({
73
+ configuration: input.configuration,
74
+ principal,
75
+ memberId: lookup.member.id,
76
+ input: { token },
77
+ signal: controller.signal,
78
+ envelope: runtimeEnvelope({
79
+ source: {
80
+ provider: "slack",
81
+ ...channel === "slack" ? {} : { channel },
82
+ chat_id: channelId,
83
+ thread_id: threadTs,
84
+ kind: address.kind,
85
+ ...direct ? { peer: user } : {},
86
+ message_id: messageTs,
87
+ sender: user
88
+ },
89
+ sessionId: `slack:callback:${callId}`,
90
+ callId
91
+ }),
92
+ environment: input.environment,
93
+ ...input.token === void 0 ? {} : { token: input.token },
94
+ ...input.fetch === void 0 ? {} : { fetch: input.fetch }
95
+ }), new Promise((resolve) => {
96
+ timer = setTimeout(() => {
97
+ controller.abort();
98
+ report("workspace_callback_timeout", new Error("A Slack workspace button's action took more than 10 seconds."));
99
+ resolve(void 0);
100
+ }, DISPATCH_DEADLINE_MS);
101
+ })]);
102
+ } catch (error) {
103
+ report("workspace_callback_failed", error);
104
+ return;
105
+ } finally {
106
+ if (timer !== void 0) clearTimeout(timer);
107
+ }
108
+ if (result === void 0) return;
109
+ const acknowledgement = result.acknowledgement;
110
+ if (typeof acknowledgement === "string" && acknowledgement.trim() !== "" && acknowledgement.length <= ACKNOWLEDGEMENT_LIMIT) await privately(acknowledgement).catch((error) => report("workspace_callback_ack_failed", error));
111
+ const edit = object(result.edit);
112
+ if (typeof edit.text === "string" || Array.isArray(edit.blocks)) try {
113
+ const text = typeof edit.text === "string" && edit.text.length <= EDIT_TEXT_LIMIT ? edit.text : void 0;
114
+ const blocks = Array.isArray(edit.blocks) && edit.blocks.length <= EDIT_BLOCKS_LIMIT ? edit.blocks : void 0;
115
+ if (text === void 0 && blocks === void 0) throw new Error("The callback edit has no text or blocks Slack accepts.");
116
+ const payload = {
117
+ channel: channelId,
118
+ ts: messageTs,
119
+ ...text === void 0 ? {} : { text },
120
+ ...blocks === void 0 ? {} : { blocks }
121
+ };
122
+ if (JSON.stringify(payload).length > EDIT_PAYLOAD_LIMIT) throw new Error("The callback edit exceeds the Slack hook limit.");
123
+ await ctx.slack.request("chat.update", payload);
124
+ } catch (error) {
125
+ report("workspace_callback_edit_failed", error);
126
+ }
127
+ const context = result.context;
128
+ if (typeof context !== "string" || context.trim() === "" || context.length > CONTEXT_LIMIT) return;
129
+ try {
130
+ const admitted = await admitMessage({
131
+ identity: {
132
+ provider: "slack",
133
+ externalId: user,
134
+ chat: direct ? "private" : "group",
135
+ turn: true
136
+ },
137
+ identities: input.identities,
138
+ settings: input.admission,
139
+ sendNotice: (text) => privately(text),
140
+ noticeFailed: (error) => report("workspace_callback_notice_failed", error),
141
+ ...direct ? { chat: {
142
+ channel,
143
+ chatId: channelId,
144
+ recipient: user
145
+ } } : {}
146
+ });
147
+ if (admitted.status !== "existing" && admitted.status !== "created" || admitted.member.id !== lookup.member.id || admitted.handled === true) return;
148
+ await ctx.send(context, {
149
+ auth: principal,
150
+ turnPolicy: "queue"
151
+ });
152
+ } catch (error) {
153
+ report("workspace_callback_turn_failed", error);
154
+ }
155
+ }
156
+ export { handleWorkspaceCallback };
@@ -0,0 +1,14 @@
1
+ import type { AdmissionSettings } from "../../config.js";
2
+ import { type Environment } from "../environment.js";
3
+ import type { AgentIdentities } from "../identities.js";
4
+ /**
5
+ * The workspace's `replies.pairingRequired` text with a link that pairs this Slack account to
6
+ * whoever opens it, for that person's eyes only; nothing without the reply.
7
+ */
8
+ export declare function pairingNotice(input: {
9
+ readonly admission: AdmissionSettings;
10
+ readonly identities: AgentIdentities;
11
+ readonly environment: Environment;
12
+ readonly user: string;
13
+ readonly display?: string;
14
+ }): Promise<string | undefined>;
@@ -0,0 +1,19 @@
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 { localizedText } from "../admission.mjs";
8
+ import { appOrigin } from "../environment.mjs";
9
+ async function pairingNotice(input) {
10
+ const text = localizedText(input.admission.replies.pairingRequired);
11
+ if (text === void 0) return;
12
+ const code = (await input.identities.createPairing({
13
+ provider: "slack",
14
+ externalId: input.user,
15
+ ...input.display === void 0 ? {} : { display: input.display }
16
+ })).code;
17
+ return `${text}\n\n${appOrigin(input.environment)}/agent/connect?code=${encodeURIComponent(code)}`;
18
+ }
19
+ export { pairingNotice };
@@ -4,8 +4,10 @@ import type { ChatArchive } from "../chat-archive.js";
4
4
  * Records the messages of a thread in a Slack channel written before a member first called the
5
5
  * agent into it, as messages that started no turn (docs/agent-chat-storage.md): its new session reads
6
6
  * them in its first turn's context, and the review of its replies reads them as the thread's. Slack
7
- * gives the thread's first 50 messages. The agent's own messages are left out, as are messages no
8
- * later than the newest the archive holds of the thread: those reached a session of the agent's.
7
+ * gives the thread's first 50 messages. Messages no later than the newest the archive holds of the
8
+ * thread are left out: those reached a session of the agent's. A message of the agent's own app the
9
+ * archive does not hold, such as a card the workspace sent through the Slack connection, is recorded
10
+ * as the workspace's, written by a program; the agent's own replies are in the archive already.
9
11
  */
10
12
  export declare function recordThreadHistory(input: {
11
13
  readonly archive: ChatArchive;
@@ -28,14 +28,22 @@ async function recordThreadHistory(input) {
28
28
  });
29
29
  for (const message of earlier) {
30
30
  const at = slackTime(message.ts);
31
- if (message.isMe || message.markdown.trim() === "" || at === void 0 || recordedUntil !== void 0 && Date.parse(at) <= recordedUntil) continue;
31
+ if (message.markdown.trim() === "" || at === void 0 || recordedUntil !== void 0 && Date.parse(at) <= recordedUntil) continue;
32
+ if (message.isMe) {
33
+ const [known] = (await input.archive.context({
34
+ ...chat,
35
+ messageId: message.ts,
36
+ limit: 1
37
+ })).events;
38
+ if (known !== void 0) continue;
39
+ }
32
40
  await recordChatMessage(input.archive, {
33
41
  ...chat,
34
42
  chatType: "group",
35
43
  participantIds: [input.memberId],
36
44
  eventId: `slack-thread:${input.channel}:${input.chatId}:${message.ts}`,
37
- direction: "inbound",
38
- by: message.botId === void 0 ? "human" : "bot",
45
+ direction: message.isMe ? "outbound" : "inbound",
46
+ by: message.isMe || message.botId !== void 0 ? "bot" : "human",
39
47
  senderId: message.user ?? message.botId ?? null,
40
48
  messageId: message.ts,
41
49
  text: message.markdown,
@@ -8,9 +8,9 @@ import { object } from "../confirmation-description.mjs";
8
8
  import { archivedRoutingMessages } from "../group-routing/routing-context.mjs";
9
9
  import { groupRoutingHealth } from "../group-routing/health.mjs";
10
10
  import { dispatchStructuredMessage, structuredMessage } from "./structured.mjs";
11
- import { handleWorkspaceCallback, isWorkspaceCallback } from "./callbacks.mjs";
11
+ import { handleWorkspaceCallback } from "./callbacks.mjs";
12
12
  import { telegramText, withTelegramTexts } from "./texts.mjs";
13
- import { t as agentBuild } from "../../../_chunks/build-metadata-uZJeSn-O.mjs";
13
+ import { t as agentBuild } from "../../../_chunks/build-metadata-B9V6_ebN.mjs";
14
14
  import { attachmentLifecycle } from "./lifecycle.mjs";
15
15
  import { manifestOf } from "../../config.mjs";
16
16
  import { gatewayAttachmentDescriber } from "./attachment-description.mjs";
@@ -30,6 +30,7 @@ import { telegramAppLinkContext } from "./app-links.mjs";
30
30
  import { gatewayImageDescriber } from "../inbound-media/images.mjs";
31
31
  import { chatMediaPlan, gatewayMediaCapabilities, sessionModel } from "../inbound-media/plan.mjs";
32
32
  import { gatewayTranscriber } from "../inbound-media/speech.mjs";
33
+ import { isWorkspaceCallback } from "../workspace-action.mjs";
33
34
  import { agentChats, channelChats } from "../chats.mjs";
34
35
  import { currentChannel, withNamedRoutes, withSessionChannels } from "../channel-scope.mjs";
35
36
  import { handleInboundMessage } from "./inbound.mjs";
@@ -3,7 +3,8 @@ import type { AdmissionSettings, SessionSettings, TelegramSettings } from "../..
3
3
  import type { AgentIdentities } from "../identities.js";
4
4
  import type { Environment } from "../environment.js";
5
5
  import type { RuntimeToken } from "../runtime-token.js";
6
- export declare const isWorkspaceCallback: (data?: string) => boolean;
6
+ import { isWorkspaceCallback } from "../workspace-action.js";
7
+ export { isWorkspaceCallback };
7
8
  /** A single dispatch and acknowledgement. Token policy and business idempotency belong to the workspace. */
8
9
  export declare function handleWorkspaceCallback(input: {
9
10
  readonly context: TelegramContext;
@@ -8,10 +8,9 @@ import { object } from "../confirmation-description.mjs";
8
8
  import { At as reportTelegramError, It as runtimeEnvelope, Lt as telegramRuntimeSource, c as currentInboundRequest, i as memberIdOf, o as telegramPrincipal } from "../../../_chunks/principal-DYl7vqOp.mjs";
9
9
  import { formatAddress, parseAddress, scopedAddress } from "./sessions.mjs";
10
10
  import { telegramText } from "./texts.mjs";
11
- import { workspaceAction } from "./workspace-action.mjs";
11
+ import { isWorkspaceCallback, workspaceAction, workspaceButtonToken } from "../workspace-action.mjs";
12
12
  import { admitMessage } from "../admission.mjs";
13
13
  import { currentChannel } from "../channel-scope.mjs";
14
- const isWorkspaceCallback = (data) => data?.startsWith("ws:") === true;
15
14
  async function handleWorkspaceCallback(input) {
16
15
  const { query, context } = input;
17
16
  const locale = query.from.languageCode;
@@ -22,8 +21,8 @@ async function handleWorkspaceCallback(input) {
22
21
  const controller = new AbortController();
23
22
  let timer;
24
23
  try {
25
- const token = query.data?.slice(3) ?? "";
26
- if (!query.message || query.from.isBot || !token || new TextEncoder().encode(token).byteLength > 60) acknowledgement = telegramText("callback", "unknown", locale);
24
+ const token = workspaceButtonToken(query.data);
25
+ if (!query.message || query.from.isBot || token === void 0) acknowledgement = telegramText("callback", "unknown", locale);
27
26
  else if (input.configuration === void 0) acknowledgement = telegramText("callback", "unsupported", locale);
28
27
  else {
29
28
  const message = {
@@ -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-uZJeSn-O.mjs";
7
+ import { t as agentBuild } from "../../../_chunks/build-metadata-B9V6_ebN.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";
@@ -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 { WorkspaceActionAlreadyDispatched } from "./workspace-action.mjs";
7
+ import { WorkspaceActionAlreadyDispatched } from "../workspace-action.mjs";
8
8
  import { structuredMessage } from "./structured.mjs";
9
9
  import { currentChannel } from "../channel-scope.mjs";
10
10
  import { At as reportTelegramError, It as runtimeEnvelope, Lt as telegramRuntimeSource, f as attachmentsContext, n as chatLanguage, o as telegramPrincipal, x as attachmentUrl } from "../../../_chunks/principal-DYl7vqOp.mjs";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { E as OntologyActionNotPermitted, Ft as principalRuntimeSource, It as runtimeEnvelope, L as needsConfirmation, Lt as telegramRuntimeSource, W as member, c as currentInboundRequest, j as ontologyTools, k as actionToolName } from "../../../_chunks/principal-DYl7vqOp.mjs";
8
- import { t as agentBuild } from "../../../_chunks/build-metadata-uZJeSn-O.mjs";
8
+ import { t as agentBuild } from "../../../_chunks/build-metadata-B9V6_ebN.mjs";
9
9
  import { object } from "../confirmation-description.mjs";
10
10
  var AttachmentLifecycleNotPermitted = class extends Error {
11
11
  code = "attachment_lifecycle_not_permitted";
@@ -1,4 +1,4 @@
1
- import type { WorkspaceActionHook } from "./workspace-action.js";
1
+ import type { WorkspaceActionHook } from "../workspace-action.js";
2
2
  export declare const STRUCTURED_KINDS: readonly ["location", "venue", "contact"];
3
3
  export type StructuredKind = (typeof STRUCTURED_KINDS)[number];
4
4
  export interface StructuredInbound extends WorkspaceActionHook {
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { It as runtimeEnvelope, Lt as telegramRuntimeSource } from "../../../_chunks/principal-DYl7vqOp.mjs";
8
- import { workspaceAction } from "./workspace-action.mjs";
8
+ import { workspaceAction } from "../workspace-action.mjs";
9
9
  import { STRUCTURED_KINDS } from "./structured-settings.mjs";
10
10
  const record = (value) => {
11
11
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid structured Telegram object.");
@@ -1,9 +1,17 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
- import type { RuntimeEnvelope } from "../runtime-envelope.js";
3
- import type { Environment } from "../environment.js";
4
- import type { RuntimeToken } from "../runtime-token.js";
2
+ import type { RuntimeEnvelope } from "./runtime-envelope.js";
3
+ import type { Environment } from "./environment.js";
4
+ import type { RuntimeToken } from "./runtime-token.js";
5
5
  export declare class WorkspaceActionAlreadyDispatched extends Error {
6
6
  }
7
+ /** What a button the workspace sends carries before its token: `ws:<token>`. */
8
+ export declare const WORKSPACE_BUTTON_PREFIX = "ws:";
9
+ /** The most bytes a workspace button's token holds: what fits Telegram's callback data. */
10
+ export declare const WORKSPACE_TOKEN_BYTES = 60;
11
+ /** Whether a button's data is a workspace button's, which the workspace's own action answers. */
12
+ export declare const isWorkspaceCallback: (data?: string) => boolean;
13
+ /** A workspace button's token, or undefined when it is empty or longer than the limit. */
14
+ export declare function workspaceButtonToken(data: string | undefined): string | undefined;
7
15
  export interface WorkspaceActionHook {
8
16
  readonly entity: string;
9
17
  readonly action: string;
@@ -4,9 +4,16 @@ 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 { L as needsConfirmation, W as member, j as ontologyTools, k as actionToolName } from "../../../_chunks/principal-DYl7vqOp.mjs";
8
- import { object } from "../confirmation-description.mjs";
7
+ import { L as needsConfirmation, W as member, j as ontologyTools, k as actionToolName } from "../../_chunks/principal-DYl7vqOp.mjs";
8
+ import { object } from "./confirmation-description.mjs";
9
9
  var WorkspaceActionAlreadyDispatched = class extends Error {};
10
+ const WORKSPACE_BUTTON_PREFIX = "ws:";
11
+ const WORKSPACE_TOKEN_BYTES = 60;
12
+ const isWorkspaceCallback = (data) => data?.startsWith("ws:") === true;
13
+ function workspaceButtonToken(data) {
14
+ const token = isWorkspaceCallback(data) ? data.slice(3) : "";
15
+ return token === "" || new TextEncoder().encode(token).byteLength > 60 ? void 0 : token;
16
+ }
10
17
  async function workspaceAction(input) {
11
18
  const action = actionToolName(input.configuration.entity, input.configuration.action);
12
19
  const tools = ontologyTools({
@@ -15,14 +22,14 @@ async function workspaceAction(input) {
15
22
  if (name === action) await input.beforeDispatch?.();
16
23
  }
17
24
  });
18
- if (needsConfirmation(await tools.labels(member(input.memberId), action, input.input, input.signal))) throw new Error("A Telegram workspace hook must be a permitted routine action.");
19
- if (!await tools.supportsRuntimeSource(member(input.memberId), input.signal)) throw new Error("A Telegram workspace hook requires the runtime-source capability.");
25
+ if (needsConfirmation(await tools.labels(member(input.memberId), action, input.input, input.signal))) throw new Error("A workspace hook must be a permitted routine action.");
26
+ if (!await tools.supportsRuntimeSource(member(input.memberId), input.signal)) throw new Error("A workspace hook requires the runtime-source capability.");
20
27
  const raw = await tools.rpc(member(input.memberId), "tools/call", {
21
28
  name: action,
22
29
  arguments: input.input
23
30
  }, input.signal);
24
31
  const envelope = object(raw.structuredContent);
25
- if (object(envelope.validation).ok === false) throw new Error("The Telegram workspace hook rejected its event.");
32
+ if (object(envelope.validation).ok === false) throw new Error("The workspace hook rejected its event.");
26
33
  return object(envelope.result ?? envelope);
27
34
  }
28
- export { WorkspaceActionAlreadyDispatched, workspaceAction };
35
+ export { WORKSPACE_BUTTON_PREFIX, WORKSPACE_TOKEN_BYTES, WorkspaceActionAlreadyDispatched, isWorkspaceCallback, workspaceAction, workspaceButtonToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/agent",
3
- "version": "0.68.1",
3
+ "version": "0.69.1",
4
4
  "description": "The SegmentStream workspace agent: the ontology as tools, acting as the member who writes, and the browser, Telegram, WhatsApp and Slack through the workspace's connections.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -80,7 +80,7 @@
80
80
  "@chat-adapter/state-memory": "4.42.0",
81
81
  "@chat-adapter/telegram": "4.41.0",
82
82
  "@chat-adapter/whatsapp": "4.42.0",
83
- "@segmentstream/ontology": "0.143.0",
83
+ "@segmentstream/ontology": "0.144.0",
84
84
  "@vercel/oidc": "^3.8.4",
85
85
  "ai": "^7.0.172",
86
86
  "chat": "4.42.0",