@vellumai/assistant 0.10.11-dev.202607222129.31c06e5 → 0.10.11-dev.202607222226.fdf0e3d
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__/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__/tool-approval-handler.test.ts +25 -1
- package/src/api/events/bookmark-created.ts +37 -0
- package/src/api/events/bookmark-deleted.ts +20 -0
- package/src/api/index.ts +14 -0
- 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
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,
|
|
@@ -656,6 +668,8 @@ export const AssistantEventSchema = z.discriminatedUnion("type", [
|
|
|
656
668
|
AvatarUpdatedEventSchema,
|
|
657
669
|
BackgroundToolCompletedEventSchema,
|
|
658
670
|
BackgroundToolStartedEventSchema,
|
|
671
|
+
BookmarkCreatedEventSchema,
|
|
672
|
+
BookmarkDeletedEventSchema,
|
|
659
673
|
CompactionCircuitClosedEventSchema,
|
|
660
674
|
CompactionCircuitOpenEventSchema,
|
|
661
675
|
ConfirmationRequestEventSchema,
|
|
@@ -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)",
|
|
@@ -860,7 +860,24 @@ export async function check(
|
|
|
860
860
|
signal,
|
|
861
861
|
);
|
|
862
862
|
|
|
863
|
-
const { level:
|
|
863
|
+
const { level: classifiedRisk, reason: riskReason } = classification;
|
|
864
|
+
|
|
865
|
+
// Inline-command ("dynamic") skill loads execute embedded shell at load time
|
|
866
|
+
// via child_process.spawn, outside the tool-approval pipeline that the
|
|
867
|
+
// auto-approve threshold governs. Treat an uncovered one as High so the
|
|
868
|
+
// standard threshold decides it like any other high-risk action: it runs at
|
|
869
|
+
// Full access (autoApproveUpTo "high") and prompts below it. A covering user
|
|
870
|
+
// trust rule arrives as matchType
|
|
871
|
+
// "user_rule" with the risk already lowered (the escape hatch), so leave it
|
|
872
|
+
// untouched. The gateway classifier is authoritative and also returns High;
|
|
873
|
+
// this local elevation is defense-in-depth for the gateway-unreachable or
|
|
874
|
+
// under-classified path. The separate non-interactive denial (no human to
|
|
875
|
+
// approve embedded shell) lives in tools/permission-checker.ts.
|
|
876
|
+
const risk =
|
|
877
|
+
isDynamicSkillLoadInvocation(toolName, input) &&
|
|
878
|
+
getCachedAssessment(toolName, input)?.matchType !== "user_rule"
|
|
879
|
+
? RiskLevel.High
|
|
880
|
+
: classifiedRisk;
|
|
864
881
|
|
|
865
882
|
// Use gateway-provided sandboxAutoApprove instead of evaluating locally.
|
|
866
883
|
const hasSandboxAutoApprove = classification.sandboxAutoApprove ?? false;
|
|
@@ -912,26 +929,6 @@ export async function check(
|
|
|
912
929
|
}
|
|
913
930
|
}
|
|
914
931
|
|
|
915
|
-
// Inline-command ("dynamic") skill loads execute embedded shell commands
|
|
916
|
-
// at load time, so a threshold-based allow is not enough: they run
|
|
917
|
-
// without asking only when the user's own trust rule covers them (the
|
|
918
|
-
// rule re-classifies the risk inside the gateway, arriving here as
|
|
919
|
-
// matchType "user_rule"). Everything else prompts — at every threshold
|
|
920
|
-
// and in every execution context. The non-interactive guardian gate in
|
|
921
|
-
// tools/permission-checker.ts then converts the prompt into a denial
|
|
922
|
-
// when no human is present to answer it.
|
|
923
|
-
if (
|
|
924
|
-
approvalDecision.decision === "allow" &&
|
|
925
|
-
isDynamicSkillLoadInvocation(toolName, input) &&
|
|
926
|
-
getCachedAssessment(toolName, input)?.matchType !== "user_rule"
|
|
927
|
-
) {
|
|
928
|
-
approvalDecision = {
|
|
929
|
-
decision: "prompt",
|
|
930
|
-
reason:
|
|
931
|
-
"Inline-command skill load: executes embedded commands, requires explicit approval",
|
|
932
|
-
};
|
|
933
|
-
}
|
|
934
|
-
|
|
935
932
|
// Enrich the reason with the classifier's explanation when available.
|
|
936
933
|
// For risk-based fallback decisions (prompt/deny from High/Medium risk),
|
|
937
934
|
// incorporate the classifier reason so the user sees *why* the command
|
|
@@ -32,6 +32,20 @@ const log = getLogger("confirmation-guardian-request");
|
|
|
32
32
|
export async function createGuardianRequestForConfirmation(
|
|
33
33
|
msg: ServerMessage & { type: "confirmation_request" },
|
|
34
34
|
conversationId: string,
|
|
35
|
+
opts?: {
|
|
36
|
+
/**
|
|
37
|
+
* Bind the request to the conversation's per-turn trust snapshot rather
|
|
38
|
+
* than the live context. Turn-emitted confirmations (PermissionPrompter)
|
|
39
|
+
* set this: the promotion runs fire-and-forget, and the live trustContext
|
|
40
|
+
* can mutate mid-promotion (e.g. a concurrent owner meta command), so the
|
|
41
|
+
* snapshot pins the actor and source-message provenance to the turn that
|
|
42
|
+
* emitted the confirmation — the executor's own snapshot semantics.
|
|
43
|
+
* Route-generated confirmations (ACP spawn/steer) leave this unset: their
|
|
44
|
+
* provenance is the conversation's live binding, not whatever unrelated
|
|
45
|
+
* turn happens to be in flight.
|
|
46
|
+
*/
|
|
47
|
+
preferTurnSnapshot?: boolean;
|
|
48
|
+
},
|
|
35
49
|
): Promise<void> {
|
|
36
50
|
try {
|
|
37
51
|
const [
|
|
@@ -51,7 +65,9 @@ export async function createGuardianRequestForConfirmation(
|
|
|
51
65
|
]);
|
|
52
66
|
|
|
53
67
|
const conversation = findConversation(conversationId);
|
|
54
|
-
const trustContext =
|
|
68
|
+
const trustContext = opts?.preferTurnSnapshot
|
|
69
|
+
? (conversation?.currentTurnTrustContext ?? conversation?.trustContext)
|
|
70
|
+
: conversation?.trustContext;
|
|
55
71
|
const sourceChannel = trustContext?.sourceChannel ?? "vellum";
|
|
56
72
|
const inputRecord = msg.input as Record<string, unknown>;
|
|
57
73
|
const activityRaw =
|
|
@@ -180,10 +180,13 @@ export class PermissionPrompter {
|
|
|
180
180
|
|
|
181
181
|
// Promote the confirmation to a guardian request so channel
|
|
182
182
|
// guardian decisions (reactions, buttons, text) can resolve it.
|
|
183
|
+
// The prompter runs inside the emitting turn, so the request binds
|
|
184
|
+
// to that turn's trust snapshot.
|
|
183
185
|
if (conversationId) {
|
|
184
186
|
void createGuardianRequestForConfirmation(
|
|
185
187
|
confirmationMsg,
|
|
186
188
|
conversationId,
|
|
189
|
+
{ preferTurnSnapshot: true },
|
|
187
190
|
);
|
|
188
191
|
}
|
|
189
192
|
|
|
@@ -45,7 +45,10 @@ import { getLogger } from "../util/logger.js";
|
|
|
45
45
|
import { getLogsDbPath } from "../util/logs-db-path.js";
|
|
46
46
|
import { getConversationsDir } from "../util/platform.js";
|
|
47
47
|
import { createRowMapper, parseJsonNullable } from "../util/row-mapper.js";
|
|
48
|
-
import {
|
|
48
|
+
import {
|
|
49
|
+
isRetryableSqliteError,
|
|
50
|
+
withSqliteRetry,
|
|
51
|
+
} from "../util/sqlite-retry.js";
|
|
49
52
|
import {
|
|
50
53
|
deleteOrphanAttachments,
|
|
51
54
|
linkAttachmentToMessage,
|
|
@@ -2744,18 +2747,43 @@ export function getConversationPersistedSeq(id: string): number | null {
|
|
|
2744
2747
|
* Monotonic: the `WHERE seq IS NULL OR seq < ?` guard makes the update raise
|
|
2745
2748
|
* the high-water mark only, so out-of-order async commits never regress it.
|
|
2746
2749
|
* Non-positive or non-finite `seq` values are ignored.
|
|
2750
|
+
*
|
|
2751
|
+
* Transient SQLite write contention (`SQLITE_BUSY`/`SQLITE_IOERR`) is swallowed
|
|
2752
|
+
* rather than thrown. This is a single, idempotent, monotonic UPDATE of a
|
|
2753
|
+
* snapshot↔stream anchor that every subsequent flush re-records with an
|
|
2754
|
+
* equal-or-higher seq, so a dropped write self-heals on the next flush — the
|
|
2755
|
+
* same self-healing property that lets the paired content write
|
|
2756
|
+
* (`persistLoopMessageContent`) swallow its final failure. `busy_timeout`
|
|
2757
|
+
* already made the statement wait for the lock before surfacing `SQLITE_BUSY`,
|
|
2758
|
+
* so this synchronous path cannot usefully back off and retry; it just must not
|
|
2759
|
+
* throw. Several callers are fire-and-forget bookkeeping in the agent loop
|
|
2760
|
+
* (`flushAccumulatedContent`, `handleMessageComplete`, tool events) where a
|
|
2761
|
+
* raw throw is fatal: the debounced partial flush becomes an unhandled
|
|
2762
|
+
* rejection, and `message_complete` is on `dispatchAgentEvent`'s re-throw
|
|
2763
|
+
* allowlist — either one takes down the daemon on lock contention. A
|
|
2764
|
+
* non-contention error (a genuine bug: bad SQL, missing column) still throws.
|
|
2747
2765
|
*/
|
|
2748
2766
|
export function recordConversationPersistedSeq(id: string, seq: number): void {
|
|
2749
2767
|
if (!Number.isFinite(seq) || seq <= 0) {
|
|
2750
2768
|
return;
|
|
2751
2769
|
}
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2770
|
+
try {
|
|
2771
|
+
rawRun(
|
|
2772
|
+
"conversation:recordPersistedSeq",
|
|
2773
|
+
"UPDATE conversations SET seq = ? WHERE id = ? AND (seq IS NULL OR seq < ?)",
|
|
2774
|
+
seq,
|
|
2775
|
+
id,
|
|
2776
|
+
seq,
|
|
2777
|
+
);
|
|
2778
|
+
} catch (err) {
|
|
2779
|
+
if (!isRetryableSqliteError(err)) {
|
|
2780
|
+
throw err;
|
|
2781
|
+
}
|
|
2782
|
+
log.warn(
|
|
2783
|
+
{ err, conversationId: id, seq },
|
|
2784
|
+
"recordConversationPersistedSeq: transient SQLite contention; dropping this anchor advance (self-heals on the next flush)",
|
|
2785
|
+
);
|
|
2786
|
+
}
|
|
2759
2787
|
}
|
|
2760
2788
|
|
|
2761
2789
|
/**
|
|
@@ -37,6 +37,13 @@ export interface RecordInboundOptions {
|
|
|
37
37
|
const SLACK_LEGACY_THREAD_EVIDENCE_BATCH_SIZE = 50;
|
|
38
38
|
const SLACK_LEGACY_THREAD_EVIDENCE_MAX_SCAN = 500;
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* Channels where an inbound thread id scopes the conversation: a Slack thread
|
|
42
|
+
* or a Telegram private-chat topic each maps to its own conversation. A
|
|
43
|
+
* message without a thread id always resolves to the chat-level base key.
|
|
44
|
+
*/
|
|
45
|
+
const THREAD_SCOPED_CHANNELS = new Set(["slack", "telegram"]);
|
|
46
|
+
|
|
40
47
|
function buildScopedConversationKeyForAssistant(
|
|
41
48
|
assistantId: string,
|
|
42
49
|
sourceChannel: string,
|
|
@@ -44,7 +51,7 @@ function buildScopedConversationKeyForAssistant(
|
|
|
44
51
|
sourceThreadId?: string | null,
|
|
45
52
|
): string {
|
|
46
53
|
const threadId = sourceThreadId?.trim();
|
|
47
|
-
if (sourceChannel
|
|
54
|
+
if (THREAD_SCOPED_CHANNELS.has(sourceChannel) && threadId) {
|
|
48
55
|
return `asst:${assistantId}:${sourceChannel}:${externalChatId}:thread:${threadId}`;
|
|
49
56
|
}
|
|
50
57
|
return `asst:${assistantId}:${sourceChannel}:${externalChatId}`;
|
|
@@ -137,6 +144,11 @@ function resolveInboundConversation(
|
|
|
137
144
|
);
|
|
138
145
|
|
|
139
146
|
const threadId = sourceThreadId?.trim();
|
|
147
|
+
// Flat→threaded aliasing applies only to Slack: a Slack thread may continue
|
|
148
|
+
// a conversation that lives on the flat channel key, so the alias path below
|
|
149
|
+
// checks for that evidence before minting a threaded conversation. Every
|
|
150
|
+
// other thread-scoped channel (Telegram topics) has no flat-key aliasing —
|
|
151
|
+
// a thread id always resolves the threaded key directly.
|
|
140
152
|
if (sourceChannel !== "slack" || !threadId) {
|
|
141
153
|
return getOrCreateConversation(threadedKey);
|
|
142
154
|
}
|
|
@@ -262,6 +262,28 @@ export function deleteBindingByChannelChat(
|
|
|
262
262
|
.run();
|
|
263
263
|
}
|
|
264
264
|
|
|
265
|
+
/**
|
|
266
|
+
* Remove only the thread-less (chat-level) binding for a channel + chat,
|
|
267
|
+
* leaving bindings that carry an `externalThreadId` untouched. Used when
|
|
268
|
+
* resetting a chat's main conversation so sibling thread/topic conversations
|
|
269
|
+
* in the same chat keep their bindings.
|
|
270
|
+
*/
|
|
271
|
+
export function deleteBindingByChannelChatNullThread(
|
|
272
|
+
sourceChannel: string,
|
|
273
|
+
externalChatId: string,
|
|
274
|
+
): void {
|
|
275
|
+
const db = getDb();
|
|
276
|
+
db.delete(externalConversationBindings)
|
|
277
|
+
.where(
|
|
278
|
+
and(
|
|
279
|
+
eq(externalConversationBindings.sourceChannel, sourceChannel),
|
|
280
|
+
eq(externalConversationBindings.externalChatId, externalChatId),
|
|
281
|
+
isNull(externalConversationBindings.externalThreadId),
|
|
282
|
+
),
|
|
283
|
+
)
|
|
284
|
+
.run();
|
|
285
|
+
}
|
|
286
|
+
|
|
265
287
|
/**
|
|
266
288
|
* Remove an external binding by channel + external chat ID + thread ID.
|
|
267
289
|
*/
|
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Channel conversation
|
|
2
|
+
* Channel conversation reset handler.
|
|
3
|
+
*
|
|
4
|
+
* Channel-agnostic contract — two reset shapes, keyed on `sourceThreadId`:
|
|
5
|
+
*
|
|
6
|
+
* - **Thread-less reset** (no `sourceThreadId`): resets the chat's MAIN
|
|
7
|
+
* conversation only — deletes the base + legacy keys and the thread-less
|
|
8
|
+
* binding. Thread/topic conversations in the same chat (Slack threads,
|
|
9
|
+
* Telegram topics) are independent conversations and are never touched.
|
|
10
|
+
* - **Threaded reset** (`sourceThreadId` set): resets exactly that
|
|
11
|
+
* thread/topic's conversation — deletes its scoped key and its binding.
|
|
12
|
+
*
|
|
13
|
+
* Adapter-specific behavior stays inside the explicitly channel-gated
|
|
14
|
+
* branches below and must not leak into the shared contract.
|
|
3
15
|
*/
|
|
4
16
|
import {
|
|
5
17
|
deleteConversationKey,
|
|
@@ -7,7 +19,7 @@ import {
|
|
|
7
19
|
} from "../../persistence/conversation-key-store.js";
|
|
8
20
|
import { buildScopedConversationKey } from "../../persistence/delivery-crud.js";
|
|
9
21
|
import {
|
|
10
|
-
|
|
22
|
+
deleteBindingByChannelChatNullThread,
|
|
11
23
|
deleteBindingByChannelChatThread,
|
|
12
24
|
} from "../../persistence/external-conversation-store.js";
|
|
13
25
|
import { BadRequestError } from "./errors.js";
|
|
@@ -38,8 +50,12 @@ export function handleDeleteConversation({ body = {} }: RouteHandlerArgs) {
|
|
|
38
50
|
const legacyKey = `${sourceChannel}:${conversationExternalId}`;
|
|
39
51
|
if (!normalizedThreadId) {
|
|
40
52
|
deleteConversationKey(legacyKey);
|
|
41
|
-
|
|
53
|
+
deleteBindingByChannelChatNullThread(sourceChannel, conversationExternalId);
|
|
42
54
|
} else {
|
|
55
|
+
// Slack adapter: eagerly re-mint a fresh conversation for the threaded
|
|
56
|
+
// key so mid-thread turns racing the reset land in the new conversation.
|
|
57
|
+
// Telegram deliberately skips this — a reset topic simply creates its
|
|
58
|
+
// fresh conversation on the next inbound message.
|
|
43
59
|
if (sourceChannel === "slack") {
|
|
44
60
|
getOrCreateConversation(scopedKey);
|
|
45
61
|
}
|
|
@@ -674,12 +674,15 @@ export async function handleChannelInbound({
|
|
|
674
674
|
typeof sourceMetadata?.messageId === "string"
|
|
675
675
|
? sourceMetadata.messageId
|
|
676
676
|
: undefined;
|
|
677
|
-
|
|
678
|
-
|
|
677
|
+
// Thread id of the inbound message's external container (Slack thread ts,
|
|
678
|
+
// Telegram topic id). Scopes conversation resolution and the persisted
|
|
679
|
+
// binding for thread-scoped channels.
|
|
680
|
+
const channelThreadId =
|
|
679
681
|
typeof sourceMetadata?.threadId === "string" &&
|
|
680
682
|
sourceMetadata.threadId.trim().length > 0
|
|
681
683
|
? sourceMetadata.threadId.trim()
|
|
682
684
|
: undefined;
|
|
685
|
+
const slackThreadTs = sourceChannel === "slack" ? channelThreadId : undefined;
|
|
683
686
|
|
|
684
687
|
if (isEdit && !sourceMessageId) {
|
|
685
688
|
throw new BadRequestError("sourceMetadata.messageId is required for edits");
|
|
@@ -692,7 +695,7 @@ export async function handleChannelInbound({
|
|
|
692
695
|
conversationExternalId,
|
|
693
696
|
externalMessageId,
|
|
694
697
|
sourceMessageId,
|
|
695
|
-
sourceThreadId:
|
|
698
|
+
sourceThreadId: channelThreadId,
|
|
696
699
|
canonicalAssistantId,
|
|
697
700
|
assistantId,
|
|
698
701
|
content,
|
|
@@ -708,7 +711,7 @@ export async function handleChannelInbound({
|
|
|
708
711
|
{
|
|
709
712
|
sourceMessageId,
|
|
710
713
|
assistantId: canonicalAssistantId,
|
|
711
|
-
sourceThreadId:
|
|
714
|
+
sourceThreadId: channelThreadId,
|
|
712
715
|
},
|
|
713
716
|
);
|
|
714
717
|
|
|
@@ -723,7 +726,7 @@ export async function handleChannelInbound({
|
|
|
723
726
|
sourceChannel,
|
|
724
727
|
externalChatId: conversationExternalId,
|
|
725
728
|
externalChatName: slackChannelName,
|
|
726
|
-
externalThreadId:
|
|
729
|
+
externalThreadId: channelThreadId ?? null,
|
|
727
730
|
externalUserId: canonicalSenderId ?? rawSenderId ?? null,
|
|
728
731
|
displayName: body.actorDisplayName ?? null,
|
|
729
732
|
username: body.actorUsername ?? null,
|