@vellumai/assistant 0.10.3-dev.202606260109.8a3d17b → 0.10.3-dev.202606260916.ffa4dca
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 +1 -1
- package/src/__tests__/channel-reply-delivery.test.ts +6 -2
- package/src/__tests__/conversation-title-service.test.ts +222 -201
- package/src/__tests__/mcp-config-secret-boundary.test.ts +1 -0
- package/src/__tests__/slack-block-formatting.test.ts +1 -38
- package/src/memory/__tests__/embedding-cache.test.ts +136 -0
- package/src/memory/conversation-title-service.ts +173 -24
- package/src/memory/embedding-backend.ts +8 -1
- package/src/memory/embedding-cache.ts +139 -0
- package/src/messaging/providers/__tests__/callback-routing.test.ts +45 -0
- package/src/messaging/providers/__tests__/transport-dispatch.test.ts +195 -0
- package/src/messaging/providers/a2a/__tests__/deliver.test.ts +11 -0
- package/src/messaging/providers/a2a/deliver.ts +5 -1
- package/src/messaging/providers/a2a/transport.ts +10 -0
- package/src/messaging/providers/callback-routing.ts +48 -0
- package/src/messaging/providers/channel-transport.ts +55 -0
- package/src/messaging/providers/index.ts +65 -241
- package/src/messaging/providers/slack/transport.ts +92 -0
- package/src/messaging/providers/telegram-bot/transport.ts +51 -0
- package/src/messaging/providers/whatsapp/transport.ts +38 -0
- package/src/plugins/defaults/memory-v3-shadow/__tests__/dense.test.ts +11 -0
- package/src/plugins/defaults/memory-v3-shadow/__tests__/section-dense-store.test.ts +243 -2
- package/src/plugins/defaults/memory-v3-shadow/section-dense-store.ts +167 -14
- package/src/runtime/channel-reply-delivery.ts +3 -8
- package/src/runtime/slack-block-formatting.ts +0 -15
|
@@ -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,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for `assistant/src/memory/embedding-cache.ts` — the shared dense-vector
|
|
3
|
+
* cache over the `memory_embeddings` table. Exercises the real SQL against a
|
|
4
|
+
* temp workspace DB (round-trip, dim-mismatch miss, key isolation, upsert).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import {
|
|
11
|
+
afterAll,
|
|
12
|
+
beforeAll,
|
|
13
|
+
beforeEach,
|
|
14
|
+
describe,
|
|
15
|
+
expect,
|
|
16
|
+
mock,
|
|
17
|
+
test,
|
|
18
|
+
} from "bun:test";
|
|
19
|
+
|
|
20
|
+
mock.module("../../util/logger.js", () => ({
|
|
21
|
+
getLogger: () =>
|
|
22
|
+
new Proxy({} as Record<string, unknown>, { get: () => () => {} }),
|
|
23
|
+
}));
|
|
24
|
+
|
|
25
|
+
let tmpWorkspace: string;
|
|
26
|
+
let previousWorkspaceEnv: string | undefined;
|
|
27
|
+
|
|
28
|
+
beforeAll(() => {
|
|
29
|
+
tmpWorkspace = mkdtempSync(join(tmpdir(), "embedding-cache-test-"));
|
|
30
|
+
previousWorkspaceEnv = process.env.VELLUM_WORKSPACE_DIR;
|
|
31
|
+
process.env.VELLUM_WORKSPACE_DIR = tmpWorkspace;
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
afterAll(() => {
|
|
35
|
+
if (previousWorkspaceEnv === undefined) {
|
|
36
|
+
delete process.env.VELLUM_WORKSPACE_DIR;
|
|
37
|
+
} else {
|
|
38
|
+
process.env.VELLUM_WORKSPACE_DIR = previousWorkspaceEnv;
|
|
39
|
+
}
|
|
40
|
+
rmSync(tmpWorkspace, { recursive: true, force: true });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Deferred so internal `getWorkspaceDir()` resolves to the tmpdir set above.
|
|
44
|
+
const { getDb } = await import("../db-connection.js");
|
|
45
|
+
const { resetDbForTesting } =
|
|
46
|
+
await import("../../__tests__/db-test-helpers.js");
|
|
47
|
+
const { initializeDb } = await import("../db-init.js");
|
|
48
|
+
const { memoryEmbeddings } = await import("../schema.js");
|
|
49
|
+
const { readEmbeddingCache, writeEmbeddingCache } =
|
|
50
|
+
await import("../embedding-cache.js");
|
|
51
|
+
|
|
52
|
+
beforeEach(async () => {
|
|
53
|
+
resetDbForTesting();
|
|
54
|
+
// The first run pays the full cold-start migration chain; bump the hook
|
|
55
|
+
// timeout above bun's 5s default so the leading test doesn't flake in CI.
|
|
56
|
+
await initializeDb();
|
|
57
|
+
}, 30_000);
|
|
58
|
+
|
|
59
|
+
const KEY = {
|
|
60
|
+
targetType: "v3_section",
|
|
61
|
+
targetId: "people/alice#0",
|
|
62
|
+
provider: "local",
|
|
63
|
+
model: "test-model",
|
|
64
|
+
expectedDim: 4,
|
|
65
|
+
} as const;
|
|
66
|
+
|
|
67
|
+
function seed(
|
|
68
|
+
overrides: Partial<{
|
|
69
|
+
dense: number[];
|
|
70
|
+
contentHash: string;
|
|
71
|
+
now: number;
|
|
72
|
+
}> = {},
|
|
73
|
+
): void {
|
|
74
|
+
writeEmbeddingCache(getDb(), {
|
|
75
|
+
targetType: KEY.targetType,
|
|
76
|
+
targetId: KEY.targetId,
|
|
77
|
+
provider: KEY.provider,
|
|
78
|
+
model: KEY.model,
|
|
79
|
+
dense: overrides.dense ?? [1, 2, 3, 4],
|
|
80
|
+
contentHash: overrides.contentHash ?? "hash-a",
|
|
81
|
+
now: overrides.now ?? 1000,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
describe("embedding-cache", () => {
|
|
86
|
+
test("read returns null when nothing is cached", () => {
|
|
87
|
+
expect(readEmbeddingCache(getDb(), KEY)).toBeNull();
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("write then read round-trips the vector and content hash", () => {
|
|
91
|
+
seed({ dense: [1, 2, 3, 4], contentHash: "hash-a" });
|
|
92
|
+
|
|
93
|
+
const got = readEmbeddingCache(getDb(), KEY);
|
|
94
|
+
expect(got).not.toBeNull();
|
|
95
|
+
expect(got!.dense).toEqual([1, 2, 3, 4]);
|
|
96
|
+
expect(got!.contentHash).toBe("hash-a");
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("read misses when the configured dimension differs from the stored row", () => {
|
|
100
|
+
seed();
|
|
101
|
+
expect(readEmbeddingCache(getDb(), { ...KEY, expectedDim: 8 })).toBeNull();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("read is isolated by targetType / targetId / provider / model", () => {
|
|
105
|
+
seed();
|
|
106
|
+
const db = getDb();
|
|
107
|
+
expect(
|
|
108
|
+
readEmbeddingCache(db, { ...KEY, targetType: "concept_page" }),
|
|
109
|
+
).toBeNull();
|
|
110
|
+
expect(
|
|
111
|
+
readEmbeddingCache(db, { ...KEY, targetId: "people/bob#0" }),
|
|
112
|
+
).toBeNull();
|
|
113
|
+
expect(readEmbeddingCache(db, { ...KEY, provider: "openai" })).toBeNull();
|
|
114
|
+
expect(readEmbeddingCache(db, { ...KEY, model: "other-model" })).toBeNull();
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("re-writing the same key upserts in place (one row, latest content)", () => {
|
|
118
|
+
const db = getDb();
|
|
119
|
+
seed({ dense: [1, 2, 3, 4], contentHash: "hash-a", now: 1000 });
|
|
120
|
+
seed({ dense: [5, 6, 7, 8], contentHash: "hash-b", now: 2000 });
|
|
121
|
+
|
|
122
|
+
const got = readEmbeddingCache(db, KEY);
|
|
123
|
+
expect(got!.dense).toEqual([5, 6, 7, 8]);
|
|
124
|
+
expect(got!.contentHash).toBe("hash-b");
|
|
125
|
+
|
|
126
|
+
// The unique key collapses both writes onto a single row.
|
|
127
|
+
const rows = db
|
|
128
|
+
.select()
|
|
129
|
+
.from(memoryEmbeddings)
|
|
130
|
+
.all()
|
|
131
|
+
.filter(
|
|
132
|
+
(r) => r.targetType === KEY.targetType && r.targetId === KEY.targetId,
|
|
133
|
+
);
|
|
134
|
+
expect(rows).toHaveLength(1);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -7,9 +7,14 @@
|
|
|
7
7
|
* overwritten, never user-provided custom titles.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
import {
|
|
11
|
+
createTimeout,
|
|
12
|
+
extractAllText,
|
|
13
|
+
extractToolUse,
|
|
14
|
+
getConfiguredProvider,
|
|
15
|
+
userMessage as buildUserMessage,
|
|
16
|
+
} from "../providers/provider-send-message.js";
|
|
17
|
+
import type { Provider, ToolDefinition } from "../providers/types.js";
|
|
13
18
|
import { publishConversationTitleChanged } from "../runtime/sync/resource-sync-events.js";
|
|
14
19
|
import { getLogger } from "../util/logger.js";
|
|
15
20
|
import { Mutex } from "../util/mutex.js";
|
|
@@ -171,16 +176,7 @@ export async function generateAndPersistConversationTitle(
|
|
|
171
176
|
}
|
|
172
177
|
|
|
173
178
|
const prompt = buildTitlePrompt(context, userMessage, assistantResponse);
|
|
174
|
-
const
|
|
175
|
-
content: prompt,
|
|
176
|
-
provider,
|
|
177
|
-
systemPrompt: buildTitleSystemPrompt(),
|
|
178
|
-
tools: [],
|
|
179
|
-
callSite: "conversationTitle",
|
|
180
|
-
signal,
|
|
181
|
-
timeoutMs: 15_000,
|
|
182
|
-
});
|
|
183
|
-
const title = normalizeTitle(result.text);
|
|
179
|
+
const title = await generateTitleViaLLM(provider, prompt, signal);
|
|
184
180
|
if (title) {
|
|
185
181
|
// Re-check replaceability before persisting (race guard)
|
|
186
182
|
const current = getConversation(conversationId);
|
|
@@ -318,16 +314,7 @@ export async function regenerateConversationTitle(
|
|
|
318
314
|
if (!/\n(?:User|Assistant): /.test(prompt)) {
|
|
319
315
|
return { title: conversation.title ?? UNTITLED_FALLBACK, updated: false };
|
|
320
316
|
}
|
|
321
|
-
const
|
|
322
|
-
content: prompt,
|
|
323
|
-
provider,
|
|
324
|
-
systemPrompt: buildTitleSystemPrompt(),
|
|
325
|
-
tools: [],
|
|
326
|
-
callSite: "conversationTitle",
|
|
327
|
-
signal,
|
|
328
|
-
timeoutMs: 15_000,
|
|
329
|
-
});
|
|
330
|
-
const title = normalizeTitle(result.text);
|
|
317
|
+
const title = await generateTitleViaLLM(provider, prompt, signal);
|
|
331
318
|
if (title) {
|
|
332
319
|
// Re-check isAutoTitle before persisting (race guard against manual rename)
|
|
333
320
|
const current = getConversation(conversationId);
|
|
@@ -396,6 +383,81 @@ function buildTitleSystemPrompt(): string {
|
|
|
396
383
|
].join("\n");
|
|
397
384
|
}
|
|
398
385
|
|
|
386
|
+
const TITLE_TOOL_NAME = "record_conversation_title";
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Tool the title model is forced to call. Constraining the output to a single
|
|
390
|
+
* `title` argument keeps weak/fast models (e.g. Haiku-class title models) from
|
|
391
|
+
* "thinking aloud" or continuing the conversation in the response text —
|
|
392
|
+
* failure modes that otherwise get captured verbatim as the title
|
|
393
|
+
* (e.g. "I need to generate a…", "I'll work through these files…").
|
|
394
|
+
*/
|
|
395
|
+
function buildTitleTool(): ToolDefinition {
|
|
396
|
+
return {
|
|
397
|
+
name: TITLE_TOOL_NAME,
|
|
398
|
+
description:
|
|
399
|
+
"Record the conversation's title. Call this exactly once with a short noun phrase naming the TOPIC — never a sentence, a reply, or any preamble.",
|
|
400
|
+
input_schema: {
|
|
401
|
+
type: "object",
|
|
402
|
+
properties: {
|
|
403
|
+
title: {
|
|
404
|
+
type: "string",
|
|
405
|
+
description:
|
|
406
|
+
"2–5 words, 40 characters max. A scannable sidebar label naming the topic (e.g. 'Auth Middleware Rewrite', 'Docker Volume Mounts'). No quotes, markdown, or trailing punctuation.",
|
|
407
|
+
},
|
|
408
|
+
},
|
|
409
|
+
required: ["title"],
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Run the title LLM call with a forced tool so the model returns a structured
|
|
416
|
+
* `{ title }` rather than free text. Returns a normalized title, or "" when the
|
|
417
|
+
* model declines or misbehaves — callers fall back to a deterministic title.
|
|
418
|
+
*
|
|
419
|
+
* Forcing the tool is the primary guard against prose leakage; `normalizeTitle`
|
|
420
|
+
* is the backstop for the text-fallback path and for any provider that ignores
|
|
421
|
+
* forced `tool_choice`.
|
|
422
|
+
*/
|
|
423
|
+
async function generateTitleViaLLM(
|
|
424
|
+
provider: Provider,
|
|
425
|
+
prompt: string,
|
|
426
|
+
signal?: AbortSignal,
|
|
427
|
+
): Promise<string> {
|
|
428
|
+
const { signal: timeoutSignal, cleanup } = createTimeout(15_000);
|
|
429
|
+
const combinedSignal = signal
|
|
430
|
+
? AbortSignal.any([signal, timeoutSignal])
|
|
431
|
+
: timeoutSignal;
|
|
432
|
+
try {
|
|
433
|
+
const response = await provider.sendMessage([buildUserMessage(prompt)], {
|
|
434
|
+
tools: [buildTitleTool()],
|
|
435
|
+
systemPrompt: buildTitleSystemPrompt(),
|
|
436
|
+
config: {
|
|
437
|
+
max_tokens: 256,
|
|
438
|
+
callSite: "conversationTitle",
|
|
439
|
+
tool_choice: { type: "tool", name: TITLE_TOOL_NAME },
|
|
440
|
+
disableCache: true,
|
|
441
|
+
},
|
|
442
|
+
signal: combinedSignal,
|
|
443
|
+
});
|
|
444
|
+
const toolBlock = extractToolUse(response);
|
|
445
|
+
const titleInput = toolBlock?.input as { title?: unknown } | undefined;
|
|
446
|
+
if (
|
|
447
|
+
toolBlock?.name === TITLE_TOOL_NAME &&
|
|
448
|
+
typeof titleInput?.title === "string"
|
|
449
|
+
) {
|
|
450
|
+
return normalizeTitle(titleInput.title);
|
|
451
|
+
}
|
|
452
|
+
// Provider ignored the forced tool (or the model emitted prose instead of
|
|
453
|
+
// calling it). Fall back to the response text — `normalizeTitle`'s prose
|
|
454
|
+
// guard rejects a ramble while keeping a compliant plain-text title.
|
|
455
|
+
return normalizeTitle(extractAllText(response));
|
|
456
|
+
} finally {
|
|
457
|
+
cleanup();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
399
461
|
function buildTitlePrompt(
|
|
400
462
|
context?: TitleContext,
|
|
401
463
|
userMessage?: string,
|
|
@@ -503,13 +565,100 @@ function truncateTitle(title: string): string {
|
|
|
503
565
|
function normalizeTitle(raw: string): string {
|
|
504
566
|
let title = raw.trim().replace(/^["']|["']$/g, "");
|
|
505
567
|
title = stripMarkdown(title);
|
|
506
|
-
title = stripThinkingTags(title);
|
|
568
|
+
title = stripThinkingTags(title).trim();
|
|
569
|
+
if (!title) return "";
|
|
570
|
+
// Reject outputs that are the model reasoning aloud or continuing the
|
|
571
|
+
// conversation instead of naming it (e.g. "I need to generate a…", "I'll
|
|
572
|
+
// work through these files…"). Callers fall back to a deterministic title.
|
|
573
|
+
if (looksLikeLeakedProse(title)) {
|
|
574
|
+
return "";
|
|
575
|
+
}
|
|
507
576
|
if (META_FAILURE_TITLES.has(title.toLowerCase())) {
|
|
508
577
|
return "";
|
|
509
578
|
}
|
|
510
579
|
return truncateTitle(title);
|
|
511
580
|
}
|
|
512
581
|
|
|
582
|
+
/** Reasoning/sentence openers that never start a legitimate topic title. */
|
|
583
|
+
const LEAKED_PROSE_PREFIXES = [
|
|
584
|
+
"i need to",
|
|
585
|
+
"i needed to",
|
|
586
|
+
"i should",
|
|
587
|
+
"i will",
|
|
588
|
+
"i'll",
|
|
589
|
+
"i can ",
|
|
590
|
+
"i can't",
|
|
591
|
+
"i cannot",
|
|
592
|
+
"i'm ",
|
|
593
|
+
"i am ",
|
|
594
|
+
"i've ",
|
|
595
|
+
"i have ",
|
|
596
|
+
"i'd ",
|
|
597
|
+
"i would",
|
|
598
|
+
"let me",
|
|
599
|
+
"looking at",
|
|
600
|
+
"based on",
|
|
601
|
+
"given the",
|
|
602
|
+
"to generate",
|
|
603
|
+
"to summarize",
|
|
604
|
+
"to title",
|
|
605
|
+
// Subject-led reasoning openers. A bare noun phrase ("The User Interface
|
|
606
|
+
// Redesign", "The Conversation API") is a valid title, so each subject only
|
|
607
|
+
// counts as leaked prose when a verb or possessive follows it — marking the
|
|
608
|
+
// output as a sentence rather than a topic.
|
|
609
|
+
"the user wants",
|
|
610
|
+
"the user asked",
|
|
611
|
+
"the user is",
|
|
612
|
+
"the user wanted",
|
|
613
|
+
"the user needs",
|
|
614
|
+
"the user said",
|
|
615
|
+
"the user has",
|
|
616
|
+
"the user would",
|
|
617
|
+
"the user's request",
|
|
618
|
+
"the conversation is",
|
|
619
|
+
"this conversation is",
|
|
620
|
+
"the conversation appears",
|
|
621
|
+
"the conversation seems",
|
|
622
|
+
"the conversation covers",
|
|
623
|
+
"the conversation discusses",
|
|
624
|
+
"the assistant should",
|
|
625
|
+
"the assistant is",
|
|
626
|
+
"the assistant wants",
|
|
627
|
+
"the assistant needs",
|
|
628
|
+
"the title should",
|
|
629
|
+
"the title is",
|
|
630
|
+
"the title would",
|
|
631
|
+
"the title for",
|
|
632
|
+
"here's ",
|
|
633
|
+
"here is ",
|
|
634
|
+
"here are ",
|
|
635
|
+
"sure,",
|
|
636
|
+
"okay,",
|
|
637
|
+
"ok,",
|
|
638
|
+
];
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Heuristic guard for title outputs that are clearly prose — the model
|
|
642
|
+
* reasoning aloud or replying to the conversation rather than naming it. A real
|
|
643
|
+
* title is a single-line short noun phrase, so we reject multi-line output,
|
|
644
|
+
* embedded transcript markers, leading reasoning openers, and sentence-shaped
|
|
645
|
+
* clauses. Deliberately tight: a false reject only costs a deterministic
|
|
646
|
+
* fallback title, while a false accept persists a broken one.
|
|
647
|
+
*/
|
|
648
|
+
function looksLikeLeakedProse(title: string): boolean {
|
|
649
|
+
if (/\n/.test(title)) return true;
|
|
650
|
+
if (/\b(?:user|assistant)\s*:/i.test(title)) return true;
|
|
651
|
+
const lower = title.toLowerCase();
|
|
652
|
+
if (LEAKED_PROSE_PREFIXES.some((prefix) => lower.startsWith(prefix))) {
|
|
653
|
+
return true;
|
|
654
|
+
}
|
|
655
|
+
// Sentence-shaped: terminal punctuation on a multi-word clause.
|
|
656
|
+
if (/[.?!]$/.test(title) && title.split(/\s+/).length > 5) {
|
|
657
|
+
return true;
|
|
658
|
+
}
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
661
|
+
|
|
513
662
|
/** Strip thinking tags so they don't bleed into generated titles. */
|
|
514
663
|
function stripThinkingTags(text: string): string {
|
|
515
664
|
return text
|
|
@@ -262,7 +262,14 @@ function getCached(
|
|
|
262
262
|
return backendCache.get(cacheKey(provider, model, extras));
|
|
263
263
|
}
|
|
264
264
|
|
|
265
|
-
|
|
265
|
+
/**
|
|
266
|
+
* The Gemini embedding options that change the output vector for identical
|
|
267
|
+
* input — task type and output dimensionality — rendered as stable cache-key
|
|
268
|
+
* fragments. Empty for a default Gemini config and for every non-Gemini
|
|
269
|
+
* provider. Part of the in-memory vector-cache identity here, and reused by the
|
|
270
|
+
* v3 section dense store so its persistent cache shares the same identity.
|
|
271
|
+
*/
|
|
272
|
+
export function geminiCacheExtras(config: AssistantConfig): string[] {
|
|
266
273
|
const extras: string[] = [];
|
|
267
274
|
if (config.memory.embeddings.geminiTaskType) {
|
|
268
275
|
extras.push(`task=${config.memory.embeddings.geminiTaskType}`);
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Shared dense-embedding cache over the `memory_embeddings` SQLite table
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
//
|
|
5
|
+
// A read/write pair that caches one dense vector keyed on
|
|
6
|
+
// `(targetType, targetId, provider, model)` alongside the content hash it was
|
|
7
|
+
// embedded from, so callers can skip the embedding-backend round-trip when an
|
|
8
|
+
// input's text is unchanged. The `embed_concept_page` job pioneered this
|
|
9
|
+
// pattern for whole-page bodies; this module factors out the generic mechanics
|
|
10
|
+
// — dim-match gating, legacy-null-hash handling, blob encode/decode, and the
|
|
11
|
+
// upsert on the unique key — so other embedders (e.g. the v3 section dense
|
|
12
|
+
// store) reuse one implementation instead of duplicating it.
|
|
13
|
+
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
|
|
16
|
+
import { and, eq } from "drizzle-orm";
|
|
17
|
+
|
|
18
|
+
import { getLogger } from "../util/logger.js";
|
|
19
|
+
import type { getDb } from "./db-connection.js";
|
|
20
|
+
import { blobToVector, vectorToBlob } from "./job-utils.js";
|
|
21
|
+
import { memoryEmbeddings } from "./schema.js";
|
|
22
|
+
|
|
23
|
+
const log = getLogger("memory-embedding-cache");
|
|
24
|
+
|
|
25
|
+
type MemoryDb = ReturnType<typeof getDb>;
|
|
26
|
+
|
|
27
|
+
/** Lookup key for {@link readEmbeddingCache}. */
|
|
28
|
+
export interface EmbeddingCacheKey {
|
|
29
|
+
targetType: string;
|
|
30
|
+
targetId: string;
|
|
31
|
+
provider: string;
|
|
32
|
+
model: string;
|
|
33
|
+
/** Configured embedding dimension; a row at a different size is a miss. */
|
|
34
|
+
expectedDim: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A cached dense vector plus the content hash it was embedded from. */
|
|
38
|
+
export interface EmbeddingCacheEntry {
|
|
39
|
+
dense: number[];
|
|
40
|
+
contentHash: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Look up a cached dense vector keyed on `(targetType, targetId, provider,
|
|
45
|
+
* model)`. Returns the row only when the persisted dimensions match
|
|
46
|
+
* `expectedDim` — a stale row from a previous `vectorSize` is treated as a miss
|
|
47
|
+
* so the caller re-embeds. A row with a null `contentHash` (legacy/corrupt) is
|
|
48
|
+
* likewise a miss rather than a key the caller could misalign against.
|
|
49
|
+
*/
|
|
50
|
+
export function readEmbeddingCache(
|
|
51
|
+
db: MemoryDb,
|
|
52
|
+
key: EmbeddingCacheKey,
|
|
53
|
+
): EmbeddingCacheEntry | null {
|
|
54
|
+
const row = db
|
|
55
|
+
.select({
|
|
56
|
+
vectorBlob: memoryEmbeddings.vectorBlob,
|
|
57
|
+
vectorJson: memoryEmbeddings.vectorJson,
|
|
58
|
+
dimensions: memoryEmbeddings.dimensions,
|
|
59
|
+
contentHash: memoryEmbeddings.contentHash,
|
|
60
|
+
})
|
|
61
|
+
.from(memoryEmbeddings)
|
|
62
|
+
.where(
|
|
63
|
+
and(
|
|
64
|
+
eq(memoryEmbeddings.targetType, key.targetType),
|
|
65
|
+
eq(memoryEmbeddings.targetId, key.targetId),
|
|
66
|
+
eq(memoryEmbeddings.provider, key.provider),
|
|
67
|
+
eq(memoryEmbeddings.model, key.model),
|
|
68
|
+
),
|
|
69
|
+
)
|
|
70
|
+
.get();
|
|
71
|
+
if (!row || row.dimensions !== key.expectedDim) return null;
|
|
72
|
+
if (row.contentHash === null) return null;
|
|
73
|
+
const dense = row.vectorBlob
|
|
74
|
+
? blobToVector(row.vectorBlob as Buffer)
|
|
75
|
+
: (JSON.parse(row.vectorJson!) as number[]);
|
|
76
|
+
return { dense, contentHash: row.contentHash };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Parameters for {@link writeEmbeddingCache}. */
|
|
80
|
+
export interface EmbeddingCacheWrite {
|
|
81
|
+
targetType: string;
|
|
82
|
+
targetId: string;
|
|
83
|
+
dense: number[];
|
|
84
|
+
contentHash: string;
|
|
85
|
+
provider: string;
|
|
86
|
+
model: string;
|
|
87
|
+
now: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Persist a freshly embedded dense vector, upserting on the
|
|
92
|
+
* `(targetType, targetId, provider, model)` unique key. Best-effort: a write
|
|
93
|
+
* failure is logged and swallowed so the caller's downstream write still runs.
|
|
94
|
+
*/
|
|
95
|
+
export function writeEmbeddingCache(
|
|
96
|
+
db: MemoryDb,
|
|
97
|
+
params: EmbeddingCacheWrite,
|
|
98
|
+
): void {
|
|
99
|
+
const { targetType, targetId, dense, contentHash, provider, model, now } =
|
|
100
|
+
params;
|
|
101
|
+
try {
|
|
102
|
+
const blobValue = vectorToBlob(dense);
|
|
103
|
+
db.insert(memoryEmbeddings)
|
|
104
|
+
.values({
|
|
105
|
+
id: randomUUID(),
|
|
106
|
+
targetType,
|
|
107
|
+
targetId,
|
|
108
|
+
provider,
|
|
109
|
+
model,
|
|
110
|
+
dimensions: dense.length,
|
|
111
|
+
vectorBlob: blobValue,
|
|
112
|
+
vectorJson: null,
|
|
113
|
+
contentHash,
|
|
114
|
+
createdAt: now,
|
|
115
|
+
updatedAt: now,
|
|
116
|
+
})
|
|
117
|
+
.onConflictDoUpdate({
|
|
118
|
+
target: [
|
|
119
|
+
memoryEmbeddings.targetType,
|
|
120
|
+
memoryEmbeddings.targetId,
|
|
121
|
+
memoryEmbeddings.provider,
|
|
122
|
+
memoryEmbeddings.model,
|
|
123
|
+
],
|
|
124
|
+
set: {
|
|
125
|
+
vectorBlob: blobValue,
|
|
126
|
+
vectorJson: null,
|
|
127
|
+
dimensions: dense.length,
|
|
128
|
+
contentHash,
|
|
129
|
+
updatedAt: now,
|
|
130
|
+
},
|
|
131
|
+
})
|
|
132
|
+
.run();
|
|
133
|
+
} catch (err) {
|
|
134
|
+
log.warn(
|
|
135
|
+
{ err, targetType, targetId },
|
|
136
|
+
"Failed to write embedding cache row",
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -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
|
+
});
|