@segmentstream/ontology 0.144.0 → 0.146.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.146.0
4
+
5
+ `initialize` lists the channels a tool call's runtime source may name (`telegram`, `slack`,
6
+ `whatsapp`), so that an agent sends a Slack or WhatsApp message's source only to an ontology that
7
+ reads it. `RUNTIME_SOURCE_PROVIDERS` exports the list.
8
+
9
+ ## 0.145.0
10
+
11
+ `agent_chat.send` takes `buttons` under a text: rows of links (`{ text, url }`) and workspace
12
+ buttons (`{ text, token }`, a token of at most 60 UTF-8 bytes), whose press calls the workspace's
13
+ button action with `{ token }` as the member who pressed it. Each channel lays them out its own way:
14
+ an inline keyboard in Telegram, rows of buttons under a Markdown block in Slack, and on WhatsApp an
15
+ interactive message with up to three workspace buttons (labels of at most 20 characters, each its
16
+ own) or one link, under at most 1,024 characters.
17
+
18
+ A channel that cannot show the buttons as given refuses the message with
19
+ `refusal: "buttons_unsupported"` before its key is reserved, so the key stays free; nothing is cut.
20
+ The key binds the buttons. The chat's history keeps the text with the buttons after it, so a card a
21
+ workflow sends with buttons is part of the conversation the agent reads, in every channel. A
22
+ template has its own buttons and takes none.
23
+
3
24
  ## 0.144.0
4
25
 
5
26
  The built-in entities `agent_chat`, `agent_review` and `app_feedback` replicate to the warehouse
@@ -85,6 +85,13 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
85
85
  readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
86
86
  }>>;
87
87
  readonly replyTo: Schema.optionalKey<Schema.String>;
88
+ readonly buttons: Schema.optionalKey<Schema.$Array<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
89
+ readonly text: Schema.String;
90
+ readonly url: Schema.String;
91
+ }>, Schema.Struct<{
92
+ readonly text: Schema.String;
93
+ readonly token: Schema.String;
94
+ }>]>>>>;
88
95
  readonly idempotencyKey: Schema.String;
89
96
  }>, {
90
97
  readonly status: "sent" | "uncertain";
@@ -229,7 +229,12 @@ export const AgentChat = entity("agent_chat", {
229
229
  "(on WhatsApp the person last wrote more than 24 hours ago), recipient_unreachable or " +
230
230
  "recipient_opted_out. On WhatsApp, template sends an approved template in place of text, " +
231
231
  "which reaches a person outside the 24 hours, with its body's, header's and buttons' " +
232
- "values; give exactly one of text and template.",
232
+ "values; give exactly one of text and template. buttons puts rows of buttons under a " +
233
+ "text: links ({ text, url }) and workspace buttons ({ text, token }), whose press calls the " +
234
+ "workspace's button action with { token } as the member who pressed it. A channel that " +
235
+ "cannot show them as given refuses the message with refusal buttons_unsupported before " +
236
+ "spending the key: WhatsApp shows one link, or up to three workspace buttons with labels of " +
237
+ "at most 20 characters, under at most 1,024 characters.",
233
238
  input: ChatSendInput,
234
239
  hints: { destructive: false, irreversible: true, idempotent: true },
235
240
  connections: [],
package/dist/chat.d.ts CHANGED
@@ -65,6 +65,29 @@ export declare const ChatTemplate: Schema.Struct<{
65
65
  readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
66
66
  }>;
67
67
  export type ChatTemplate = typeof ChatTemplate.Type;
68
+ /** The most UTF-8 bytes of a workspace button's token: what fits Telegram's callback data. */
69
+ export declare const CHAT_BUTTON_TOKEN_BYTES = 60;
70
+ /**
71
+ * A button under a message the agent sends: a link it opens, by an https URL, or a workspace button,
72
+ * whose press calls the workspace's button action as the member who pressed it, with this token.
73
+ */
74
+ export declare const ChatButton: Schema.Union<readonly [Schema.Struct<{
75
+ readonly text: Schema.String;
76
+ readonly url: Schema.String;
77
+ }>, Schema.Struct<{
78
+ readonly text: Schema.String;
79
+ readonly token: Schema.String;
80
+ }>]>;
81
+ export type ChatButton = typeof ChatButton.Type;
82
+ /** A message's buttons by row, as the person sees them; each channel lays them out its own way. */
83
+ export declare const ChatButtonRows: Schema.$Array<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
84
+ readonly text: Schema.String;
85
+ readonly url: Schema.String;
86
+ }>, Schema.Struct<{
87
+ readonly text: Schema.String;
88
+ readonly token: Schema.String;
89
+ }>]>>>;
90
+ export type ChatButtonRows = typeof ChatButtonRows.Type;
68
91
  /** What `agent_chat.send` takes: a post's text, or on WhatsApp an approved template instead. */
69
92
  export declare const ChatSendInput: Schema.Struct<{
70
93
  readonly chat: Schema.String;
@@ -88,6 +111,13 @@ export declare const ChatSendInput: Schema.Struct<{
88
111
  readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
89
112
  }>>;
90
113
  readonly replyTo: Schema.optionalKey<Schema.String>;
114
+ readonly buttons: Schema.optionalKey<Schema.$Array<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
115
+ readonly text: Schema.String;
116
+ readonly url: Schema.String;
117
+ }>, Schema.Struct<{
118
+ readonly text: Schema.String;
119
+ readonly token: Schema.String;
120
+ }>]>>>>;
91
121
  readonly idempotencyKey: Schema.String;
92
122
  }>;
93
123
  export type ChatSendInput = typeof ChatSendInput.Type;
package/dist/chat.js CHANGED
@@ -50,6 +50,42 @@ export const ChatTemplate = Schema.Struct({
50
50
  "returns when tapped.",
51
51
  })),
52
52
  });
53
+ /** The most UTF-8 bytes of a workspace button's token: what fits Telegram's callback data. */
54
+ export const CHAT_BUTTON_TOKEN_BYTES = 60;
55
+ /** A button's label: one line, as the person reads it. Each channel bounds it further. */
56
+ const ButtonLabel = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(75), Schema.makeFilter((value) => value === value.trim() && !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(value)
57
+ ? undefined
58
+ : "Expected one line of text, without spaces around it"));
59
+ /**
60
+ * A button under a message the agent sends: a link it opens, by an https URL, or a workspace button,
61
+ * whose press calls the workspace's button action as the member who pressed it, with this token.
62
+ */
63
+ export const ChatButton = Schema.Union([
64
+ Schema.Struct({
65
+ text: ButtonLabel,
66
+ url: Schema.String.check(Schema.isMaxLength(2048), Schema.makeFilter((value) => {
67
+ try {
68
+ return new URL(value).protocol === "https:" ? undefined : "Expected an https URL";
69
+ }
70
+ catch {
71
+ return "Expected an https URL";
72
+ }
73
+ })).annotate({ description: "The https link the button opens." }),
74
+ }),
75
+ Schema.Struct({
76
+ text: ButtonLabel,
77
+ token: Schema.String.check(Schema.makeFilter((value) => value !== "" &&
78
+ new TextEncoder().encode(value).byteLength <= CHAT_BUTTON_TOKEN_BYTES &&
79
+ !/\p{Cc}/u.test(value)
80
+ ? undefined
81
+ : `Expected 1 to ${CHAT_BUTTON_TOKEN_BYTES} UTF-8 bytes without control characters`)).annotate({
82
+ description: "What the workspace's button action receives as { token } when the button is pressed, " +
83
+ "such as the record and what to do with it.",
84
+ }),
85
+ }),
86
+ ]);
87
+ /** A message's buttons by row, as the person sees them; each channel lays them out its own way. */
88
+ export const ChatButtonRows = Schema.Array(Schema.Array(ChatButton).check(Schema.isMinLength(1), Schema.isMaxLength(8))).check(Schema.isMinLength(1), Schema.isMaxLength(10));
53
89
  /** What `agent_chat.send` takes: a post's text, or on WhatsApp an approved template instead. */
54
90
  export const ChatSendInput = Schema.Struct({
55
91
  chat: Identifier,
@@ -61,6 +97,10 @@ export const ChatSendInput = Schema.Struct({
61
97
  "more than 24 hours ago.",
62
98
  })),
63
99
  replyTo: Schema.optionalKey(Identifier),
100
+ buttons: Schema.optionalKey(ChatButtonRows.annotate({
101
+ description: "Buttons under the text, by row: links, and workspace buttons whose press calls the " +
102
+ "workspace's button action. A channel that cannot show them as given refuses the message.",
103
+ })),
64
104
  idempotencyKey: Identifier,
65
105
  });
66
106
  export const ChatPostResult = Schema.Struct({
package/dist/index.d.ts CHANGED
@@ -114,6 +114,7 @@ export { sqlAgentStore, resolveChannelIdentity, resolveChannelSignIn } from "./r
114
114
  export { DEFAULT_AGENT_LIMITS, PLATFORM_CHANNEL_LIMITS, clampChannelLimits, effectiveChannelLimits, } from "./runtime/agent-counters.js";
115
115
  export type { ChannelAppProvider } from "./service/channel/provider.js";
116
116
  export type { RuntimeSource, ActionRuntime } from "./runtime-source.js";
117
+ export { RUNTIME_SOURCE_PROVIDERS } from "./runtime-source.js";
117
118
  export { callbackIdentityToken, serveWorkflowCallback } from "./service/workflow-callback.js";
118
119
  export { compiledWorkflowId, triggerPath, vercelWorkflowEngine, WorkflowStepFailed, } from "./service/workflows.js";
119
120
  export type { WorkflowEngine, WorkflowPage, WorkflowRunRecord, WorkflowStepRecord, } from "./service/workflows.js";
package/dist/index.js CHANGED
@@ -77,6 +77,7 @@ export { runBlobStorageMaintenance } from "./storage/operator.js";
77
77
  export { runNewUserHook } from "./runtime/new-user-hook.js";
78
78
  export { sqlAgentStore, resolveChannelIdentity, resolveChannelSignIn } from "./runtime/agents.js";
79
79
  export { DEFAULT_AGENT_LIMITS, PLATFORM_CHANNEL_LIMITS, clampChannelLimits, effectiveChannelLimits, } from "./runtime/agent-counters.js";
80
+ export { RUNTIME_SOURCE_PROVIDERS } from "./runtime-source.js";
80
81
  export { callbackIdentityToken, serveWorkflowCallback } from "./service/workflow-callback.js";
81
82
  export { compiledWorkflowId, triggerPath, vercelWorkflowEngine, WorkflowStepFailed, } from "./service/workflows.js";
82
83
  export { validateBrowserSignIn } from "./sign-in.js";
@@ -1,4 +1,9 @@
1
1
  import { Schema } from "effect";
2
+ /**
3
+ * The channels whose message a tool call's runtime source can name. `initialize` lists them, so
4
+ * that an agent sends only a source its ontology reads.
5
+ */
6
+ export declare const RUNTIME_SOURCE_PROVIDERS: readonly ["telegram", "slack", "whatsapp"];
2
7
  /** Decoded only at a verified runtime boundary; ordinary action arguments never establish provenance. */
3
8
  export declare const RuntimeSource: Schema.Union<readonly [Schema.Struct<{
4
9
  readonly provider: Schema.Literal<"telegram">;
@@ -11,6 +11,11 @@ const TelegramLocation = Schema.Struct({
11
11
  horizontal_accuracy: Schema.optionalKey(Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1500 }))),
12
12
  live_period: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
13
13
  });
14
+ /**
15
+ * The channels whose message a tool call's runtime source can name. `initialize` lists them, so
16
+ * that an agent sends only a source its ontology reads.
17
+ */
18
+ export const RUNTIME_SOURCE_PROVIDERS = ["telegram", "slack", "whatsapp"];
14
19
  /** A Telegram chat, with the references Telegram's own actions and attachments use. */
15
20
  const TelegramRuntimeSource = Schema.Struct({
16
21
  provider: Schema.Literal("telegram"),
@@ -9,7 +9,7 @@ import type { DeliveryArchive } from "./archive.js";
9
9
  import type { RuntimeChatEnvelope } from "./envelope.js";
10
10
  import type { ChatArchiveTransport } from "../agent/chat-archive.js";
11
11
  import { type Destination } from "./resolve.js";
12
- import type { AgentChannelTransport } from "./providers/provider.js";
12
+ import { type AgentChannelTransport } from "./providers/provider.js";
13
13
  import { type HistoryArchive } from "./history-import.js";
14
14
  export type ChatDeliveryFactory = (input: {
15
15
  readonly backend: OntologyBackend["Service"];
@@ -10,6 +10,7 @@ import { deliveryRequester } from "./attribution.js";
10
10
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
11
11
  import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
12
12
  import { chatResolver } from "./resolve.js";
13
+ import { buttonLines } from "./providers/provider.js";
13
14
  import { reviewSender } from "./review-delivery.js";
14
15
  import { chatPeopleQuery, historyImporter } from "./history-import.js";
15
16
  import { reviewReviser } from "./review-revision.js";
@@ -62,12 +63,19 @@ chats) {
62
63
  */
63
64
  const check = (input, approved = true, asAgent = false) => Effect.gen(function* () {
64
65
  const template = "template" in input ? input.template : undefined;
66
+ const buttons = "buttons" in input ? input.buttons : undefined;
65
67
  // A message is text, or on WhatsApp a template the agent sends; a post is always text.
66
68
  if ((input.text === undefined) === (template === undefined) || (template && !asAgent)) {
67
69
  return yield* new ActionRejected({
68
70
  message: "Give exactly one of text and template.",
69
71
  });
70
72
  }
73
+ // An approved template has its own buttons, given by their values.
74
+ if (buttons !== undefined && (template !== undefined || !asAgent)) {
75
+ return yield* new ActionRejected({
76
+ message: "Buttons go under a text the agent sends; a template's are its own.",
77
+ });
78
+ }
71
79
  const permission = asAgent ? "agent_chat:send" : "agent_chat:post_message";
72
80
  if (!isAllowed(permission, context.principal)) {
73
81
  return yield* new PermissionDenied({
@@ -256,6 +264,18 @@ chats) {
256
264
  plainText.length > provider.limit) {
257
265
  return yield* invalid();
258
266
  }
267
+ // Buttons the channel cannot show as given are refused before the key is reserved.
268
+ if (buttons !== undefined) {
269
+ const refused = provider.refuseButtons === undefined
270
+ ? "This chat's channel shows no buttons."
271
+ : provider.refuseButtons(buttons, finalText);
272
+ if (refused !== undefined) {
273
+ return yield* new ActionRejected({
274
+ message: `${refused} Nothing was sent.`,
275
+ refusal: "buttons_unsupported",
276
+ });
277
+ }
278
+ }
259
279
  const preview = { ...destination, text, finalText };
260
280
  if (context.caller.kind === "runtime" && approved) {
261
281
  const envelope = context.envelope;
@@ -284,7 +304,8 @@ chats) {
284
304
  provider,
285
305
  inbox,
286
306
  preview,
287
- fingerprint: deliveryFingerprint(preview, requester),
307
+ buttons,
308
+ fingerprint: deliveryFingerprint(preview, requester, undefined, buttons),
288
309
  compose: Effect.succeed({
289
310
  preview,
290
311
  payload: undefined,
@@ -471,7 +492,9 @@ chats) {
471
492
  /** One delivery: posted with its requester's attribution, or sent as the agent without it. */
472
493
  function deliver(input, asAgent) {
473
494
  return Effect.gen(function* () {
474
- const { target, requester, connection, provider, inbox, fingerprint, compose } = yield* check(input, true, asAgent);
495
+ const checked = yield* check(input, true, asAgent);
496
+ const { target, requester, connection, provider, inbox, fingerprint, compose } = checked;
497
+ const buttons = "buttons" in checked ? checked.buttons : undefined;
475
498
  const scope = deliveryScopeDigest({
476
499
  via: requester.via,
477
500
  subjectId: requester.id,
@@ -518,6 +541,10 @@ chats) {
518
541
  }
519
542
  }
520
543
  const { preview, payload, summary } = yield* compose;
544
+ // The message as sent without formatting: the text, then any attribution.
545
+ const plainText = preview.attribution === ""
546
+ ? preview.text
547
+ : `${preview.text}${separator}${preview.attribution}`;
521
548
  // A member who answers in the inbox writes as themselves, not as the agent.
522
549
  const staff = inbox !== undefined && context.caller.kind === "member" && !asAgent;
523
550
  const place = inbox ?? (yield* personalChat(target));
@@ -540,15 +567,13 @@ chats) {
540
567
  turnId: null,
541
568
  // The claim binds text immutably. Keep the source here and the actual wire payload
542
569
  // in argsSummary, which can record the plain retry without changing that binding. A
543
- // message without attribution is kept as written.
544
- text: preview.attribution === ""
545
- ? preview.text
546
- : `${preview.text}${separator}${preview.attribution}`,
570
+ // message without attribution is kept as written, its buttons after it as they read.
571
+ text: buttons === undefined ? plainText : `${plainText}\n\n${buttonLines(buttons)}`,
547
572
  decision: null,
548
573
  reason: null,
549
574
  toolCallId: null,
550
575
  toolName: null,
551
- argsSummary: JSON.stringify(summary ?? payload ?? provider.payload(preview.finalText)),
576
+ argsSummary: JSON.stringify(summary ?? payload ?? provider.payload(preview.finalText, buttons)),
552
577
  status: "requested",
553
578
  attachments: [],
554
579
  requestedBy: requester,
@@ -583,11 +608,12 @@ chats) {
583
608
  attribution: preview.attribution,
584
609
  finalText: preview.finalText,
585
610
  previews: destinationPreviews,
586
- plainText: event.text,
611
+ plainText,
587
612
  replyTo: preview.replyTo,
588
613
  agent: agentTransport,
589
614
  operationId,
590
615
  ...(payload === undefined ? {} : { payload }),
616
+ ...(buttons === undefined ? {} : { buttons }),
591
617
  ...(inbox === undefined ? {} : { threadId: inbox.threadId, chatId: inbox.chatId }),
592
618
  transport: connections({
593
619
  identityToken: context.identityToken,
@@ -1,4 +1,4 @@
1
- import type { ChatPreview } from "../../chat.js";
1
+ import type { ChatButtonRows, ChatPreview } from "../../chat.js";
2
2
  import type { ChatRequester } from "./attribution.js";
3
3
  interface DeliveryScopeIdentifiers {
4
4
  readonly via: ChatRequester["via"];
@@ -36,5 +36,7 @@ export declare function deliveryFingerprint(preview: Pick<ChatPreview, "chatId"
36
36
  };
37
37
  };
38
38
  readonly buttons?: Readonly<Record<string, string>>;
39
- }): string;
39
+ },
40
+ /** Buttons under a text, bound when given so a key without them keeps its binding. */
41
+ buttons?: ChatButtonRows): string;
40
42
  export {};
@@ -20,7 +20,9 @@ export const deliveryKeyDigest = (idempotencyKey) => digest(JSON.stringify(idemp
20
20
  * message binds the template it names and its values in place of the text, which is read from
21
21
  * WhatsApp when it is sent: a replay finds its receipt however the template has changed since.
22
22
  */
23
- export function deliveryFingerprint(preview, requester, template) {
23
+ export function deliveryFingerprint(preview, requester, template,
24
+ /** Buttons under a text, bound when given so a key without them keeps its binding. */
25
+ buttons) {
24
26
  const sorted = (values) => Object.entries(values).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0));
25
27
  const media = template?.header?.media;
26
28
  return digest(JSON.stringify([
@@ -28,7 +30,7 @@ export function deliveryFingerprint(preview, requester, template) {
28
30
  preview.provider,
29
31
  preview.externalId,
30
32
  ...(template === undefined
31
- ? [preview.finalText, preview.text]
33
+ ? [preview.finalText, preview.text, ...(buttons === undefined ? [] : [{ buttons }])]
32
34
  : [
33
35
  {
34
36
  template: template.name,
@@ -1,4 +1,5 @@
1
1
  import { type Effect, type Exit } from "effect";
2
+ import type { ChatButtonRows } from "../../../chat.js";
2
3
  import type { TelegramPreviewContext } from "../../../telegram.js";
3
4
  import { ConnectionError, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
4
5
  import type { ActionRejected } from "../../../errors.js";
@@ -52,6 +53,8 @@ export interface ChatSend {
52
53
  readonly operationId?: string;
53
54
  /** What the provider sends in place of the text, such as a WhatsApp template; others ignore it. */
54
55
  readonly payload?: Readonly<Record<string, unknown>>;
56
+ /** Buttons under the text, which a provider that shows them lays out its own way. */
57
+ readonly buttons?: ChatButtonRows;
55
58
  /**
56
59
  * The chat's own id where it differs from the destination's, as a reviewed reply's chat does;
57
60
  * a workspace channel's send receives it, others ignore it.
@@ -92,8 +95,14 @@ export interface ChatProvider {
92
95
  readonly finalText: string;
93
96
  readonly plainText: string;
94
97
  };
95
- /** The payload a delivery records before the provider answers. */
96
- readonly payload: (finalText: string) => Readonly<Record<string, unknown>>;
98
+ /** The payload a delivery records before the provider answers, its buttons laid out. */
99
+ readonly payload: (finalText: string, buttons?: ChatButtonRows) => Readonly<Record<string, unknown>>;
100
+ /**
101
+ * Why the provider cannot show these buttons under the message as given, or undefined when it
102
+ * can. It is checked before the message is reserved, so a refusal spends no key. Absent for a
103
+ * provider that shows no buttons, which refuses them all.
104
+ */
105
+ readonly refuseButtons?: (rows: ChatButtonRows, finalText: string) => string | undefined;
97
106
  /** One attempt: `sent` only when the provider's answer proves it. */
98
107
  readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
99
108
  /**
@@ -114,3 +123,8 @@ export interface ChatProvider {
114
123
  */
115
124
  export declare function transportFailure(payload: ProviderOutcome["payload"], result: Exit.Failure<ConnectionReply, ConnectionError>): ProviderOutcome;
116
125
  export declare const record: (value: unknown) => Record<string, unknown>;
126
+ /**
127
+ * A message's buttons as its history keeps them, one a line, as the person reads them: a link where
128
+ * it leads, a workspace button by its label. The tokens stay in the delivery's payload.
129
+ */
130
+ export declare function buttonLines(rows: ChatButtonRows): string;
@@ -26,3 +26,13 @@ export function transportFailure(payload, result) {
26
26
  export const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
27
27
  ? value
28
28
  : {};
29
+ /**
30
+ * A message's buttons as its history keeps them, one a line, as the person reads them: a link where
31
+ * it leads, a workspace button by its label. The tokens stay in the delivery's payload.
32
+ */
33
+ export function buttonLines(rows) {
34
+ return rows
35
+ .flat()
36
+ .map((button) => ("url" in button ? `[${button.text}](${button.url})` : button.text))
37
+ .join("\n");
38
+ }
@@ -1,5 +1,12 @@
1
1
  import { Effect } from "effect";
2
+ import type { ChatButtonRows } from "../../../chat.js";
2
3
  import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
4
+ /**
5
+ * A message with buttons as Slack shows it: the Markdown in a `markdown` block, then a row of
6
+ * buttons in an `actions` block each, a workspace button's value `ws:<token>`, with the plain text
7
+ * for notifications. Without buttons, the Markdown as `markdown_text`, which takes no blocks.
8
+ */
9
+ export declare function slackPayload(finalText: string, plainText: string, buttons?: ChatButtonRows): Readonly<Record<string, unknown>>;
3
10
  /**
4
11
  * One `chat.postMessage` through the connection's `web` API, never retried, in the thread of the
5
12
  * message it replies to, else in the chat's thread, such as the one a reviewed reply answers.
@@ -12,6 +12,31 @@ const POSSIBLY_POSTED = new Set([
12
12
  "fatal_error",
13
13
  "service_unavailable",
14
14
  ]);
15
+ /**
16
+ * A message with buttons as Slack shows it: the Markdown in a `markdown` block, then a row of
17
+ * buttons in an `actions` block each, a workspace button's value `ws:<token>`, with the plain text
18
+ * for notifications. Without buttons, the Markdown as `markdown_text`, which takes no blocks.
19
+ */
20
+ export function slackPayload(finalText, plainText, buttons) {
21
+ return buttons === undefined
22
+ ? { markdown_text: finalText }
23
+ : {
24
+ text: plainText,
25
+ blocks: [
26
+ { type: "markdown", text: finalText },
27
+ ...buttons.map((row, rowIndex) => ({
28
+ type: "actions",
29
+ elements: row.map((button, index) => ({
30
+ type: "button",
31
+ text: { type: "plain_text", text: button.text },
32
+ ...("url" in button
33
+ ? { action_id: `link:${rowIndex}:${index}`, url: button.url }
34
+ : { action_id: `ws:${rowIndex}:${index}`, value: `ws:${button.token}` }),
35
+ })),
36
+ })),
37
+ ],
38
+ };
39
+ }
15
40
  /**
16
41
  * One `chat.postMessage` through the connection's `web` API, never retried, in the thread of the
17
42
  * message it replies to, else in the chat's thread, such as the one a reviewed reply answers.
@@ -20,7 +45,7 @@ const POSSIBLY_POSTED = new Set([
20
45
  */
21
46
  export function sendSlack(input) {
22
47
  return Effect.gen(function* () {
23
- const payload = { markdown_text: input.finalText };
48
+ const payload = slackPayload(input.finalText, input.plainText, input.buttons);
24
49
  const thread = input.replyTo ??
25
50
  (typeof input.threadId === "string" && SLACK_TS.test(input.threadId) ? input.threadId : null);
26
51
  const result = yield* input.transport
@@ -92,6 +117,8 @@ export const slackProvider = {
92
117
  finalText: renderSlack(markdown, attribution, separator),
93
118
  plainText: attribution === "" ? markdown : `${markdown}${separator}${attribution}`,
94
119
  }),
95
- payload: (finalText) => ({ markdown_text: finalText }),
120
+ payload: (finalText, buttons) => slackPayload(finalText, finalText, buttons),
121
+ // Each row is an actions block; labels and rows fit within what the schema allows.
122
+ refuseButtons: () => undefined,
96
123
  send: sendSlack,
97
124
  };
@@ -1,5 +1,6 @@
1
1
  import { type TelegramPreviewContext } from "../../../telegram.js";
2
2
  import { Effect } from "effect";
3
+ import type { ChatButtonRows } from "../../../chat.js";
3
4
  import type { ConnectionTransport } from "../../../connection.js";
4
5
  import type { Destination } from "../resolve.js";
5
6
  import { type ChatProvider, type ProviderOutcome } from "./provider.js";
@@ -9,6 +10,8 @@ export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
9
10
  * attribution, as for a reply the agent sends after a member approved it, there is no footer.
10
11
  */
11
12
  export declare function renderTelegram(markdown: string, attribution: string, separator?: string): string;
13
+ /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
14
+ export declare function telegramKeyboard(rows: ChatButtonRows): Readonly<Record<string, unknown>>;
12
15
  interface TelegramSend {
13
16
  readonly transport: ConnectionTransport["Service"];
14
17
  readonly connection: string;
@@ -23,6 +26,8 @@ interface TelegramSend {
23
26
  readonly threadId?: string | null;
24
27
  readonly link_preview_options?: Readonly<Record<string, unknown>>;
25
28
  readonly disable_web_page_preview?: boolean;
29
+ /** The message's buttons, kept on the plain retry. */
30
+ readonly replyMarkup?: Readonly<Record<string, unknown>>;
26
31
  }
27
32
  /** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
28
33
  * Never retry an unknown outcome; never chunk, truncate or invoke an agent.
@@ -13,19 +13,29 @@ export function renderTelegram(markdown, attribution, separator = "\n\n") {
13
13
  ? converter.fromMarkdown(markdown)
14
14
  : `${converter.fromMarkdown(markdown)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
15
15
  }
16
+ /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
17
+ export function telegramKeyboard(rows) {
18
+ return {
19
+ inline_keyboard: rows.map((row) => row.map((button) => "url" in button
20
+ ? { text: button.text, url: button.url }
21
+ : { text: button.text, callback_data: `ws:${button.token}` })),
22
+ };
23
+ }
16
24
  /** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
17
25
  * Never retry an unknown outcome; never chunk, truncate or invoke an agent.
18
26
  */
19
27
  export function sendTelegram(input) {
20
28
  return Effect.gen(function* () {
29
+ const markup = input.replyMarkup === undefined ? {} : { reply_markup: input.replyMarkup };
21
30
  const formatted = yield* attemptTelegram(input, {
22
31
  text: input.finalText,
23
32
  parse_mode: "MarkdownV2",
33
+ ...markup,
24
34
  });
25
35
  if (!formatted.formattingRefused) {
26
36
  return formatted;
27
37
  }
28
- const plain = yield* attemptTelegram(input, { text: input.plainText });
38
+ const plain = yield* attemptTelegram(input, { text: input.plainText, ...markup });
29
39
  return {
30
40
  ...plain,
31
41
  cause: plain.cause === undefined
@@ -135,7 +145,13 @@ export const telegramProvider = {
135
145
  finalText: renderTelegram(markdown, attribution, separator),
136
146
  plainText: attribution === "" ? markdown : `${markdown}${separator}${attribution}`,
137
147
  }),
138
- payload: (finalText) => ({ text: finalText, parse_mode: "MarkdownV2" }),
148
+ payload: (finalText, buttons) => ({
149
+ text: finalText,
150
+ parse_mode: "MarkdownV2",
151
+ ...(buttons === undefined ? {} : { reply_markup: telegramKeyboard(buttons) }),
152
+ }),
153
+ // An inline keyboard takes every row the schema allows; a token fits its callback data.
154
+ refuseButtons: () => undefined,
139
155
  send: (input) => sendTelegram({
140
156
  transport: input.transport,
141
157
  connection: input.connection,
@@ -150,5 +166,6 @@ export const telegramProvider = {
150
166
  plainText: input.plainText,
151
167
  replyTo: input.replyTo,
152
168
  ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
169
+ ...(input.buttons === undefined ? {} : { replyMarkup: telegramKeyboard(input.buttons) }),
153
170
  }),
154
171
  };
@@ -1,5 +1,18 @@
1
1
  import { Effect } from "effect";
2
+ import type { ChatButtonRows } from "../../../chat.js";
2
3
  import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
4
+ /** The most characters of an interactive message's body, under which WhatsApp shows buttons. */
5
+ export declare const WHATSAPP_INTERACTIVE_BODY_LIMIT = 1024;
6
+ /**
7
+ * Why WhatsApp cannot show these buttons under the text, or undefined when it can: up to three
8
+ * workspace buttons with distinct labels, or one link, under a body of at most 1,024 characters.
9
+ */
10
+ export declare function refuseWhatsAppButtons(rows: ChatButtonRows, finalText: string): string | undefined;
11
+ /**
12
+ * A message with buttons as WhatsApp shows it: an interactive message, its body the text, with one
13
+ * call-to-action link or up to three reply buttons, each workspace button's id `ws:<token>`.
14
+ */
15
+ export declare function whatsappInteractive(finalText: string, rows: ChatButtonRows): Readonly<Record<string, unknown>>;
3
16
  /**
4
17
  * One text message from the workspace's number, `POST /phone/messages` on the connection's
5
18
  * `graph` API, never retried. A Graph refusal with an error code, such as 131047 outside the
@@ -5,6 +5,66 @@ import { REFUSALS, WAMID } from "./whatsapp-refusals.js";
5
5
  import { record, transportFailure, } from "./provider.js";
6
6
  /** A WhatsApp id: the member's number, digits only. */
7
7
  const WA_ID = /^[1-9][0-9]{5,19}$/;
8
+ /** The most characters of an interactive message's body, under which WhatsApp shows buttons. */
9
+ export const WHATSAPP_INTERACTIVE_BODY_LIMIT = 1024;
10
+ /** The most reply buttons one WhatsApp message shows, and the most characters of each label. */
11
+ const WHATSAPP_REPLY_BUTTONS = 3;
12
+ const WHATSAPP_BUTTON_LABEL = 20;
13
+ /**
14
+ * Why WhatsApp cannot show these buttons under the text, or undefined when it can: up to three
15
+ * workspace buttons with distinct labels, or one link, under a body of at most 1,024 characters.
16
+ */
17
+ export function refuseWhatsAppButtons(rows, finalText) {
18
+ const buttons = rows.flat();
19
+ const links = buttons.filter((button) => "url" in button);
20
+ const labels = buttons.map((button) => button.text);
21
+ if (finalText.length > WHATSAPP_INTERACTIVE_BODY_LIMIT) {
22
+ return `WhatsApp shows buttons under at most ${WHATSAPP_INTERACTIVE_BODY_LIMIT} characters.`;
23
+ }
24
+ if (links.length > 0 && links.length !== buttons.length) {
25
+ return "WhatsApp shows one link or workspace buttons under a message, not both.";
26
+ }
27
+ if (links.length > 1) {
28
+ return "WhatsApp shows one link under a message.";
29
+ }
30
+ if (buttons.length > WHATSAPP_REPLY_BUTTONS) {
31
+ return `WhatsApp shows at most ${WHATSAPP_REPLY_BUTTONS} buttons under a message.`;
32
+ }
33
+ if (labels.some((label) => [...label].length > WHATSAPP_BUTTON_LABEL)) {
34
+ return `WhatsApp shows at most ${WHATSAPP_BUTTON_LABEL} characters of a button's label.`;
35
+ }
36
+ if (new Set(labels).size !== labels.length) {
37
+ return "WhatsApp needs every button under a message to have its own label.";
38
+ }
39
+ return undefined;
40
+ }
41
+ /**
42
+ * A message with buttons as WhatsApp shows it: an interactive message, its body the text, with one
43
+ * call-to-action link or up to three reply buttons, each workspace button's id `ws:<token>`.
44
+ */
45
+ export function whatsappInteractive(finalText, rows) {
46
+ const buttons = rows.flat();
47
+ const [link] = buttons.filter((button) => "url" in button);
48
+ return {
49
+ type: "interactive",
50
+ interactive: link !== undefined && "url" in link
51
+ ? {
52
+ type: "cta_url",
53
+ body: { text: finalText },
54
+ action: { name: "cta_url", parameters: { display_text: link.text, url: link.url } },
55
+ }
56
+ : {
57
+ type: "button",
58
+ body: { text: finalText },
59
+ action: {
60
+ buttons: buttons.map((button) => ({
61
+ type: "reply",
62
+ reply: { id: "token" in button ? `ws:${button.token}` : "", title: button.text },
63
+ })),
64
+ },
65
+ },
66
+ };
67
+ }
8
68
  /**
9
69
  * One text message from the workspace's number, `POST /phone/messages` on the connection's
10
70
  * `graph` API, never retried. A Graph refusal with an error code, such as 131047 outside the
@@ -13,10 +73,10 @@ const WA_ID = /^[1-9][0-9]{5,19}$/;
13
73
  */
14
74
  export function sendWhatsApp(input) {
15
75
  return Effect.gen(function* () {
16
- const payload = input.payload ?? {
17
- type: "text",
18
- text: { body: input.finalText, preview_url: false },
19
- };
76
+ const payload = input.payload ??
77
+ (input.buttons === undefined
78
+ ? { type: "text", text: { body: input.finalText, preview_url: false } }
79
+ : whatsappInteractive(input.finalText, input.buttons));
20
80
  const result = yield* input.transport
21
81
  .request({
22
82
  connection: input.connection,
@@ -91,7 +151,10 @@ export const whatsappProvider = {
91
151
  finalText: renderWhatsApp(text, attribution, separator),
92
152
  plainText: attribution === "" ? text : `${text}${separator}${attribution}`,
93
153
  }),
94
- payload: (finalText) => ({ type: "text", text: { body: finalText, preview_url: false } }),
154
+ payload: (finalText, buttons) => buttons === undefined
155
+ ? { type: "text", text: { body: finalText, preview_url: false } }
156
+ : whatsappInteractive(finalText, buttons),
157
+ refuseButtons: refuseWhatsAppButtons,
95
158
  send: sendWhatsApp,
96
159
  template: whatsappTemplate,
97
160
  };
@@ -13,6 +13,7 @@ import { currentCaller } from "../caller-context.js";
13
13
  import { requireRuntimeOperation, runtimeManifest } from "./runtime-policy.js";
14
14
  import { CONFIRMATION_PREVIEW_METHOD, previewLocale, withoutConfirmation } from "./confirmation.js";
15
15
  import { consumeChatEnvelope, CurrentChatCall } from "../chat/envelope.js";
16
+ import { RUNTIME_SOURCE_PROVIDERS } from "../../runtime-source.js";
16
17
  import { ChatList, ChatHistory, ChatPostWire, RuntimeChatPostWire } from "../chat/schemas.js";
17
18
  import { ChatPostResult } from "../../chat.js";
18
19
  import { chatKind, listedChatProviders } from "../chat/providers/index.js";
@@ -672,9 +673,10 @@ function dispatch(server, message, request) {
672
673
  capabilities: {
673
674
  tools: {},
674
675
  resources: {},
675
- // The agent runtime learns that tool calls accept its chat source without listing
676
- // the catalog. The `me` tool keeps its `_meta` marker for older agents.
677
- experimental: { [RUNTIME_SOURCE_META]: {} },
676
+ // The agent runtime learns that tool calls accept its chat source, and from which
677
+ // channels, without listing the catalog. The `me` tool keeps its `_meta` marker for
678
+ // older agents.
679
+ experimental: { [RUNTIME_SOURCE_META]: { providers: [...RUNTIME_SOURCE_PROVIDERS] } },
678
680
  },
679
681
  serverInfo: {
680
682
  name: "segmentstream-ontology",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.144.0",
3
+ "version": "0.146.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",