@vellumai/assistant 0.10.3-dev.202606260109.8a3d17b → 0.10.3-dev.202606260318.2a238d5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.3-dev.202606260109.8a3d17b",
3
+ "version": "0.10.3-dev.202606260318.2a238d5",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -81,8 +81,8 @@ mock.module("../runtime/gateway-client.js", () => ({
81
81
  }));
82
82
 
83
83
  mock.module("../memory/conversation-crud.js", () => ({
84
- setConversationProcessingStartedAt: () => {},
85
- isConversationProcessing: () => false,
84
+ setConversationProcessingStartedAt: () => {},
85
+ isConversationProcessing: () => false,
86
86
  setConversationOriginChannelIfUnset: () => {},
87
87
  updateConversationContextWindow: () => {},
88
88
  deleteMessageById: () => {},
@@ -240,6 +240,7 @@ describe("channel-reply-delivery", () => {
240
240
  payload: {
241
241
  chatId: "chat-1",
242
242
  text: "Before tool.",
243
+ useBlocks: true,
243
244
  attachments: undefined,
244
245
  assistantId: "assistant-1",
245
246
  },
@@ -249,6 +250,7 @@ describe("channel-reply-delivery", () => {
249
250
  payload: {
250
251
  chatId: "chat-1",
251
252
  text: "After tool.",
253
+ useBlocks: true,
252
254
  attachments,
253
255
  assistantId: "assistant-1",
254
256
  },
@@ -307,12 +309,14 @@ describe("channel-reply-delivery", () => {
307
309
  expect(deliveryCalls[0].payload).toEqual({
308
310
  chatId: "chat-3",
309
311
  text: "Before tool.",
312
+ useBlocks: true,
310
313
  attachments: undefined,
311
314
  assistantId: "assistant-2",
312
315
  });
313
316
  expect(deliveryCalls[1].payload).toEqual({
314
317
  chatId: "chat-3",
315
318
  text: "After tool.",
319
+ useBlocks: true,
316
320
  attachments: [
317
321
  {
318
322
  id: "att-2",
@@ -1,9 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
 
3
- import {
4
- isSlackCallbackUrl,
5
- textToSlackBlocks,
6
- } from "../runtime/slack-block-formatting.js";
3
+ import { textToSlackBlocks } from "../runtime/slack-block-formatting.js";
7
4
 
8
5
  describe("textToSlackBlocks", () => {
9
6
  test("returns undefined for empty text", () => {
@@ -174,37 +171,3 @@ describe("textToSlackBlocks", () => {
174
171
  expect(section.text.text).toContain("|");
175
172
  });
176
173
  });
177
-
178
- describe("isSlackCallbackUrl", () => {
179
- test("returns true for Slack deliver URLs", () => {
180
- expect(
181
- isSlackCallbackUrl(
182
- "http://127.0.0.1:7830/deliver/slack?threadTs=123&channel=C456",
183
- ),
184
- ).toBe(true);
185
- });
186
-
187
- test("returns true for bare Slack deliver path", () => {
188
- expect(isSlackCallbackUrl("http://localhost:7830/deliver/slack")).toBe(
189
- true,
190
- );
191
- });
192
-
193
- test("returns false for non-Slack URLs", () => {
194
- expect(isSlackCallbackUrl("http://localhost:7830/deliver/telegram")).toBe(
195
- false,
196
- );
197
- });
198
-
199
- test("returns false for invalid URLs", () => {
200
- expect(isSlackCallbackUrl("not-a-url")).toBe(false);
201
- });
202
-
203
- test("returns false for managed outbound URLs", () => {
204
- expect(
205
- isSlackCallbackUrl(
206
- "http://localhost:7830/v1/internal/managed-gateway/outbound-send/?route_id=r1&assistant_id=a1&source_channel=phone",
207
- ),
208
- ).toBe(false);
209
- });
210
- });
@@ -0,0 +1,45 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { channelForCallback } from "../callback-routing.js";
4
+
5
+ describe("channelForCallback", () => {
6
+ test("resolves each direct-delivery channel from its callback URL", () => {
7
+ expect(channelForCallback("http://gw/deliver/slack?threadTs=1")).toBe(
8
+ "slack",
9
+ );
10
+ expect(channelForCallback("http://gw/deliver/telegram")).toBe("telegram");
11
+ expect(channelForCallback("http://gw/deliver/whatsapp")).toBe("whatsapp");
12
+ expect(channelForCallback("http://gw/deliver/a2a?taskId=t1")).toBe("a2a");
13
+ });
14
+
15
+ test("returns undefined for channels not delivered directly", () => {
16
+ expect(channelForCallback("http://gw/deliver/discord")).toBeUndefined();
17
+ expect(channelForCallback("http://gw/deliver/phone")).toBeUndefined();
18
+ });
19
+
20
+ test("returns undefined for non-delivery paths", () => {
21
+ expect(channelForCallback("http://gw/v1/messages")).toBeUndefined();
22
+ expect(
23
+ channelForCallback(
24
+ "http://gw/v1/internal/managed-gateway/outbound-send/?route_id=r1",
25
+ ),
26
+ ).toBeUndefined();
27
+ });
28
+
29
+ test("returns undefined for unparseable input", () => {
30
+ expect(channelForCallback("not-a-url")).toBeUndefined();
31
+ });
32
+
33
+ test("resolves base-less callback paths", () => {
34
+ expect(channelForCallback("/deliver/slack?threadTs=1")).toBe("slack");
35
+ });
36
+
37
+ test("resolves relative guardian-style /deliver/<channel> callbacks", () => {
38
+ // resolveDeliverCallbackUrlForChannel() emits these relative URLs for
39
+ // off-channel guardian approvals/denials and timer-driven expiry notices;
40
+ // they must route as direct delivery, not fall through to the HTTP proxy.
41
+ expect(channelForCallback("/deliver/slack")).toBe("slack");
42
+ expect(channelForCallback("/deliver/telegram")).toBe("telegram");
43
+ expect(channelForCallback("/deliver/whatsapp")).toBe("whatsapp");
44
+ });
45
+ });
@@ -0,0 +1,195 @@
1
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
2
+
3
+ import type { ChannelReplyPayload } from "@vellumai/gateway-client";
4
+
5
+ // Replace each channel's provider-API send layer with spies so the dispatcher's
6
+ // routing and sub-operation selection can be asserted without network calls.
7
+ const slack = {
8
+ sendSlackReply: mock((..._args: unknown[]) =>
9
+ Promise.resolve({ ts: "slack-ts" }),
10
+ ),
11
+ sendSlackReaction: mock((..._args: unknown[]) => Promise.resolve()),
12
+ sendSlackTypingIndicator: mock((..._args: unknown[]) =>
13
+ Promise.resolve("typing-ts"),
14
+ ),
15
+ sendSlackAssistantThreadStatus: mock((..._args: unknown[]) =>
16
+ Promise.resolve(),
17
+ ),
18
+ sendSlackAttachments: mock((..._args: unknown[]) =>
19
+ Promise.resolve({ allFailed: false, failureCount: 0 }),
20
+ ),
21
+ };
22
+ const telegram = {
23
+ sendTelegramReply: mock((..._args: unknown[]) => Promise.resolve()),
24
+ sendTelegramTypingIndicator: mock((..._args: unknown[]) => Promise.resolve()),
25
+ sendTelegramAttachments: mock((..._args: unknown[]) =>
26
+ Promise.resolve({ allFailed: false, failureCount: 0 }),
27
+ ),
28
+ };
29
+ const whatsapp = {
30
+ sendWhatsAppReply: mock((..._args: unknown[]) => Promise.resolve()),
31
+ sendWhatsAppAttachments: mock((..._args: unknown[]) =>
32
+ Promise.resolve({ allFailed: false, failureCount: 0 }),
33
+ ),
34
+ };
35
+ const a2a = {
36
+ deliverA2AReply: mock((..._args: unknown[]) => Promise.resolve({ ok: true })),
37
+ };
38
+
39
+ mock.module("../slack/send.js", () => slack);
40
+ mock.module("../telegram-bot/send.js", () => telegram);
41
+ mock.module("../whatsapp/send.js", () => whatsapp);
42
+ mock.module("../a2a/deliver.js", () => a2a);
43
+ mock.module("../../../util/logger.js", () => ({
44
+ getLogger: () => ({ debug() {}, info() {}, warn() {}, error() {} }),
45
+ }));
46
+
47
+ const { deliverDirect, isDirectDelivery, getTransportForCallback } =
48
+ await import("../index.js");
49
+
50
+ const BASE = "https://gateway.internal";
51
+
52
+ function payload(
53
+ overrides: Partial<ChannelReplyPayload> = {},
54
+ ): ChannelReplyPayload {
55
+ return { chatId: "C1", ...overrides };
56
+ }
57
+
58
+ beforeEach(() => {
59
+ for (const group of [slack, telegram, whatsapp, a2a]) {
60
+ for (const spy of Object.values(group)) spy.mockClear();
61
+ }
62
+ });
63
+
64
+ describe("routing", () => {
65
+ test("resolves each channel's callback path to its transport", () => {
66
+ expect(
67
+ getTransportForCallback(`${BASE}/deliver/slack?threadTs=1`)?.channel,
68
+ ).toBe("slack");
69
+ expect(getTransportForCallback(`${BASE}/deliver/telegram`)?.channel).toBe(
70
+ "telegram",
71
+ );
72
+ expect(getTransportForCallback(`${BASE}/deliver/whatsapp`)?.channel).toBe(
73
+ "whatsapp",
74
+ );
75
+ expect(
76
+ getTransportForCallback(`${BASE}/deliver/a2a?taskId=t1`)?.channel,
77
+ ).toBe("a2a");
78
+ });
79
+
80
+ test("isDirectDelivery is true for owned paths, false otherwise", () => {
81
+ expect(isDirectDelivery(`${BASE}/deliver/slack`)).toBe(true);
82
+ expect(isDirectDelivery(`${BASE}/deliver/a2a?taskId=t1`)).toBe(true);
83
+ expect(isDirectDelivery(`${BASE}/deliver/discord`)).toBe(false);
84
+ expect(isDirectDelivery(`${BASE}/v1/messages`)).toBe(false);
85
+ expect(
86
+ isDirectDelivery(
87
+ `${BASE}/v1/internal/managed-gateway/outbound-send/?route_id=r1`,
88
+ ),
89
+ ).toBe(false);
90
+ expect(getTransportForCallback(`${BASE}/deliver/discord`)).toBeUndefined();
91
+ });
92
+ });
93
+
94
+ describe("Slack sub-operation selection", () => {
95
+ test("text routes to sendSlackReply, threading the callback URL's threadTs", async () => {
96
+ await deliverDirect(
97
+ `${BASE}/deliver/slack?threadTs=1700.5`,
98
+ payload({ text: "hi" }),
99
+ );
100
+ expect(slack.sendSlackReply).toHaveBeenCalledTimes(1);
101
+ const opts = slack.sendSlackReply.mock.calls[0][2] as { threadTs?: string };
102
+ expect(opts.threadTs).toBe("1700.5");
103
+ expect(slack.sendSlackReaction).not.toHaveBeenCalled();
104
+ });
105
+
106
+ test("threads a base-less callback URL's threadTs", async () => {
107
+ await deliverDirect(
108
+ `/deliver/slack?threadTs=1700.9`,
109
+ payload({ text: "hi" }),
110
+ );
111
+ expect(slack.sendSlackReply).toHaveBeenCalledTimes(1);
112
+ const opts = slack.sendSlackReply.mock.calls[0][2] as { threadTs?: string };
113
+ expect(opts.threadTs).toBe("1700.9");
114
+ });
115
+
116
+ test("reaction routes to sendSlackReaction, not the text path", async () => {
117
+ await deliverDirect(
118
+ `${BASE}/deliver/slack`,
119
+ payload({
120
+ reaction: {
121
+ action: "add",
122
+ name: "white_check_mark",
123
+ messageTs: "1700.5",
124
+ },
125
+ }),
126
+ );
127
+ expect(slack.sendSlackReaction).toHaveBeenCalledTimes(1);
128
+ expect(slack.sendSlackReply).not.toHaveBeenCalled();
129
+ });
130
+
131
+ test("assistantThreadStatus routes to sendSlackAssistantThreadStatus", async () => {
132
+ await deliverDirect(
133
+ `${BASE}/deliver/slack`,
134
+ payload({
135
+ assistantThreadStatus: {
136
+ channel: "C1",
137
+ threadTs: "1700.5",
138
+ status: "is thinking",
139
+ },
140
+ }),
141
+ );
142
+ expect(slack.sendSlackAssistantThreadStatus).toHaveBeenCalledTimes(1);
143
+ expect(slack.sendSlackReply).not.toHaveBeenCalled();
144
+ });
145
+
146
+ test("typing routes to sendSlackTypingIndicator", async () => {
147
+ await deliverDirect(
148
+ `${BASE}/deliver/slack`,
149
+ payload({ chatAction: "typing" }),
150
+ );
151
+ expect(slack.sendSlackTypingIndicator).toHaveBeenCalledTimes(1);
152
+ expect(slack.sendSlackReply).not.toHaveBeenCalled();
153
+ });
154
+ });
155
+
156
+ describe("capability gating across channels", () => {
157
+ test("a reaction payload to Telegram falls through to deliver (no sendReaction)", async () => {
158
+ await deliverDirect(
159
+ `${BASE}/deliver/telegram`,
160
+ payload({
161
+ text: "hi",
162
+ reaction: { action: "add", name: "x", messageTs: "1" },
163
+ }),
164
+ );
165
+ expect(telegram.sendTelegramReply).toHaveBeenCalledTimes(1);
166
+ });
167
+
168
+ test("typing to Telegram routes to its typing indicator", async () => {
169
+ await deliverDirect(
170
+ `${BASE}/deliver/telegram`,
171
+ payload({ chatAction: "typing" }),
172
+ );
173
+ expect(telegram.sendTelegramTypingIndicator).toHaveBeenCalledTimes(1);
174
+ });
175
+
176
+ test("WhatsApp text routes to sendWhatsAppReply", async () => {
177
+ await deliverDirect(`${BASE}/deliver/whatsapp`, payload({ text: "hi" }));
178
+ expect(whatsapp.sendWhatsAppReply).toHaveBeenCalledTimes(1);
179
+ });
180
+
181
+ test("A2A routes to deliverA2AReply with the callback URL", async () => {
182
+ const url = `${BASE}/deliver/a2a?taskId=t1`;
183
+ await deliverDirect(url, payload({ text: "hi" }));
184
+ expect(a2a.deliverA2AReply).toHaveBeenCalledTimes(1);
185
+ expect(a2a.deliverA2AReply.mock.calls[0][0]).toBe(url);
186
+ });
187
+ });
188
+
189
+ describe("unsupported callback", () => {
190
+ test("throws when no transport owns the callback", async () => {
191
+ await expect(
192
+ deliverDirect(`${BASE}/deliver/discord`, payload({ text: "hi" })),
193
+ ).rejects.toThrow(/unsupported callback/);
194
+ });
195
+ });
@@ -167,6 +167,17 @@ describe("deliverA2AReply", () => {
167
167
  expect(completeWithArtifactsCalls).toHaveLength(0);
168
168
  });
169
169
 
170
+ test("completes task for a base-less (relative) callback URL", async () => {
171
+ const result = await deliverA2AReply("/deliver/a2a?taskId=task-123", {
172
+ chatId: "chat-1",
173
+ text: "Hello",
174
+ });
175
+
176
+ expect(result.ok).toBe(true);
177
+ expect(completeWithArtifactsCalls).toHaveLength(1);
178
+ expect(completeWithArtifactsCalls[0].taskId).toBe("task-123");
179
+ });
180
+
170
181
  test("returns ok: true when payload has no content", async () => {
171
182
  const result = await deliverA2AReply(baseCallbackUrl, {
172
183
  chatId: "chat-1",
@@ -36,7 +36,11 @@ const PUSH_TIMEOUT_MS = 15_000;
36
36
  /** Extract the `taskId` query parameter from a callback URL. */
37
37
  function parseTaskId(callbackUrl: string): string | null {
38
38
  try {
39
- return new URL(callbackUrl).searchParams.get("taskId");
39
+ // Dummy base so base-less callbacks (e.g. `/deliver/a2a?taskId=…`) parse the
40
+ // same as absolute ones — consistent with `callbackContext` in the dispatcher.
41
+ return new URL(callbackUrl, "http://callback.invalid").searchParams.get(
42
+ "taskId",
43
+ );
40
44
  } catch {
41
45
  return null;
42
46
  }
@@ -0,0 +1,10 @@
1
+ import type { ChannelTransport } from "../channel-transport.js";
2
+ import { deliverA2AReply } from "./deliver.js";
3
+
4
+ export const a2aTransport: ChannelTransport = {
5
+ channel: "a2a",
6
+
7
+ async deliver(ctx, payload) {
8
+ return deliverA2AReply(ctx.callbackUrl, payload);
9
+ },
10
+ };
@@ -0,0 +1,48 @@
1
+ import type { ChannelId } from "../../channels/types.js";
2
+
3
+ /**
4
+ * Channels whose outbound replies the assistant delivers directly to the
5
+ * provider API, bypassing the gateway HTTP proxy. Each is reached at the gateway
6
+ * callback path `/deliver/<channel>`.
7
+ *
8
+ * This is the single source of truth for that set and that mapping — shared by
9
+ * the delivery transports (`messaging/providers`) and any caller that needs to
10
+ * resolve a callback URL back to its channel WITHOUT loading the transport
11
+ * implementations (and their provider-API send code). Keep it dependency-light.
12
+ */
13
+ const DIRECT_DELIVERY_CHANNELS = [
14
+ "slack",
15
+ "telegram",
16
+ "whatsapp",
17
+ "a2a",
18
+ ] as const satisfies readonly ChannelId[];
19
+
20
+ export type DirectDeliveryChannel = (typeof DIRECT_DELIVERY_CHANNELS)[number];
21
+
22
+ const CALLBACK_PREFIX = "/deliver/";
23
+
24
+ /**
25
+ * Resolve a gateway callback URL to the direct-delivery channel that owns it, or
26
+ * `undefined` when no channel delivers it directly.
27
+ *
28
+ * Handles both absolute callbacks (gateway webhook replies) and base-less
29
+ * relative ones like `/deliver/slack`, which off-channel guardian flows emit
30
+ * (`resolveDeliverCallbackUrlForChannel`, the guardian expiry sweep). The
31
+ * query-stripped fallback is required, not defensive: without it those relative
32
+ * notices fall through to the HTTP proxy, which cannot `fetch()` a base-less URL.
33
+ */
34
+ export function channelForCallback(
35
+ callbackUrl: string,
36
+ ): DirectDeliveryChannel | undefined {
37
+ let pathname: string;
38
+ try {
39
+ pathname = new URL(callbackUrl).pathname;
40
+ } catch {
41
+ pathname = callbackUrl.split("?", 1)[0];
42
+ }
43
+ if (!pathname.startsWith(CALLBACK_PREFIX)) return undefined;
44
+ const channel = pathname.slice(CALLBACK_PREFIX.length);
45
+ return (DIRECT_DELIVERY_CHANNELS as readonly string[]).includes(channel)
46
+ ? (channel as DirectDeliveryChannel)
47
+ : undefined;
48
+ }
@@ -0,0 +1,55 @@
1
+ import type {
2
+ ChannelDeliveryResult,
3
+ ChannelReplyPayload,
4
+ } from "@vellumai/gateway-client";
5
+
6
+ import type { ChannelId } from "../../channels/types.js";
7
+
8
+ /**
9
+ * Per-channel state carried on the gateway callback URL (e.g. Slack `threadTs`,
10
+ * A2A `taskId`). The dispatcher parses the URL once; each transport reads only
11
+ * the params it needs.
12
+ */
13
+ export interface CallbackContext {
14
+ readonly callbackUrl: string;
15
+ readonly params: Readonly<Record<string, string>>;
16
+ }
17
+
18
+ /**
19
+ * Direct outbound delivery for one channel, wrapping the channel's provider-API
20
+ * send functions behind a uniform surface. Transports are registered statically
21
+ * (delivery runs in non-daemon contexts) and dispatched by channel, resolved
22
+ * from the gateway callback URL via `callback-routing.ts`.
23
+ *
24
+ * The dispatcher routes a payload to the optional sub-operation methods when the
25
+ * matching payload field is set and the method exists; otherwise it calls
26
+ * `deliver`. A transport only implements the sub-operations it supports.
27
+ */
28
+ export interface ChannelTransport {
29
+ /** Canonical source channel id, e.g. `"slack"`. */
30
+ readonly channel: ChannelId;
31
+
32
+ /** Deliver a rendered reply (text / approval / attachments). */
33
+ deliver(
34
+ ctx: CallbackContext,
35
+ payload: ChannelReplyPayload,
36
+ ): Promise<ChannelDeliveryResult>;
37
+
38
+ /** Send a typing indicator. Routed when `payload.chatAction === "typing"`. */
39
+ sendTyping?(
40
+ ctx: CallbackContext,
41
+ payload: ChannelReplyPayload,
42
+ ): Promise<ChannelDeliveryResult>;
43
+
44
+ /** Add an emoji reaction. Routed when `payload.reaction` is set. */
45
+ sendReaction?(
46
+ ctx: CallbackContext,
47
+ payload: ChannelReplyPayload,
48
+ ): Promise<ChannelDeliveryResult>;
49
+
50
+ /** Update an assistant-thread status surface. Routed when `payload.assistantThreadStatus` is set. */
51
+ setThreadStatus?(
52
+ ctx: CallbackContext,
53
+ payload: ChannelReplyPayload,
54
+ ): Promise<ChannelDeliveryResult>;
55
+ }
@@ -1,277 +1,101 @@
1
1
  /**
2
2
  * Direct channel delivery — bypasses the gateway HTTP proxy.
3
3
  *
4
- * Each channel that supports direct delivery registers its callback-URL
5
- * matcher and send logic here. The gateway-client consults
4
+ * Each channel exposes a `ChannelTransport`; the callback-URL → channel mapping
5
+ * lives in `callback-routing.ts`. The gateway-client consults
6
6
  * `isDirectDelivery()` before falling back to the HTTP proxy path.
7
7
  *
8
- * Currently supported: WhatsApp, Telegram, Slack, A2A.
8
+ * Supported: Slack, Telegram, WhatsApp, A2A.
9
9
  */
10
10
 
11
11
  import type {
12
12
  ChannelDeliveryResult,
13
13
  ChannelReplyPayload,
14
14
  } from "@vellumai/gateway-client";
15
- import { ChannelDeliveryError } from "@vellumai/gateway-client/http-delivery";
16
15
 
17
- import { getLogger } from "../../util/logger.js";
18
- import { deliverA2AReply } from "./a2a/deliver.js";
19
- import {
20
- sendSlackAssistantThreadStatus,
21
- sendSlackAttachments,
22
- sendSlackReaction,
23
- sendSlackReply,
24
- sendSlackTypingIndicator,
25
- } from "./slack/send.js";
26
- import {
27
- sendTelegramAttachments,
28
- sendTelegramReply,
29
- sendTelegramTypingIndicator,
30
- } from "./telegram-bot/send.js";
31
- import { sendWhatsAppAttachments, sendWhatsAppReply } from "./whatsapp/send.js";
16
+ import { a2aTransport } from "./a2a/transport.js";
17
+ import type { DirectDeliveryChannel } from "./callback-routing.js";
18
+ import { channelForCallback } from "./callback-routing.js";
19
+ import type { CallbackContext, ChannelTransport } from "./channel-transport.js";
20
+ import { slackTransport } from "./slack/transport.js";
21
+ import { telegramTransport } from "./telegram-bot/transport.js";
22
+ import { whatsappTransport } from "./whatsapp/transport.js";
23
+
24
+ // Keyed by `DirectDeliveryChannel` so the type checker enforces that the
25
+ // registered transports cover exactly the channels `callback-routing` resolves:
26
+ // add a channel to that set and this object fails to compile until its transport
27
+ // is registered here (and vice versa). No second list to drift against.
28
+ const TRANSPORTS: Record<DirectDeliveryChannel, ChannelTransport> = {
29
+ slack: slackTransport,
30
+ telegram: telegramTransport,
31
+ whatsapp: whatsappTransport,
32
+ a2a: a2aTransport,
33
+ };
32
34
 
33
- const log = getLogger("direct-delivery");
34
-
35
- // ---------------------------------------------------------------------------
36
- // Callback-URL matchers
37
- // ---------------------------------------------------------------------------
38
-
39
- function matchesPathname(callbackUrl: string, pathname: string): boolean {
40
- try {
41
- return new URL(callbackUrl).pathname === pathname;
42
- } catch {
43
- return callbackUrl.endsWith(pathname);
44
- }
45
- }
46
-
47
- function isWhatsAppCallback(callbackUrl: string): boolean {
48
- return matchesPathname(callbackUrl, "/deliver/whatsapp");
49
- }
50
-
51
- function isTelegramCallback(callbackUrl: string): boolean {
52
- return matchesPathname(callbackUrl, "/deliver/telegram");
53
- }
54
-
55
- function isSlackCallback(callbackUrl: string): boolean {
56
- try {
57
- return new URL(callbackUrl).pathname === "/deliver/slack";
58
- } catch {
59
- return callbackUrl.endsWith("/deliver/slack");
60
- }
61
- }
62
-
63
- function isA2ACallback(callbackUrl: string): boolean {
64
- return matchesPathname(callbackUrl, "/deliver/a2a");
35
+ /**
36
+ * Resolve the transport that owns a gateway callback URL, or `undefined` when
37
+ * no channel delivers it directly.
38
+ */
39
+ export function getTransportForCallback(
40
+ callbackUrl: string,
41
+ ): ChannelTransport | undefined {
42
+ const channel = channelForCallback(callbackUrl);
43
+ return channel ? TRANSPORTS[channel] : undefined;
65
44
  }
66
45
 
67
- function parseSlackCallbackParams(callbackUrl: string): {
68
- channel?: string;
69
- threadTs?: string;
70
- messageTs?: string;
71
- } {
46
+ function callbackContext(callbackUrl: string): CallbackContext {
47
+ const params: Record<string, string> = {};
72
48
  try {
73
- const url = new URL(callbackUrl);
74
- return {
75
- channel: url.searchParams.get("channel") ?? undefined,
76
- threadTs: url.searchParams.get("threadTs") ?? undefined,
77
- messageTs: url.searchParams.get("messageTs") ?? undefined,
78
- };
79
- } catch {
80
- return {};
81
- }
82
- }
83
-
84
- // ---------------------------------------------------------------------------
85
- // Per-channel direct delivery
86
- // ---------------------------------------------------------------------------
87
-
88
- async function deliverWhatsApp(
89
- payload: ChannelReplyPayload,
90
- ): Promise<ChannelDeliveryResult> {
91
- const { chatId, text, attachments, approval } = payload;
92
-
93
- if (text) {
94
- await sendWhatsAppReply(chatId, text, approval);
95
- } else if (approval) {
96
- await sendWhatsAppReply(
97
- chatId,
98
- approval.plainTextFallback || "Approval required",
99
- approval,
100
- );
101
- }
102
-
103
- if (attachments && attachments.length > 0) {
104
- const result = await sendWhatsAppAttachments(chatId, attachments);
105
- if (result.allFailed && !text) {
106
- throw new ChannelDeliveryError(
107
- 502,
108
- `All ${result.failureCount} attachments failed to deliver`,
109
- );
110
- }
111
- }
112
-
113
- log.info({ chatId, hasText: !!text }, "WhatsApp reply delivered (direct)");
114
- return { ok: true };
115
- }
116
-
117
- async function deliverTelegram(
118
- payload: ChannelReplyPayload,
119
- ): Promise<ChannelDeliveryResult> {
120
- const { chatId, text, attachments, approval, chatAction } = payload;
121
-
122
- if (chatAction === "typing") {
123
- await sendTelegramTypingIndicator(chatId);
124
- log.debug({ chatId }, "Telegram typing indicator delivered (direct)");
125
- return { ok: true };
126
- }
127
-
128
- if (text) {
129
- await sendTelegramReply(chatId, text, approval);
130
- } else if (approval) {
131
- await sendTelegramReply(
132
- chatId,
133
- approval.plainTextFallback || "Approval required",
134
- approval,
135
- );
136
- }
137
-
138
- if (attachments && attachments.length > 0) {
139
- const result = await sendTelegramAttachments(chatId, attachments);
140
- if (result.allFailed && !text) {
141
- throw new ChannelDeliveryError(
142
- 502,
143
- `All ${result.failureCount} attachments failed to deliver`,
144
- );
145
- }
146
- }
147
-
148
- log.info({ chatId, hasText: !!text }, "Telegram reply delivered (direct)");
149
- return { ok: true };
150
- }
151
-
152
- async function deliverSlack(
153
- callbackUrl: string,
154
- payload: ChannelReplyPayload,
155
- ): Promise<ChannelDeliveryResult> {
156
- const { chatId, text, attachments, chatAction, blocks } = payload;
157
- const params = parseSlackCallbackParams(callbackUrl);
158
- const threadTs = params.threadTs;
159
-
160
- // Emoji reaction
161
- if (payload.reaction) {
162
- await sendSlackReaction(
163
- chatId,
164
- payload.reaction.name,
165
- payload.reaction.messageTs,
166
- payload.reaction.action,
167
- );
168
- return { ok: true };
169
- }
170
-
171
- // Assistants API thread status
172
- if (payload.assistantThreadStatus) {
173
- const {
174
- channel,
175
- threadTs: statusThreadTs,
176
- status,
177
- loadingMessages,
178
- } = payload.assistantThreadStatus;
179
- await sendSlackAssistantThreadStatus(
180
- channel,
181
- statusThreadTs,
182
- status,
183
- loadingMessages,
184
- );
185
- return { ok: true };
186
- }
187
-
188
- // Typing indicator
189
- if (chatAction === "typing") {
190
- const placeholderTs = await sendSlackTypingIndicator(chatId, threadTs);
191
- log.debug({ chatId }, "Slack typing indicator delivered (direct)");
192
- return { ok: true, ts: placeholderTs };
193
- }
194
-
195
- // Text + blocks delivery
196
- let sentTs: string | undefined;
197
- if (text) {
198
- const result = await sendSlackReply(chatId, text, {
199
- threadTs,
200
- blocks,
201
- approval: payload.approval,
202
- useBlocks: payload.useBlocks,
203
- ephemeral: payload.ephemeral,
204
- user: payload.user,
205
- messageTs: payload.messageTs,
206
- });
207
- sentTs = result.ts;
208
- } else if (payload.approval) {
209
- const result = await sendSlackReply(
210
- chatId,
211
- payload.approval.plainTextFallback || "Approval required",
212
- {
213
- threadTs,
214
- approval: payload.approval,
215
- },
216
- );
217
- sentTs = result.ts;
218
- }
219
-
220
- // Attachments
221
- if (attachments && attachments.length > 0) {
222
- const result = await sendSlackAttachments(chatId, attachments, threadTs);
223
- if (result.allFailed && !text) {
224
- throw new ChannelDeliveryError(
225
- 502,
226
- `All ${result.failureCount} attachments failed to deliver`,
227
- );
49
+ // Resolve against a dummy base so base-less callbacks (e.g.
50
+ // `/deliver/slack?threadTs=…`) still expose their params. `channelForCallback`
51
+ // already routes those as direct delivery, so dispatch must not drop
52
+ // threadTs/taskId for them.
53
+ const url = new URL(callbackUrl, "http://callback.invalid");
54
+ for (const [key, value] of url.searchParams) {
55
+ params[key] = value;
228
56
  }
57
+ } catch {
58
+ // Unparseable callback URL — deliver with no params.
229
59
  }
230
-
231
- log.info({ chatId, hasText: !!text }, "Slack reply delivered (direct)");
232
- return { ok: true, ts: sentTs };
60
+ return { callbackUrl, params };
233
61
  }
234
62
 
235
- // ---------------------------------------------------------------------------
236
- // Public API
237
- // ---------------------------------------------------------------------------
238
-
239
63
  /**
240
- * Returns true when the given callback URL targets a channel whose
241
- * outbound delivery is handled directly by the assistant (no gateway hop).
64
+ * True when the callback URL targets a channel whose outbound delivery the
65
+ * assistant handles directly (no gateway hop).
242
66
  */
243
67
  export function isDirectDelivery(callbackUrl: string): boolean {
244
- return (
245
- isWhatsAppCallback(callbackUrl) ||
246
- isTelegramCallback(callbackUrl) ||
247
- isSlackCallback(callbackUrl) ||
248
- isA2ACallback(callbackUrl)
249
- );
68
+ return getTransportForCallback(callbackUrl) !== undefined;
250
69
  }
251
70
 
252
71
  /**
253
- * Deliver a channel reply directly to the provider API, bypassing the
254
- * gateway HTTP proxy. Callers MUST check `isDirectDelivery()` first.
72
+ * Deliver a channel reply directly to the provider API, bypassing the gateway
73
+ * HTTP proxy. Callers MUST check `isDirectDelivery()` first.
74
+ *
75
+ * Sub-operations (reaction, thread status, typing) route to the transport's
76
+ * optional method when both the payload field and the method are present;
77
+ * otherwise the reply is delivered as text / approval / attachments.
255
78
  */
256
79
  export async function deliverDirect(
257
80
  callbackUrl: string,
258
81
  payload: ChannelReplyPayload,
259
82
  ): Promise<ChannelDeliveryResult> {
260
- if (isWhatsAppCallback(callbackUrl)) {
261
- return deliverWhatsApp(payload);
83
+ const transport = getTransportForCallback(callbackUrl);
84
+ if (!transport) {
85
+ throw new Error(
86
+ `deliverDirect called for unsupported callback: ${callbackUrl}`,
87
+ );
262
88
  }
263
- if (isTelegramCallback(callbackUrl)) {
264
- return deliverTelegram(payload);
89
+
90
+ const ctx = callbackContext(callbackUrl);
91
+ if (payload.reaction && transport.sendReaction) {
92
+ return transport.sendReaction(ctx, payload);
265
93
  }
266
- if (isSlackCallback(callbackUrl)) {
267
- return deliverSlack(callbackUrl, payload);
94
+ if (payload.assistantThreadStatus && transport.setThreadStatus) {
95
+ return transport.setThreadStatus(ctx, payload);
268
96
  }
269
- if (isA2ACallback(callbackUrl)) {
270
- return deliverA2AReply(callbackUrl, payload);
97
+ if (payload.chatAction === "typing" && transport.sendTyping) {
98
+ return transport.sendTyping(ctx, payload);
271
99
  }
272
-
273
- // Defensive — isDirectDelivery should have returned false.
274
- throw new Error(
275
- `deliverDirect called for unsupported callback: ${callbackUrl}`,
276
- );
100
+ return transport.deliver(ctx, payload);
277
101
  }
@@ -0,0 +1,92 @@
1
+ import { ChannelDeliveryError } from "@vellumai/gateway-client/http-delivery";
2
+
3
+ import { getLogger } from "../../../util/logger.js";
4
+ import type { ChannelTransport } from "../channel-transport.js";
5
+ import {
6
+ sendSlackAssistantThreadStatus,
7
+ sendSlackAttachments,
8
+ sendSlackReaction,
9
+ sendSlackReply,
10
+ sendSlackTypingIndicator,
11
+ } from "./send.js";
12
+
13
+ const log = getLogger("slack-transport");
14
+
15
+ export const slackTransport: ChannelTransport = {
16
+ channel: "slack",
17
+
18
+ async deliver(ctx, payload) {
19
+ const { chatId, text, attachments, blocks } = payload;
20
+ const threadTs = ctx.params.threadTs;
21
+
22
+ let sentTs: string | undefined;
23
+ if (text) {
24
+ const result = await sendSlackReply(chatId, text, {
25
+ threadTs,
26
+ blocks,
27
+ approval: payload.approval,
28
+ useBlocks: payload.useBlocks,
29
+ ephemeral: payload.ephemeral,
30
+ user: payload.user,
31
+ messageTs: payload.messageTs,
32
+ });
33
+ sentTs = result.ts;
34
+ } else if (payload.approval) {
35
+ const result = await sendSlackReply(
36
+ chatId,
37
+ payload.approval.plainTextFallback || "Approval required",
38
+ { threadTs, approval: payload.approval },
39
+ );
40
+ sentTs = result.ts;
41
+ }
42
+
43
+ if (attachments && attachments.length > 0) {
44
+ const result = await sendSlackAttachments(chatId, attachments, threadTs);
45
+ if (result.allFailed && !text) {
46
+ throw new ChannelDeliveryError(
47
+ 502,
48
+ `All ${result.failureCount} attachments failed to deliver`,
49
+ );
50
+ }
51
+ }
52
+
53
+ log.info({ chatId, hasText: !!text }, "Slack reply delivered (direct)");
54
+ return { ok: true, ts: sentTs };
55
+ },
56
+
57
+ async sendTyping(ctx, payload) {
58
+ const placeholderTs = await sendSlackTypingIndicator(
59
+ payload.chatId,
60
+ ctx.params.threadTs,
61
+ );
62
+ log.debug(
63
+ { chatId: payload.chatId },
64
+ "Slack typing indicator delivered (direct)",
65
+ );
66
+ return { ok: true, ts: placeholderTs };
67
+ },
68
+
69
+ async sendReaction(_ctx, payload) {
70
+ const reaction = payload.reaction;
71
+ if (!reaction) return { ok: true };
72
+ await sendSlackReaction(
73
+ payload.chatId,
74
+ reaction.name,
75
+ reaction.messageTs,
76
+ reaction.action,
77
+ );
78
+ return { ok: true };
79
+ },
80
+
81
+ async setThreadStatus(_ctx, payload) {
82
+ const status = payload.assistantThreadStatus;
83
+ if (!status) return { ok: true };
84
+ await sendSlackAssistantThreadStatus(
85
+ status.channel,
86
+ status.threadTs,
87
+ status.status,
88
+ status.loadingMessages,
89
+ );
90
+ return { ok: true };
91
+ },
92
+ };
@@ -0,0 +1,51 @@
1
+ import { ChannelDeliveryError } from "@vellumai/gateway-client/http-delivery";
2
+
3
+ import { getLogger } from "../../../util/logger.js";
4
+ import type { ChannelTransport } from "../channel-transport.js";
5
+ import {
6
+ sendTelegramAttachments,
7
+ sendTelegramReply,
8
+ sendTelegramTypingIndicator,
9
+ } from "./send.js";
10
+
11
+ const log = getLogger("telegram-transport");
12
+
13
+ export const telegramTransport: ChannelTransport = {
14
+ channel: "telegram",
15
+
16
+ async deliver(_ctx, payload) {
17
+ const { chatId, text, attachments, approval } = payload;
18
+
19
+ if (text) {
20
+ await sendTelegramReply(chatId, text, approval);
21
+ } else if (approval) {
22
+ await sendTelegramReply(
23
+ chatId,
24
+ approval.plainTextFallback || "Approval required",
25
+ approval,
26
+ );
27
+ }
28
+
29
+ if (attachments && attachments.length > 0) {
30
+ const result = await sendTelegramAttachments(chatId, attachments);
31
+ if (result.allFailed && !text) {
32
+ throw new ChannelDeliveryError(
33
+ 502,
34
+ `All ${result.failureCount} attachments failed to deliver`,
35
+ );
36
+ }
37
+ }
38
+
39
+ log.info({ chatId, hasText: !!text }, "Telegram reply delivered (direct)");
40
+ return { ok: true };
41
+ },
42
+
43
+ async sendTyping(_ctx, payload) {
44
+ await sendTelegramTypingIndicator(payload.chatId);
45
+ log.debug(
46
+ { chatId: payload.chatId },
47
+ "Telegram typing indicator delivered (direct)",
48
+ );
49
+ return { ok: true };
50
+ },
51
+ };
@@ -0,0 +1,38 @@
1
+ import { ChannelDeliveryError } from "@vellumai/gateway-client/http-delivery";
2
+
3
+ import { getLogger } from "../../../util/logger.js";
4
+ import type { ChannelTransport } from "../channel-transport.js";
5
+ import { sendWhatsAppAttachments, sendWhatsAppReply } from "./send.js";
6
+
7
+ const log = getLogger("whatsapp-transport");
8
+
9
+ export const whatsappTransport: ChannelTransport = {
10
+ channel: "whatsapp",
11
+
12
+ async deliver(_ctx, payload) {
13
+ const { chatId, text, attachments, approval } = payload;
14
+
15
+ if (text) {
16
+ await sendWhatsAppReply(chatId, text, approval);
17
+ } else if (approval) {
18
+ await sendWhatsAppReply(
19
+ chatId,
20
+ approval.plainTextFallback || "Approval required",
21
+ approval,
22
+ );
23
+ }
24
+
25
+ if (attachments && attachments.length > 0) {
26
+ const result = await sendWhatsAppAttachments(chatId, attachments);
27
+ if (result.allFailed && !text) {
28
+ throw new ChannelDeliveryError(
29
+ 502,
30
+ `All ${result.failureCount} attachments failed to deliver`,
31
+ );
32
+ }
33
+ }
34
+
35
+ log.info({ chatId, hasText: !!text }, "WhatsApp reply delivered (direct)");
36
+ return { ok: true };
37
+ },
38
+ };
@@ -12,10 +12,6 @@ import { getLogger } from "../util/logger.js";
12
12
  import type { ChannelDeliveryResult } from "./gateway-client.js";
13
13
  import { deliverChannelReply } from "./gateway-client.js";
14
14
  import type { RuntimeAttachmentMetadata } from "./http-types.js";
15
- import {
16
- isSlackCallbackUrl,
17
- textToSlackBlocks,
18
- } from "./slack-block-formatting.js";
19
15
 
20
16
  const log = getLogger("channel-reply-delivery");
21
17
 
@@ -167,8 +163,6 @@ export async function deliverRenderedReplyViaCallback(
167
163
  return;
168
164
  }
169
165
 
170
- const isSlack = isSlackCallbackUrl(callbackUrl);
171
-
172
166
  // Only the first segment uses messageTs for in-place update;
173
167
  // subsequent segments are posted as new messages.
174
168
  let currentMessageTs = messageTs;
@@ -177,13 +171,14 @@ export async function deliverRenderedReplyViaCallback(
177
171
  const isLastSegment = i === deliverableSegments.length - 1;
178
172
  const isFirstSegment = i === startFromSegment;
179
173
  const segmentText = deliverableSegments[i];
180
- const blocks = isSlack ? textToSlackBlocks(segmentText) : undefined;
181
174
  const result: ChannelDeliveryResult = await deliverChannelReply(
182
175
  callbackUrl,
183
176
  {
184
177
  chatId,
185
178
  text: segmentText,
186
- blocks,
179
+ // Ask the channel to render richly; each channel's adapter decides how
180
+ // (Slack → Block Kit). Channels without rich rendering send plain text.
181
+ useBlocks: true,
187
182
  attachments: isLastSegment ? replyAttachments : undefined,
188
183
  assistantId,
189
184
  ephemeral,
@@ -118,21 +118,6 @@ export function textToSlackBlocks(text: string): KnownBlock[] | undefined {
118
118
  return blocks.length > 0 ? blocks : undefined;
119
119
  }
120
120
 
121
- /**
122
- * Detect whether a callback URL points to the gateway's Slack delivery endpoint.
123
- */
124
- export function isSlackCallbackUrl(callbackUrl: string): boolean {
125
- try {
126
- const url = new URL(callbackUrl);
127
- return (
128
- url.pathname === "/deliver/slack" ||
129
- url.pathname.startsWith("/deliver/slack?")
130
- );
131
- } catch {
132
- return false;
133
- }
134
- }
135
-
136
121
  // ---------------------------------------------------------------------------
137
122
  // Internals
138
123
  // ---------------------------------------------------------------------------