@vellumai/assistant 0.10.11-dev.202607222129.31c06e5 → 0.10.11-dev.202607222325.35fc367
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/ARCHITECTURE.md +30 -21
- package/package.json +1 -1
- package/src/__tests__/channel-delivery-store.test.ts +141 -0
- package/src/__tests__/document-preview-surface-schema.test.ts +33 -0
- package/src/__tests__/dynamic-skill-background-guard.test.ts +102 -13
- package/src/__tests__/inline-skill-load-permissions.test.ts +29 -6
- package/src/__tests__/record-persisted-seq-lock-resilience.test.ts +95 -0
- package/src/__tests__/surface-type-registry-guard.test.ts +66 -0
- package/src/__tests__/tool-approval-handler.test.ts +25 -1
- package/src/__tests__/ui-choice-copy-surfaces.test.ts +26 -0
- package/src/api/events/bookmark-created.ts +37 -0
- package/src/api/events/bookmark-deleted.ts +20 -0
- package/src/api/index.ts +17 -0
- package/src/api/surfaces.ts +42 -5
- package/src/daemon/conversation-surfaces.ts +12 -4
- package/src/daemon/message-types/bookmarks.ts +9 -14
- package/src/messaging/providers/telegram-bot/send.test.ts +88 -0
- package/src/messaging/providers/telegram-bot/send.ts +43 -3
- package/src/messaging/providers/telegram-bot/transport.ts +26 -8
- package/src/permissions/checker.ts +18 -21
- package/src/permissions/confirmation-guardian-request.ts +17 -1
- package/src/permissions/prompter.ts +3 -0
- package/src/persistence/conversation-crud.ts +36 -8
- package/src/persistence/delivery-crud.ts +13 -1
- package/src/persistence/external-conversation-store.ts +22 -0
- package/src/runtime/routes/inbound-conversation.ts +19 -3
- package/src/runtime/routes/inbound-message-handler.ts +8 -5
- package/src/tools/permission-checker.ts +42 -9
- package/src/tools/tool-approval-handler.ts +24 -4
|
@@ -28,6 +28,16 @@ mock.module("../tools/registry.js", () => ({
|
|
|
28
28
|
getAllTools: () => [fakeTool],
|
|
29
29
|
}));
|
|
30
30
|
|
|
31
|
+
// Mock the dynamic-skill predicate so isSensitiveTool's skill_load branch is
|
|
32
|
+
// exercised without a real skill catalog: "dynamic-skill" is an inline-command
|
|
33
|
+
// load, anything else is plain.
|
|
34
|
+
mock.module("../permissions/checker.js", () => ({
|
|
35
|
+
isDynamicSkillLoadInvocation: (
|
|
36
|
+
_name: string,
|
|
37
|
+
input: Record<string, unknown>,
|
|
38
|
+
) => input?.skill === "dynamic-skill",
|
|
39
|
+
}));
|
|
40
|
+
|
|
31
41
|
// Capture tool-audit terminal calls so tests can assert on denied/error outcomes
|
|
32
42
|
// the way they previously asserted on emitted lifecycle events.
|
|
33
43
|
const auditCalls = {
|
|
@@ -519,7 +529,7 @@ describe("ToolApprovalHandler / pre-exec gate grant check", () => {
|
|
|
519
529
|
});
|
|
520
530
|
|
|
521
531
|
describe("isSensitiveTool", () => {
|
|
522
|
-
test("sensitivity is a property of the tool and execution target
|
|
532
|
+
test("sensitivity is a property of the tool and execution target", () => {
|
|
523
533
|
// Side-effect tools are sensitive wherever they run.
|
|
524
534
|
expect(isSensitiveTool("bash", "sandbox")).toBe(true);
|
|
525
535
|
expect(isSensitiveTool("file_write", "sandbox")).toBe(true);
|
|
@@ -531,6 +541,20 @@ describe("isSensitiveTool", () => {
|
|
|
531
541
|
expect(isSensitiveTool("ui_update", "host")).toBe(false);
|
|
532
542
|
expect(isSensitiveTool("ui_dismiss", "host")).toBe(false);
|
|
533
543
|
});
|
|
544
|
+
|
|
545
|
+
test("an inline-command (dynamic) skill_load is sensitive; a plain one is not", () => {
|
|
546
|
+
// skill_load is not a side-effect tool, but a load that executes embedded
|
|
547
|
+
// shell at load time must pass through the capability floor — so a
|
|
548
|
+
// non-guardian's dynamic load escalates to the guardian, Full-access-proof.
|
|
549
|
+
expect(
|
|
550
|
+
isSensitiveTool("skill_load", "sandbox", { skill: "dynamic-skill" }),
|
|
551
|
+
).toBe(true);
|
|
552
|
+
expect(
|
|
553
|
+
isSensitiveTool("skill_load", "sandbox", { skill: "plain-skill" }),
|
|
554
|
+
).toBe(false);
|
|
555
|
+
// Without input, skill_load falls back to the name/target rule.
|
|
556
|
+
expect(isSensitiveTool("skill_load", "sandbox")).toBe(false);
|
|
557
|
+
});
|
|
534
558
|
});
|
|
535
559
|
|
|
536
560
|
describe("resolveSensitiveToolDecision / CapabilitySet floor invariant", () => {
|
|
@@ -303,6 +303,32 @@ describe("choice and copy_block surface proxying", () => {
|
|
|
303
303
|
expect(sent).toHaveLength(0);
|
|
304
304
|
});
|
|
305
305
|
|
|
306
|
+
test("ui_show rejects daemon-internal surface types and omits them from the valid list", async () => {
|
|
307
|
+
for (const internalType of ["skill_card", "call_summary"]) {
|
|
308
|
+
const sent: ServerMessage[] = [];
|
|
309
|
+
const ctx = makeContext(sent);
|
|
310
|
+
|
|
311
|
+
const result = await surfaceProxyResolver(ctx, "ui_show", {
|
|
312
|
+
surface_type: internalType,
|
|
313
|
+
data: { anything: true },
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
expect(result.isError).toBe(true);
|
|
317
|
+
expect(result.content).toContain(
|
|
318
|
+
`"${internalType}" is not a valid surface_type`,
|
|
319
|
+
);
|
|
320
|
+
// The advertised valid list must never enumerate the internal types
|
|
321
|
+
// (the leading echo of the rejected input naming it is expected).
|
|
322
|
+
const validList =
|
|
323
|
+
typeof result.content === "string"
|
|
324
|
+
? (result.content.split("Valid surface_type values:")[1] ?? "")
|
|
325
|
+
: "";
|
|
326
|
+
expect(validList).not.toContain("skill_card");
|
|
327
|
+
expect(validList).not.toContain("call_summary");
|
|
328
|
+
expect(sent).toHaveLength(0);
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
|
|
306
332
|
test("ui_show teaching guard accepts copy_block text at the top level of the input", () => {
|
|
307
333
|
const teachingError = uiShowTeachingError({
|
|
308
334
|
surface_type: "copy_block",
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bookmark.created` SSE event.
|
|
3
|
+
*
|
|
4
|
+
* Server → client broadcast emitted after a bookmark is created, so a
|
|
5
|
+
* `BookmarkStore` in any other connected client refreshes in lock-step.
|
|
6
|
+
* Carries the full `BookmarkSummary` for the new bookmark.
|
|
7
|
+
*
|
|
8
|
+
* Canonical wire-contract source. Daemon code imports the type
|
|
9
|
+
* directly from this file; external consumers import via
|
|
10
|
+
* `@vellumai/assistant-api`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
|
|
15
|
+
/** Summary row for a saved message, as surfaced to clients. */
|
|
16
|
+
export const BookmarkSummarySchema = z.object({
|
|
17
|
+
id: z.string(),
|
|
18
|
+
messageId: z.string(),
|
|
19
|
+
conversationId: z.string(),
|
|
20
|
+
conversationTitle: z.string().nullable(),
|
|
21
|
+
messagePreview: z.string(),
|
|
22
|
+
/** "user" | "assistant" — kept free-form so it round-trips raw. */
|
|
23
|
+
messageRole: z.string(),
|
|
24
|
+
/** Unix milliseconds. */
|
|
25
|
+
messageCreatedAt: z.number(),
|
|
26
|
+
/** Unix milliseconds. */
|
|
27
|
+
createdAt: z.number(),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export type BookmarkSummary = z.infer<typeof BookmarkSummarySchema>;
|
|
31
|
+
|
|
32
|
+
export const BookmarkCreatedEventSchema = z.object({
|
|
33
|
+
type: z.literal("bookmark.created"),
|
|
34
|
+
bookmark: BookmarkSummarySchema,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export type BookmarkCreatedEvent = z.infer<typeof BookmarkCreatedEventSchema>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bookmark.deleted` SSE event.
|
|
3
|
+
*
|
|
4
|
+
* Server → client broadcast emitted after a bookmark is removed, so a
|
|
5
|
+
* `BookmarkStore` in any other connected client drops it in lock-step.
|
|
6
|
+
* Identifies the bookmark by the `messageId` it was anchored to.
|
|
7
|
+
*
|
|
8
|
+
* Canonical wire-contract source. Daemon code imports the type
|
|
9
|
+
* directly from this file; external consumers import via
|
|
10
|
+
* `@vellumai/assistant-api`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
|
|
15
|
+
export const BookmarkDeletedEventSchema = z.object({
|
|
16
|
+
type: z.literal("bookmark.deleted"),
|
|
17
|
+
messageId: z.string(),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export type BookmarkDeletedEvent = z.infer<typeof BookmarkDeletedEventSchema>;
|
package/src/api/index.ts
CHANGED
|
@@ -12,6 +12,8 @@ import { AssistantTurnStartEventSchema } from "./events/assistant-turn-start.js"
|
|
|
12
12
|
import { AvatarUpdatedEventSchema } from "./events/avatar-updated.js";
|
|
13
13
|
import { BackgroundToolCompletedEventSchema } from "./events/background-tool-completed.js";
|
|
14
14
|
import { BackgroundToolStartedEventSchema } from "./events/background-tool-started.js";
|
|
15
|
+
import { BookmarkCreatedEventSchema } from "./events/bookmark-created.js";
|
|
16
|
+
import { BookmarkDeletedEventSchema } from "./events/bookmark-deleted.js";
|
|
15
17
|
import { CompactionCircuitClosedEventSchema } from "./events/compaction-circuit-closed.js";
|
|
16
18
|
import { CompactionCircuitOpenEventSchema } from "./events/compaction-circuit-open.js";
|
|
17
19
|
import { ConfirmationRequestEventSchema } from "./events/confirmation-request.js";
|
|
@@ -143,6 +145,16 @@ export {
|
|
|
143
145
|
type BackgroundToolStartedEvent,
|
|
144
146
|
BackgroundToolStartedEventSchema,
|
|
145
147
|
} from "./events/background-tool-started.js";
|
|
148
|
+
export {
|
|
149
|
+
type BookmarkCreatedEvent,
|
|
150
|
+
BookmarkCreatedEventSchema,
|
|
151
|
+
type BookmarkSummary,
|
|
152
|
+
BookmarkSummarySchema,
|
|
153
|
+
} from "./events/bookmark-created.js";
|
|
154
|
+
export {
|
|
155
|
+
type BookmarkDeletedEvent,
|
|
156
|
+
BookmarkDeletedEventSchema,
|
|
157
|
+
} from "./events/bookmark-deleted.js";
|
|
146
158
|
export {
|
|
147
159
|
type CompactionCircuitClosedEvent,
|
|
148
160
|
CompactionCircuitClosedEventSchema,
|
|
@@ -576,6 +588,7 @@ export {
|
|
|
576
588
|
ConfirmationSurfaceDataSchema,
|
|
577
589
|
type CopyBlockSurfaceData,
|
|
578
590
|
CopyBlockSurfaceDataSchema,
|
|
591
|
+
DAEMON_INTERNAL_SURFACE_TYPES,
|
|
579
592
|
type DocumentPreviewSurfaceData,
|
|
580
593
|
DocumentPreviewSurfaceDataSchema,
|
|
581
594
|
type DynamicPagePreview,
|
|
@@ -590,10 +603,12 @@ export {
|
|
|
590
603
|
FormPageSchema,
|
|
591
604
|
type FormSurfaceData,
|
|
592
605
|
FormSurfaceDataSchema,
|
|
606
|
+
isDaemonInternalSurfaceType,
|
|
593
607
|
type ListItem,
|
|
594
608
|
ListItemSchema,
|
|
595
609
|
type ListSurfaceData,
|
|
596
610
|
ListSurfaceDataSchema,
|
|
611
|
+
MODEL_INVOKABLE_SURFACE_TYPES,
|
|
597
612
|
normalizeCopyBlockShowData,
|
|
598
613
|
type OAuthConnectSurfaceData,
|
|
599
614
|
OAuthConnectSurfaceDataSchema,
|
|
@@ -656,6 +671,8 @@ export const AssistantEventSchema = z.discriminatedUnion("type", [
|
|
|
656
671
|
AvatarUpdatedEventSchema,
|
|
657
672
|
BackgroundToolCompletedEventSchema,
|
|
658
673
|
BackgroundToolStartedEventSchema,
|
|
674
|
+
BookmarkCreatedEventSchema,
|
|
675
|
+
BookmarkDeletedEventSchema,
|
|
659
676
|
CompactionCircuitClosedEventSchema,
|
|
660
677
|
CompactionCircuitOpenEventSchema,
|
|
661
678
|
ConfirmationRequestEventSchema,
|
package/src/api/surfaces.ts
CHANGED
|
@@ -372,6 +372,10 @@ export const DocumentPreviewSurfaceDataSchema = z.object({
|
|
|
372
372
|
/** The document's real surfaceId, for focusing the panel. */
|
|
373
373
|
surfaceId: z.string().catch(""),
|
|
374
374
|
subtitle: tolerantString(),
|
|
375
|
+
/** Document body the client renderer displays inline. */
|
|
376
|
+
content: tolerantString(),
|
|
377
|
+
/** MIME type the client renderer uses to choose how to render `content`. */
|
|
378
|
+
mimeType: tolerantString(),
|
|
375
379
|
});
|
|
376
380
|
export type DocumentPreviewSurfaceData = z.infer<
|
|
377
381
|
typeof DocumentPreviewSurfaceDataSchema
|
|
@@ -471,11 +475,40 @@ export const SURFACE_TYPES = [
|
|
|
471
475
|
"document_preview",
|
|
472
476
|
"task_preferences",
|
|
473
477
|
"work_result",
|
|
478
|
+
"skill_card",
|
|
479
|
+
"call_summary",
|
|
474
480
|
] as const;
|
|
475
481
|
|
|
476
482
|
export const SurfaceTypeSchema = z.enum(SURFACE_TYPES);
|
|
477
483
|
export type SurfaceType = z.infer<typeof SurfaceTypeSchema>;
|
|
478
484
|
|
|
485
|
+
/**
|
|
486
|
+
* Surface types the daemon emits and persists directly — the memory
|
|
487
|
+
* retrospective's `skill_card` and a call's `call_summary` — but that the
|
|
488
|
+
* model must never invoke via `ui_show`. They are members of `SurfaceType`
|
|
489
|
+
* so the persistence/restore path can represent them, but they are
|
|
490
|
+
* deliberately absent from the model-facing `ui_show` surface list
|
|
491
|
+
* (`SURFACE_SHAPE_DOCS`), and the `ui_show` resolver rejects them.
|
|
492
|
+
*/
|
|
493
|
+
export const DAEMON_INTERNAL_SURFACE_TYPES = [
|
|
494
|
+
"skill_card",
|
|
495
|
+
"call_summary",
|
|
496
|
+
] as const;
|
|
497
|
+
|
|
498
|
+
const DAEMON_INTERNAL_SURFACE_TYPE_SET = new Set<string>(
|
|
499
|
+
DAEMON_INTERNAL_SURFACE_TYPES,
|
|
500
|
+
);
|
|
501
|
+
|
|
502
|
+
/** Whether `type` is a daemon-internal surface type the model must not `ui_show`. */
|
|
503
|
+
export function isDaemonInternalSurfaceType(type: string): boolean {
|
|
504
|
+
return DAEMON_INTERNAL_SURFACE_TYPE_SET.has(type);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Surface types the model may request via `ui_show` (internal types excluded). */
|
|
508
|
+
export const MODEL_INVOKABLE_SURFACE_TYPES = SURFACE_TYPES.filter(
|
|
509
|
+
(type) => !isDaemonInternalSurfaceType(type),
|
|
510
|
+
);
|
|
511
|
+
|
|
479
512
|
export type SurfaceData =
|
|
480
513
|
| CardSurfaceData
|
|
481
514
|
| ChoiceSurfaceData
|
|
@@ -538,11 +571,15 @@ export function safeParseSurfaceData(
|
|
|
538
571
|
return parse(WorkResultSurfaceDataSchema);
|
|
539
572
|
case "channel_setup":
|
|
540
573
|
case "task_preferences":
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
//
|
|
544
|
-
//
|
|
545
|
-
//
|
|
574
|
+
case "skill_card":
|
|
575
|
+
case "call_summary":
|
|
576
|
+
// Opaque payloads the daemon forwards/persists verbatim: channel_setup
|
|
577
|
+
// is a side-effect command whose data goes to the setup panel,
|
|
578
|
+
// task_preferences renders a fixed grid that reads no data, and
|
|
579
|
+
// skill_card / call_summary are daemon-appended cards whose data shape
|
|
580
|
+
// is owned by their client renderers. There is no canonical shape to
|
|
581
|
+
// parse into, so this is the one deliberate cast in the surface-data
|
|
582
|
+
// parse path.
|
|
546
583
|
return coerceSurfaceDataRecord(data) as SurfaceData;
|
|
547
584
|
default:
|
|
548
585
|
return surfaceType satisfies never;
|
|
@@ -7,10 +7,11 @@ import {
|
|
|
7
7
|
ChoiceSurfaceDataSchema,
|
|
8
8
|
coerceSurfaceDataRecord,
|
|
9
9
|
DynamicPageSurfaceDataSchema,
|
|
10
|
+
isDaemonInternalSurfaceType,
|
|
11
|
+
MODEL_INVOKABLE_SURFACE_TYPES,
|
|
10
12
|
normalizeCopyBlockShowData,
|
|
11
13
|
OAuthConnectSurfaceDataSchema,
|
|
12
14
|
safeParseSurfaceData,
|
|
13
|
-
SURFACE_TYPES,
|
|
14
15
|
SurfaceTypeSchema,
|
|
15
16
|
} from "../api/surfaces.js";
|
|
16
17
|
import {
|
|
@@ -2935,16 +2936,23 @@ export async function surfaceProxyResolver(
|
|
|
2935
2936
|
const surfaceId = uuid();
|
|
2936
2937
|
// Parse, don't cast: an unrecognized surface_type used to be asserted
|
|
2937
2938
|
// into the union and fall through to an opaque passthrough the client
|
|
2938
|
-
// silently dropped. Reject it with the valid values instead.
|
|
2939
|
+
// silently dropped. Reject it with the valid values instead. Daemon-
|
|
2940
|
+
// internal types (skill_card, call_summary) are members of SurfaceType
|
|
2941
|
+
// for persistence but are not model-invokable — reject them here too so
|
|
2942
|
+
// the model can never report an unrenderable surface as shown. Both
|
|
2943
|
+
// messages enumerate only the model-facing set, never the internal types.
|
|
2939
2944
|
const parsedSurfaceType = SurfaceTypeSchema.safeParse(input.surface_type);
|
|
2940
|
-
if (
|
|
2945
|
+
if (
|
|
2946
|
+
!parsedSurfaceType.success ||
|
|
2947
|
+
isDaemonInternalSurfaceType(parsedSurfaceType.data)
|
|
2948
|
+
) {
|
|
2941
2949
|
const got =
|
|
2942
2950
|
typeof input.surface_type === "string" &&
|
|
2943
2951
|
input.surface_type.trim().length > 0
|
|
2944
2952
|
? `"${input.surface_type}" is not a valid surface_type`
|
|
2945
2953
|
: "`surface_type` is missing";
|
|
2946
2954
|
return {
|
|
2947
|
-
content: `Error: ui_show was not displayed — ${got}. Valid surface_type values: ${
|
|
2955
|
+
content: `Error: ui_show was not displayed — ${got}. Valid surface_type values: ${MODEL_INVOKABLE_SURFACE_TYPES.join(", ")}. Resend ui_show with one of these values.`,
|
|
2948
2956
|
isError: true,
|
|
2949
2957
|
};
|
|
2950
2958
|
}
|
|
@@ -1,18 +1,13 @@
|
|
|
1
1
|
// Bookmark events. Surfaced over SSE so a `BookmarkStore` instance in any
|
|
2
2
|
// connected client can stay in sync when another window mutates the list.
|
|
3
|
+
//
|
|
4
|
+
// Server→client events are single-sourced from their canonical `api/events`
|
|
5
|
+
// wire schemas; this file only composes them into the domain union consumed by
|
|
6
|
+
// `message-protocol.ts`.
|
|
3
7
|
|
|
4
|
-
import type {
|
|
8
|
+
import type { BookmarkCreatedEvent } from "../../api/events/bookmark-created.js";
|
|
9
|
+
import type { BookmarkDeletedEvent } from "../../api/events/bookmark-deleted.js";
|
|
5
10
|
|
|
6
|
-
export
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export interface BookmarkDeleted {
|
|
12
|
-
type: "bookmark.deleted";
|
|
13
|
-
messageId: string;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
// --- Domain-level union aliases (consumed by the barrel file) ---
|
|
17
|
-
|
|
18
|
-
export type _BookmarksServerMessages = BookmarkCreated | BookmarkDeleted;
|
|
11
|
+
export type _BookmarksServerMessages =
|
|
12
|
+
| BookmarkCreatedEvent
|
|
13
|
+
| BookmarkDeletedEvent;
|
|
@@ -188,3 +188,91 @@ describe("telegramTransport.deliver routing", () => {
|
|
|
188
188
|
});
|
|
189
189
|
});
|
|
190
190
|
});
|
|
191
|
+
|
|
192
|
+
describe("telegramTransport topic targeting", () => {
|
|
193
|
+
// A `threadId` param on the deliver callback URL identifies the private-chat
|
|
194
|
+
// topic the inbound message arrived in; every outbound send must echo it.
|
|
195
|
+
const topicCtx: CallbackContext = {
|
|
196
|
+
callbackUrl: "/deliver/telegram?threadId=777",
|
|
197
|
+
params: { threadId: "777" },
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
function payload(
|
|
201
|
+
overrides: Partial<ChannelReplyPayload>,
|
|
202
|
+
): ChannelReplyPayload {
|
|
203
|
+
return {
|
|
204
|
+
chatId: "123",
|
|
205
|
+
text: "hello",
|
|
206
|
+
...overrides,
|
|
207
|
+
} as ChannelReplyPayload;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
test("plain replies target the topic from the callback threadId param", async () => {
|
|
211
|
+
await telegramTransport.deliver(topicCtx, payload({ useBlocks: false }));
|
|
212
|
+
|
|
213
|
+
expect(callTelegramBotApiMock).toHaveBeenCalledWith("sendMessage", {
|
|
214
|
+
chat_id: "123",
|
|
215
|
+
text: "hello",
|
|
216
|
+
message_thread_id: 777,
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
test("rich replies target the topic", async () => {
|
|
221
|
+
await telegramTransport.deliver(topicCtx, payload({ useBlocks: true }));
|
|
222
|
+
|
|
223
|
+
expect(callTelegramBotApiMock).toHaveBeenCalledWith("sendRichMessage", {
|
|
224
|
+
chat_id: "123",
|
|
225
|
+
rich_message: { html: "<p>hello</p>", skip_entity_detection: true },
|
|
226
|
+
message_thread_id: 777,
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
test("the plain-text fallback of a rejected rich send stays in the topic", async () => {
|
|
231
|
+
callTelegramBotApiMock.mockImplementationOnce(async () => {
|
|
232
|
+
throw new TelegramNonRetryableError("rejected", "rejected");
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
await telegramTransport.deliver(topicCtx, payload({ useBlocks: true }));
|
|
236
|
+
|
|
237
|
+
expect(callTelegramBotApiMock).toHaveBeenNthCalledWith(2, "sendMessage", {
|
|
238
|
+
chat_id: "123",
|
|
239
|
+
text: "hello",
|
|
240
|
+
message_thread_id: 777,
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("typing indicators target the topic", async () => {
|
|
245
|
+
await telegramTransport.sendTyping!(
|
|
246
|
+
topicCtx,
|
|
247
|
+
payload({ chatAction: "typing" }),
|
|
248
|
+
);
|
|
249
|
+
|
|
250
|
+
expect(callTelegramBotApiMock).toHaveBeenCalledWith("sendChatAction", {
|
|
251
|
+
chat_id: "123",
|
|
252
|
+
action: "typing",
|
|
253
|
+
message_thread_id: 777,
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
test("a callback URL without threadId keeps sends thread-less", async () => {
|
|
258
|
+
const bareCtx: CallbackContext = {
|
|
259
|
+
callbackUrl: "/deliver/telegram",
|
|
260
|
+
params: {},
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
await telegramTransport.deliver(bareCtx, payload({ useBlocks: false }));
|
|
264
|
+
await telegramTransport.sendTyping!(
|
|
265
|
+
bareCtx,
|
|
266
|
+
payload({ chatAction: "typing" }),
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
expect(callTelegramBotApiMock).toHaveBeenCalledWith("sendMessage", {
|
|
270
|
+
chat_id: "123",
|
|
271
|
+
text: "hello",
|
|
272
|
+
});
|
|
273
|
+
expect(callTelegramBotApiMock).toHaveBeenCalledWith("sendChatAction", {
|
|
274
|
+
chat_id: "123",
|
|
275
|
+
action: "typing",
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
});
|
|
@@ -36,6 +36,35 @@ const TELEGRAM_IMAGE_MIME_PREFIXES = [
|
|
|
36
36
|
"image/webp",
|
|
37
37
|
];
|
|
38
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Per-send options shared by the Telegram send helpers.
|
|
41
|
+
*
|
|
42
|
+
* `messageThreadId` targets a private-chat topic (the Telegram analog of a
|
|
43
|
+
* Slack thread); omitted, the send lands in the main chat. The value is the
|
|
44
|
+
* `message_thread_id` carried on the inbound update. Carried as a string
|
|
45
|
+
* because it originates as a URL param and multipart sends need the string
|
|
46
|
+
* form; payloads convert once in {@link threadIdPayloadFields}.
|
|
47
|
+
*/
|
|
48
|
+
export interface TelegramSendOptions {
|
|
49
|
+
messageThreadId?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Topic-targeting field for a send payload, or undefined when the send
|
|
54
|
+
* targets the main chat — spread into the payload literal.
|
|
55
|
+
*
|
|
56
|
+
* `message_thread_id` is the Bot API topic field for both forum supergroups
|
|
57
|
+
* and private chats of bots with topic ("threaded") mode enabled — the same
|
|
58
|
+
* field inbound updates carry. (`direct_messages_topic_id` is a different
|
|
59
|
+
* surface — channel direct-messages/monoforum chats — and is not used here.)
|
|
60
|
+
*/
|
|
61
|
+
function threadIdPayloadFields(
|
|
62
|
+
opts?: TelegramSendOptions,
|
|
63
|
+
): { message_thread_id: number } | undefined {
|
|
64
|
+
const id = opts?.messageThreadId?.trim();
|
|
65
|
+
return id ? { message_thread_id: Number(id) } : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
39
68
|
// ---------------------------------------------------------------------------
|
|
40
69
|
// Text splitting
|
|
41
70
|
// ---------------------------------------------------------------------------
|
|
@@ -98,6 +127,7 @@ export async function sendTelegramReply(
|
|
|
98
127
|
chatId: string,
|
|
99
128
|
text: string,
|
|
100
129
|
approval?: ApprovalUIMetadata,
|
|
130
|
+
opts?: TelegramSendOptions,
|
|
101
131
|
): Promise<void> {
|
|
102
132
|
const chunks = splitText(text, TELEGRAM_MAX_MESSAGE_LEN);
|
|
103
133
|
|
|
@@ -105,6 +135,7 @@ export async function sendTelegramReply(
|
|
|
105
135
|
const payload: Record<string, unknown> = {
|
|
106
136
|
chat_id: chatId,
|
|
107
137
|
text: chunks[i],
|
|
138
|
+
...threadIdPayloadFields(opts),
|
|
108
139
|
};
|
|
109
140
|
|
|
110
141
|
// Attach inline keyboard only to the last chunk so buttons appear after
|
|
@@ -150,17 +181,19 @@ export async function sendTelegramRichReply(
|
|
|
150
181
|
chatId: string,
|
|
151
182
|
markdown: string,
|
|
152
183
|
approval?: ApprovalUIMetadata,
|
|
184
|
+
opts?: TelegramSendOptions,
|
|
153
185
|
): Promise<void> {
|
|
154
186
|
const html = renderTelegramHtml(markdown);
|
|
155
187
|
if (html === undefined) {
|
|
156
188
|
// No renderable rich content — send as plain text.
|
|
157
|
-
await sendTelegramReply(chatId, markdown, approval);
|
|
189
|
+
await sendTelegramReply(chatId, markdown, approval, opts);
|
|
158
190
|
return;
|
|
159
191
|
}
|
|
160
192
|
|
|
161
193
|
const payload: Record<string, unknown> = {
|
|
162
194
|
chat_id: chatId,
|
|
163
195
|
rich_message: { html, skip_entity_detection: true },
|
|
196
|
+
...threadIdPayloadFields(opts),
|
|
164
197
|
};
|
|
165
198
|
if (approval) {
|
|
166
199
|
payload.reply_markup = buildInlineKeyboard(approval);
|
|
@@ -175,7 +208,7 @@ export async function sendTelegramRichReply(
|
|
|
175
208
|
{ chatId, description: err.description },
|
|
176
209
|
"Telegram rejected rich message; falling back to plain text",
|
|
177
210
|
);
|
|
178
|
-
await sendTelegramReply(chatId, markdown, approval);
|
|
211
|
+
await sendTelegramReply(chatId, markdown, approval, opts);
|
|
179
212
|
return;
|
|
180
213
|
}
|
|
181
214
|
throw err;
|
|
@@ -195,8 +228,10 @@ export type TelegramAttachmentResult = {
|
|
|
195
228
|
export async function sendTelegramAttachments(
|
|
196
229
|
chatId: string,
|
|
197
230
|
attachments: RuntimeAttachmentMetadata[],
|
|
231
|
+
opts?: TelegramSendOptions,
|
|
198
232
|
): Promise<TelegramAttachmentResult> {
|
|
199
233
|
const failures: string[] = [];
|
|
234
|
+
const threadFields = threadIdPayloadFields(opts);
|
|
200
235
|
|
|
201
236
|
for (const meta of attachments) {
|
|
202
237
|
// Skip oversized attachments when size is known upfront
|
|
@@ -238,6 +273,9 @@ export async function sendTelegramAttachments(
|
|
|
238
273
|
const blob = new Blob([new Uint8Array(content)], { type: mimeType });
|
|
239
274
|
const form = new FormData();
|
|
240
275
|
form.set("chat_id", chatId);
|
|
276
|
+
if (threadFields) {
|
|
277
|
+
form.set("message_thread_id", String(threadFields.message_thread_id));
|
|
278
|
+
}
|
|
241
279
|
|
|
242
280
|
const isImage = TELEGRAM_IMAGE_MIME_PREFIXES.some((p) =>
|
|
243
281
|
mimeType.startsWith(p),
|
|
@@ -267,7 +305,7 @@ export async function sendTelegramAttachments(
|
|
|
267
305
|
if (failures.length > 0) {
|
|
268
306
|
const notice = `\u26a0\ufe0f ${failures.length} attachment(s) could not be delivered: ${failures.join(", ")}`;
|
|
269
307
|
try {
|
|
270
|
-
await sendTelegramReply(chatId, notice);
|
|
308
|
+
await sendTelegramReply(chatId, notice, undefined, opts);
|
|
271
309
|
} catch (err) {
|
|
272
310
|
log.error({ err, chatId }, "Failed to send attachment failure notice");
|
|
273
311
|
}
|
|
@@ -286,11 +324,13 @@ export async function sendTelegramAttachments(
|
|
|
286
324
|
*/
|
|
287
325
|
export async function sendTelegramTypingIndicator(
|
|
288
326
|
chatId: string,
|
|
327
|
+
opts?: TelegramSendOptions,
|
|
289
328
|
): Promise<boolean> {
|
|
290
329
|
try {
|
|
291
330
|
await callTelegramBotApi("sendChatAction", {
|
|
292
331
|
chat_id: chatId,
|
|
293
332
|
action: "typing",
|
|
333
|
+
...threadIdPayloadFields(opts),
|
|
294
334
|
});
|
|
295
335
|
return true;
|
|
296
336
|
} catch (err) {
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { ChannelDeliveryError } from "@vellumai/gateway-client/http-delivery";
|
|
2
2
|
|
|
3
3
|
import { getLogger } from "../../../util/logger.js";
|
|
4
|
-
import type {
|
|
4
|
+
import type {
|
|
5
|
+
CallbackContext,
|
|
6
|
+
ChannelTransport,
|
|
7
|
+
} from "../channel-transport.js";
|
|
8
|
+
import type { TelegramSendOptions } from "./send.js";
|
|
5
9
|
import {
|
|
6
10
|
sendTelegramAttachments,
|
|
7
11
|
sendTelegramReply,
|
|
@@ -11,11 +15,21 @@ import {
|
|
|
11
15
|
|
|
12
16
|
const log = getLogger("telegram-transport");
|
|
13
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Topic targeting from the deliver callback URL's `threadId` param.
|
|
20
|
+
* Absent → main chat.
|
|
21
|
+
*/
|
|
22
|
+
function threadOptions(ctx: CallbackContext): TelegramSendOptions | undefined {
|
|
23
|
+
const threadId = ctx.params.threadId?.trim();
|
|
24
|
+
return threadId ? { messageThreadId: threadId } : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
14
27
|
export const telegramTransport: ChannelTransport = {
|
|
15
28
|
channel: "telegram",
|
|
16
29
|
|
|
17
|
-
async deliver(
|
|
30
|
+
async deliver(ctx, payload) {
|
|
18
31
|
const { chatId, text, attachments, approval } = payload;
|
|
32
|
+
const opts = threadOptions(ctx);
|
|
19
33
|
|
|
20
34
|
if (text) {
|
|
21
35
|
// `useBlocks` is the channel-neutral "render richly" intent set by the
|
|
@@ -23,20 +37,21 @@ export const telegramTransport: ChannelTransport = {
|
|
|
23
37
|
// to `sendRichMessage`, degrading to plain text otherwise (and on any
|
|
24
38
|
// rich-send rejection).
|
|
25
39
|
if (payload.useBlocks) {
|
|
26
|
-
await sendTelegramRichReply(chatId, text, approval);
|
|
40
|
+
await sendTelegramRichReply(chatId, text, approval, opts);
|
|
27
41
|
} else {
|
|
28
|
-
await sendTelegramReply(chatId, text, approval);
|
|
42
|
+
await sendTelegramReply(chatId, text, approval, opts);
|
|
29
43
|
}
|
|
30
44
|
} else if (approval) {
|
|
31
45
|
await sendTelegramReply(
|
|
32
46
|
chatId,
|
|
33
47
|
approval.plainTextFallback || "Approval required",
|
|
34
48
|
approval,
|
|
49
|
+
opts,
|
|
35
50
|
);
|
|
36
51
|
}
|
|
37
52
|
|
|
38
53
|
if (attachments && attachments.length > 0) {
|
|
39
|
-
const result = await sendTelegramAttachments(chatId, attachments);
|
|
54
|
+
const result = await sendTelegramAttachments(chatId, attachments, opts);
|
|
40
55
|
if (result.allFailed && !text) {
|
|
41
56
|
throw new ChannelDeliveryError(
|
|
42
57
|
502,
|
|
@@ -45,12 +60,15 @@ export const telegramTransport: ChannelTransport = {
|
|
|
45
60
|
}
|
|
46
61
|
}
|
|
47
62
|
|
|
48
|
-
log.info(
|
|
63
|
+
log.info(
|
|
64
|
+
{ chatId, hasText: !!text, messageThreadId: opts?.messageThreadId },
|
|
65
|
+
"Telegram reply delivered (direct)",
|
|
66
|
+
);
|
|
49
67
|
return { ok: true };
|
|
50
68
|
},
|
|
51
69
|
|
|
52
|
-
async sendTyping(
|
|
53
|
-
await sendTelegramTypingIndicator(payload.chatId);
|
|
70
|
+
async sendTyping(ctx, payload) {
|
|
71
|
+
await sendTelegramTypingIndicator(payload.chatId, threadOptions(ctx));
|
|
54
72
|
log.debug(
|
|
55
73
|
{ chatId: payload.chatId },
|
|
56
74
|
"Telegram typing indicator delivered (direct)",
|