@exulu/backend 5.23.0 → 5.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-K7CGLUW4.js → chunk-6HADZYCD.js} +8 -6
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-XEPIBTZT.js → convert-exulu-tools-to-ai-sdk-tools-RBKOADD7.js} +1 -1
- package/dist/index.cjs +128 -31
- package/dist/index.d.cts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +119 -24
- package/ee/workers.ts +16 -0
- package/package.json +1 -1
|
@@ -688,7 +688,7 @@ var ExuluTool = class _ExuluTool {
|
|
|
688
688
|
if (!agent) {
|
|
689
689
|
throw new Error("Agent not found.");
|
|
690
690
|
}
|
|
691
|
-
const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-
|
|
691
|
+
const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-RBKOADD7.js");
|
|
692
692
|
const tools = await convertExuluToolsToAiSdkTools2(
|
|
693
693
|
[this],
|
|
694
694
|
[],
|
|
@@ -12266,13 +12266,14 @@ function createRecallCollector(context, user, db) {
|
|
|
12266
12266
|
});
|
|
12267
12267
|
}
|
|
12268
12268
|
var cite = (s) => s.replace(/[{}",]/g, " ").replace(/\s+/g, " ").trim();
|
|
12269
|
+
function memoryPromptLine(m) {
|
|
12270
|
+
const who = m.createdBy ? `saved by ${m.createdBy.name}` : "saved earlier";
|
|
12271
|
+
const when = m.createdAt ? ` on ${m.createdAt.slice(0, 10)}` : "";
|
|
12272
|
+
return `- {item_name: "${cite(m.title)}", item_id: "${m.id}", context: "${m.contextId}"} ${m.information} (${who}${when}, ${m.rights_mode})`;
|
|
12273
|
+
}
|
|
12269
12274
|
function buildMemoryPromptBlock(memories) {
|
|
12270
12275
|
if (memories.length === 0) return "";
|
|
12271
|
-
const lines = memories.map(
|
|
12272
|
-
const who = m.createdBy ? `saved by ${m.createdBy.name}` : "saved earlier";
|
|
12273
|
-
const when = m.createdAt ? ` on ${m.createdAt.slice(0, 10)}` : "";
|
|
12274
|
-
return `- {item_name: "${cite(m.title)}", item_id: "${m.id}", context: "${m.contextId}"} ${m.information} (${who}${when}, ${m.rights_mode})`;
|
|
12275
|
-
});
|
|
12276
|
+
const lines = memories.map(memoryPromptLine);
|
|
12276
12277
|
return [
|
|
12277
12278
|
"Memories: facts people saved earlier for this assistant. Use them where relevant and cite each memory you rely on",
|
|
12278
12279
|
"with its citation object exactly as given, e.g. {item_name: <title>, item_id: <id>, context: <contextId>}",
|
|
@@ -19660,6 +19661,7 @@ export {
|
|
|
19660
19661
|
canEditMemory,
|
|
19661
19662
|
displayName,
|
|
19662
19663
|
createRecallCollector,
|
|
19664
|
+
memoryPromptLine,
|
|
19663
19665
|
buildMemoryPromptBlock,
|
|
19664
19666
|
normalizeRbac,
|
|
19665
19667
|
collectMemoryDecisions,
|
package/dist/index.cjs
CHANGED
|
@@ -11235,13 +11235,14 @@ function createRecallCollector(context, user, db2) {
|
|
|
11235
11235
|
loadUsers: (ids) => db2("users").whereIn("id", ids).select("id", "firstname", "lastname", "email")
|
|
11236
11236
|
});
|
|
11237
11237
|
}
|
|
11238
|
+
function memoryPromptLine(m) {
|
|
11239
|
+
const who = m.createdBy ? `saved by ${m.createdBy.name}` : "saved earlier";
|
|
11240
|
+
const when = m.createdAt ? ` on ${m.createdAt.slice(0, 10)}` : "";
|
|
11241
|
+
return `- {item_name: "${cite(m.title)}", item_id: "${m.id}", context: "${m.contextId}"} ${m.information} (${who}${when}, ${m.rights_mode})`;
|
|
11242
|
+
}
|
|
11238
11243
|
function buildMemoryPromptBlock(memories) {
|
|
11239
11244
|
if (memories.length === 0) return "";
|
|
11240
|
-
const lines = memories.map(
|
|
11241
|
-
const who = m.createdBy ? `saved by ${m.createdBy.name}` : "saved earlier";
|
|
11242
|
-
const when = m.createdAt ? ` on ${m.createdAt.slice(0, 10)}` : "";
|
|
11243
|
-
return `- {item_name: "${cite(m.title)}", item_id: "${m.id}", context: "${m.contextId}"} ${m.information} (${who}${when}, ${m.rights_mode})`;
|
|
11244
|
-
});
|
|
11245
|
+
const lines = memories.map(memoryPromptLine);
|
|
11245
11246
|
return [
|
|
11246
11247
|
"Memories: facts people saved earlier for this assistant. Use them where relevant and cite each memory you rely on",
|
|
11247
11248
|
"with its citation object exactly as given, e.g. {item_name: <title>, item_id: <id>, context: <contextId>}",
|
|
@@ -19037,10 +19038,10 @@ var init_doc_processor = __esm({
|
|
|
19037
19038
|
if (!fileType) {
|
|
19038
19039
|
throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
|
|
19039
19040
|
}
|
|
19040
|
-
const
|
|
19041
|
+
const UUID4 = (0, import_crypto4.randomUUID)();
|
|
19041
19042
|
let buffer;
|
|
19042
19043
|
if (Buffer.isBuffer(file)) {
|
|
19043
|
-
filePath = path3.join(tempDir, `${
|
|
19044
|
+
filePath = path3.join(tempDir, `${UUID4}.${fileType}`);
|
|
19044
19045
|
await fs2.promises.writeFile(filePath, file);
|
|
19045
19046
|
buffer = file;
|
|
19046
19047
|
} else {
|
|
@@ -19048,7 +19049,7 @@ var init_doc_processor = __esm({
|
|
|
19048
19049
|
if (filePath.startsWith("http")) {
|
|
19049
19050
|
const response = await fetch(filePath);
|
|
19050
19051
|
const array = await response.arrayBuffer();
|
|
19051
|
-
const tempFilePath = path3.join(tempDir, `${
|
|
19052
|
+
const tempFilePath = path3.join(tempDir, `${UUID4}.${fileType}`);
|
|
19052
19053
|
await fs2.promises.writeFile(tempFilePath, Buffer.from(array));
|
|
19053
19054
|
buffer = Buffer.from(array);
|
|
19054
19055
|
filePath = tempFilePath;
|
|
@@ -29760,6 +29761,7 @@ function previousUserTexts(messages) {
|
|
|
29760
29761
|
}
|
|
29761
29762
|
|
|
29762
29763
|
// src/exulu/memory/recall.ts
|
|
29764
|
+
var FOLLOW_UP_MAX_NEW = 5;
|
|
29763
29765
|
var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
|
|
29764
29766
|
async function recallMemories({ agent, contexts, query, user, db: db2, previousUserTurns }) {
|
|
29765
29767
|
if (!agent?.memory || !query) return { ...EMPTY3 };
|
|
@@ -29771,29 +29773,112 @@ async function recallMemories({ agent, contexts, query, user, db: db2, previousU
|
|
|
29771
29773
|
const config = resolveMemoryConfig(agent.memory_config);
|
|
29772
29774
|
const collector = createRecallCollector(context, user, db2);
|
|
29773
29775
|
if (!config.retrieval.enabled) return { collector, memoryItems: void 0, promptBlock: "" };
|
|
29776
|
+
const search = (text) => context.search({
|
|
29777
|
+
query: text,
|
|
29778
|
+
itemFilters: [],
|
|
29779
|
+
chunkFilters: [],
|
|
29780
|
+
method: "hybridSearch",
|
|
29781
|
+
sort: { field: "updatedAt", direction: "desc" },
|
|
29782
|
+
trigger: "agent",
|
|
29783
|
+
limit: config.retrieval.limit,
|
|
29784
|
+
page: 1,
|
|
29785
|
+
user,
|
|
29786
|
+
role: user?.role?.id
|
|
29787
|
+
});
|
|
29788
|
+
const memoryItems = [];
|
|
29789
|
+
const followUp = async (text) => {
|
|
29790
|
+
const q = (text ?? "").trim().slice(0, MAX_QUERY_CHARS);
|
|
29791
|
+
if (!q) return [];
|
|
29792
|
+
try {
|
|
29793
|
+
const known = new Set(collector.list().map((m) => m.id));
|
|
29794
|
+
const freshIds = /* @__PURE__ */ new Set();
|
|
29795
|
+
const fresh = ((await search(q))?.chunks ?? []).filter((c) => {
|
|
29796
|
+
if (!c.item_id || known.has(c.item_id)) return false;
|
|
29797
|
+
if (!freshIds.has(c.item_id) && freshIds.size >= FOLLOW_UP_MAX_NEW) return false;
|
|
29798
|
+
freshIds.add(c.item_id);
|
|
29799
|
+
return true;
|
|
29800
|
+
});
|
|
29801
|
+
if (fresh.length === 0) return [];
|
|
29802
|
+
await collector.addFromChunks(fresh, "follow_up");
|
|
29803
|
+
const added = collector.list().filter((m) => !known.has(m.id));
|
|
29804
|
+
const addedIds = new Set(added.map((m) => m.id));
|
|
29805
|
+
memoryItems.push(...fresh.filter((c) => addedIds.has(c.item_id)));
|
|
29806
|
+
return added;
|
|
29807
|
+
} catch (e) {
|
|
29808
|
+
console.warn(`[EXULU] memory: follow-up recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
29809
|
+
return [];
|
|
29810
|
+
}
|
|
29811
|
+
};
|
|
29774
29812
|
let result;
|
|
29775
29813
|
try {
|
|
29776
|
-
result = await
|
|
29777
|
-
query: buildRecallQuery(query, previousUserTurns ?? []),
|
|
29778
|
-
itemFilters: [],
|
|
29779
|
-
chunkFilters: [],
|
|
29780
|
-
method: "hybridSearch",
|
|
29781
|
-
sort: { field: "updatedAt", direction: "desc" },
|
|
29782
|
-
trigger: "agent",
|
|
29783
|
-
limit: config.retrieval.limit,
|
|
29784
|
-
page: 1,
|
|
29785
|
-
user,
|
|
29786
|
-
role: user?.role?.id
|
|
29787
|
-
});
|
|
29814
|
+
result = await search(buildRecallQuery(query, previousUserTurns ?? []));
|
|
29788
29815
|
} catch (e) {
|
|
29789
29816
|
console.warn(`[EXULU] memory: recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
29790
|
-
return { collector, memoryItems
|
|
29817
|
+
return { collector, memoryItems, promptBlock: "", followUp };
|
|
29791
29818
|
}
|
|
29792
29819
|
const chunks = result?.chunks ?? [];
|
|
29793
|
-
if (chunks.length === 0) return { collector, memoryItems
|
|
29820
|
+
if (chunks.length === 0) return { collector, memoryItems, promptBlock: "", followUp };
|
|
29794
29821
|
await collector.addFromChunks(chunks, "prefetch");
|
|
29795
|
-
|
|
29822
|
+
memoryItems.push(...chunks);
|
|
29823
|
+
return { collector, memoryItems, promptBlock: buildMemoryPromptBlock(collector.list()), followUp };
|
|
29824
|
+
}
|
|
29825
|
+
|
|
29826
|
+
// src/exulu/memory/recall-step.ts
|
|
29827
|
+
init_cjs_shims();
|
|
29828
|
+
init_recall_collector();
|
|
29829
|
+
var MAX_FOLLOW_UP_RECALLS = 4;
|
|
29830
|
+
var MAX_VALUE_CHARS = 200;
|
|
29831
|
+
function memoryRecallStep(recall, system) {
|
|
29832
|
+
if (!recall.followUp) return () => void 0;
|
|
29833
|
+
const followUp = recall.followUp;
|
|
29834
|
+
const found = [];
|
|
29835
|
+
const asked = /* @__PURE__ */ new Set();
|
|
29836
|
+
let lastStepSeen = 0;
|
|
29837
|
+
return async ({ steps }) => {
|
|
29838
|
+
const all = steps ?? [];
|
|
29839
|
+
for (let i = lastStepSeen; i < all.length; i++) {
|
|
29840
|
+
if (asked.size >= MAX_FOLLOW_UP_RECALLS) break;
|
|
29841
|
+
const query = toolCallQuery(all[i]?.toolCalls);
|
|
29842
|
+
if (!query || asked.has(query.toLowerCase())) continue;
|
|
29843
|
+
asked.add(query.toLowerCase());
|
|
29844
|
+
found.push(...await followUp(query));
|
|
29845
|
+
}
|
|
29846
|
+
lastStepSeen = all.length;
|
|
29847
|
+
return found.length > 0 ? { system: system + "\n\n" + buildFollowUpBlock(found) } : void 0;
|
|
29848
|
+
};
|
|
29849
|
+
}
|
|
29850
|
+
function buildFollowUpBlock(memories) {
|
|
29851
|
+
return [
|
|
29852
|
+
"More memories, found for what you looked up while working on this answer. They count like the memories above:",
|
|
29853
|
+
"use them where relevant, cite them the same way, and where one of them corrects or narrows another memory for the",
|
|
29854
|
+
"exact product or case at hand, follow the more specific one.",
|
|
29855
|
+
...memories.map(memoryPromptLine)
|
|
29856
|
+
].join("\n");
|
|
29796
29857
|
}
|
|
29858
|
+
function toolCallQuery(toolCalls) {
|
|
29859
|
+
const words = [];
|
|
29860
|
+
const seen = /* @__PURE__ */ new Set();
|
|
29861
|
+
const add = (value) => {
|
|
29862
|
+
const v = value.trim();
|
|
29863
|
+
if (v.length < 2 || v.length > MAX_VALUE_CHARS || v.includes("\n")) return;
|
|
29864
|
+
if (UUID.test(v) || PATH.test(v)) return;
|
|
29865
|
+
for (const w of v.split(/\s+/)) {
|
|
29866
|
+
const key = w.toLowerCase();
|
|
29867
|
+
if (!w || seen.has(key)) continue;
|
|
29868
|
+
seen.add(key);
|
|
29869
|
+
words.push(w);
|
|
29870
|
+
}
|
|
29871
|
+
};
|
|
29872
|
+
const walk = (value, depth) => {
|
|
29873
|
+
if (typeof value === "string") add(value);
|
|
29874
|
+
else if (depth < 3 && Array.isArray(value)) value.forEach((v) => walk(v, depth + 1));
|
|
29875
|
+
else if (depth < 3 && value && typeof value === "object") Object.values(value).forEach((v) => walk(v, depth + 1));
|
|
29876
|
+
};
|
|
29877
|
+
for (const call2 of toolCalls ?? []) walk(call2?.input, 0);
|
|
29878
|
+
return words.join(" ").slice(0, MAX_QUERY_CHARS).trim();
|
|
29879
|
+
}
|
|
29880
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
29881
|
+
var PATH = /^\S*\/\S*$|^\S+\.[a-z0-9]{1,5}$/i;
|
|
29797
29882
|
|
|
29798
29883
|
// src/exulu/generate-stream.ts
|
|
29799
29884
|
init_public_surface();
|
|
@@ -30499,7 +30584,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30499
30584
|
// Stop after the image_generation tool fires — the widget IS the
|
|
30500
30585
|
// assistant's response, no follow-up text turn is wanted (same
|
|
30501
30586
|
// reasoning as question_ask: the UI artifact is the message).
|
|
30502
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30587
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30503
30588
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30504
30589
|
});
|
|
30505
30590
|
console.log("[EXULU] Output: " + JSON.stringify(output, null, 2));
|
|
@@ -30578,7 +30663,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30578
30663
|
}),
|
|
30579
30664
|
maxRetries: 2,
|
|
30580
30665
|
tools,
|
|
30581
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30666
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30582
30667
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30583
30668
|
});
|
|
30584
30669
|
if (statistics) {
|
|
@@ -30947,7 +31032,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30947
31032
|
// Log only — throwing here crashed the process (see stream-error.ts).
|
|
30948
31033
|
onError: onChatStreamError,
|
|
30949
31034
|
// todo allow configuring the step budget per skill
|
|
30950
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
31035
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30951
31036
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30952
31037
|
});
|
|
30953
31038
|
return {
|
|
@@ -34371,6 +34456,18 @@ var processUiMessagesFlow = async ({
|
|
|
34371
34456
|
},
|
|
34372
34457
|
onFinish: async ({ messages }) => {
|
|
34373
34458
|
const metadata = messages[messages.length - 1]?.metadata;
|
|
34459
|
+
if (agent.memory && messages[messages.length - 1]?.id) {
|
|
34460
|
+
const { db: usageDb } = await postgresClient();
|
|
34461
|
+
await recordMemoryUsage({
|
|
34462
|
+
db: usageDb,
|
|
34463
|
+
recall: result.recall,
|
|
34464
|
+
contextId: agent.memory,
|
|
34465
|
+
agentId: agent.id,
|
|
34466
|
+
session: sessionId ?? null,
|
|
34467
|
+
messageId: messages[messages.length - 1].id,
|
|
34468
|
+
userId: typeof user?.id === "number" ? user.id : null
|
|
34469
|
+
});
|
|
34470
|
+
}
|
|
34374
34471
|
console.log("[EXULU] Stream finished with messages:", messages);
|
|
34375
34472
|
console.log("[EXULU] Stream metadata", metadata);
|
|
34376
34473
|
await Promise.all([
|
|
@@ -36758,7 +36855,7 @@ var epochMs = (d) => {
|
|
|
36758
36855
|
const date = d instanceof Date ? d : typeof d === "string" || typeof d === "number" ? new Date(d) : null;
|
|
36759
36856
|
return date && Number.isFinite(date.getTime()) ? date.getTime() : null;
|
|
36760
36857
|
};
|
|
36761
|
-
var
|
|
36858
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
36762
36859
|
var clamp = (limit, fallback, max) => {
|
|
36763
36860
|
const asked = limit == null ? NaN : Number(limit);
|
|
36764
36861
|
return Math.max(1, Math.min(Number.isFinite(asked) ? asked : fallback, max));
|
|
@@ -36887,7 +36984,7 @@ async function contextMapItem({
|
|
|
36887
36984
|
user,
|
|
36888
36985
|
itemId
|
|
36889
36986
|
}) {
|
|
36890
|
-
if (!
|
|
36987
|
+
if (!UUID2.test(itemId)) return null;
|
|
36891
36988
|
const items = getTableName(context.id);
|
|
36892
36989
|
const table = convertContextToTableDefinition(context);
|
|
36893
36990
|
let q = db2(`${items} as items`).where("items.id", itemId).whereRaw("items.archived IS NOT TRUE");
|
|
@@ -36926,7 +37023,7 @@ async function contextMapEdges({
|
|
|
36926
37023
|
mode = "DOCUMENTS",
|
|
36927
37024
|
limit
|
|
36928
37025
|
}) {
|
|
36929
|
-
if (!
|
|
37026
|
+
if (!UUID2.test(String(nodeId ?? ""))) return [];
|
|
36930
37027
|
const chunks = getChunksTableName(context.id);
|
|
36931
37028
|
const items = getTableName(context.id);
|
|
36932
37029
|
if (!await db2.schema.hasTable(chunks)) return [];
|
|
@@ -44621,7 +44718,7 @@ var import_multer = __toESM(require("multer"), 1);
|
|
|
44621
44718
|
init_cjs_shims();
|
|
44622
44719
|
var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
|
|
44623
44720
|
var LOG_PREFIX3 = "[EXULU-CHANNEL]";
|
|
44624
|
-
var
|
|
44721
|
+
var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
44625
44722
|
var RATE_WINDOW_MS2 = 6e4;
|
|
44626
44723
|
var RATE_MAX_REQUESTS2 = 300;
|
|
44627
44724
|
var rateWindowStart2 = 0;
|
|
@@ -44679,7 +44776,7 @@ var createChannelWebhookHandler = (deps) => async (req, res) => {
|
|
|
44679
44776
|
return;
|
|
44680
44777
|
}
|
|
44681
44778
|
const channelId = String(req.params?.channelId ?? "");
|
|
44682
|
-
if (!
|
|
44779
|
+
if (!UUID3.test(channelId)) {
|
|
44683
44780
|
res.status(404).json({ detail: "not found" });
|
|
44684
44781
|
return;
|
|
44685
44782
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -2158,7 +2158,7 @@ declare function postgresClient(): Promise<{
|
|
|
2158
2158
|
db: Knex;
|
|
2159
2159
|
}>;
|
|
2160
2160
|
|
|
2161
|
-
type RecallSource = "prefetch" | "knowledge_search";
|
|
2161
|
+
type RecallSource = "prefetch" | "knowledge_search" | "follow_up";
|
|
2162
2162
|
type MemoryItemRow = {
|
|
2163
2163
|
id: string;
|
|
2164
2164
|
name?: string | null;
|
|
@@ -2212,8 +2212,20 @@ declare class RecallCollector {
|
|
|
2212
2212
|
|
|
2213
2213
|
type RecallResult = {
|
|
2214
2214
|
collector: RecallCollector | undefined;
|
|
2215
|
+
/**
|
|
2216
|
+
* The recalled chunks, handed to the knowledge search so it can weigh them
|
|
2217
|
+
* against its own results. While recall is on this is ONE array for the whole
|
|
2218
|
+
* turn: `followUp` appends to it, so a search later in the turn sees what was
|
|
2219
|
+
* recalled in between.
|
|
2220
|
+
*/
|
|
2215
2221
|
memoryItems: VectorSearchChunkResult[] | undefined;
|
|
2216
2222
|
promptBlock: string;
|
|
2223
|
+
/**
|
|
2224
|
+
* Searches the memory again during the turn (recall-step.ts) and returns the
|
|
2225
|
+
* memories that were not recalled before. Same context, user and limit as the
|
|
2226
|
+
* first search. Absent when recall is off.
|
|
2227
|
+
*/
|
|
2228
|
+
followUp?: (query: string) => Promise<RecalledMemory[]>;
|
|
2217
2229
|
};
|
|
2218
2230
|
/**
|
|
2219
2231
|
* Memory pre-fetch shared by generateSync and generateStream (spec §3.1):
|
package/dist/index.d.ts
CHANGED
|
@@ -2158,7 +2158,7 @@ declare function postgresClient(): Promise<{
|
|
|
2158
2158
|
db: Knex;
|
|
2159
2159
|
}>;
|
|
2160
2160
|
|
|
2161
|
-
type RecallSource = "prefetch" | "knowledge_search";
|
|
2161
|
+
type RecallSource = "prefetch" | "knowledge_search" | "follow_up";
|
|
2162
2162
|
type MemoryItemRow = {
|
|
2163
2163
|
id: string;
|
|
2164
2164
|
name?: string | null;
|
|
@@ -2212,8 +2212,20 @@ declare class RecallCollector {
|
|
|
2212
2212
|
|
|
2213
2213
|
type RecallResult = {
|
|
2214
2214
|
collector: RecallCollector | undefined;
|
|
2215
|
+
/**
|
|
2216
|
+
* The recalled chunks, handed to the knowledge search so it can weigh them
|
|
2217
|
+
* against its own results. While recall is on this is ONE array for the whole
|
|
2218
|
+
* turn: `followUp` appends to it, so a search later in the turn sees what was
|
|
2219
|
+
* recalled in between.
|
|
2220
|
+
*/
|
|
2215
2221
|
memoryItems: VectorSearchChunkResult[] | undefined;
|
|
2216
2222
|
promptBlock: string;
|
|
2223
|
+
/**
|
|
2224
|
+
* Searches the memory again during the turn (recall-step.ts) and returns the
|
|
2225
|
+
* memories that were not recalled before. Same context, user and limit as the
|
|
2226
|
+
* first search. Absent when recall is off.
|
|
2227
|
+
*/
|
|
2228
|
+
followUp?: (query: string) => Promise<RecalledMemory[]>;
|
|
2217
2229
|
};
|
|
2218
2230
|
/**
|
|
2219
2231
|
* Memory pre-fetch shared by generateSync and generateStream (spec §3.1):
|
package/dist/index.js
CHANGED
|
@@ -200,6 +200,7 @@ import {
|
|
|
200
200
|
mayUseGenericS3Route,
|
|
201
201
|
maybePruneJobResults,
|
|
202
202
|
meanVector,
|
|
203
|
+
memoryPromptLine,
|
|
203
204
|
microCall,
|
|
204
205
|
microCallProviderOptions,
|
|
205
206
|
normalizeLayout,
|
|
@@ -279,7 +280,7 @@ import {
|
|
|
279
280
|
willEmbedOnQueue,
|
|
280
281
|
withRunSession,
|
|
281
282
|
workflowTemplatesSchema
|
|
282
|
-
} from "./chunk-
|
|
283
|
+
} from "./chunk-6HADZYCD.js";
|
|
283
284
|
import {
|
|
284
285
|
LITELLM_UI_PATH,
|
|
285
286
|
ResolveModelError,
|
|
@@ -6011,6 +6012,7 @@ function previousUserTexts(messages) {
|
|
|
6011
6012
|
}
|
|
6012
6013
|
|
|
6013
6014
|
// src/exulu/memory/recall.ts
|
|
6015
|
+
var FOLLOW_UP_MAX_NEW = 5;
|
|
6014
6016
|
var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
|
|
6015
6017
|
async function recallMemories({ agent, contexts, query, user, db, previousUserTurns }) {
|
|
6016
6018
|
if (!agent?.memory || !query) return { ...EMPTY3 };
|
|
@@ -6022,29 +6024,110 @@ async function recallMemories({ agent, contexts, query, user, db, previousUserTu
|
|
|
6022
6024
|
const config = resolveMemoryConfig(agent.memory_config);
|
|
6023
6025
|
const collector = createRecallCollector(context, user, db);
|
|
6024
6026
|
if (!config.retrieval.enabled) return { collector, memoryItems: void 0, promptBlock: "" };
|
|
6027
|
+
const search = (text) => context.search({
|
|
6028
|
+
query: text,
|
|
6029
|
+
itemFilters: [],
|
|
6030
|
+
chunkFilters: [],
|
|
6031
|
+
method: "hybridSearch",
|
|
6032
|
+
sort: { field: "updatedAt", direction: "desc" },
|
|
6033
|
+
trigger: "agent",
|
|
6034
|
+
limit: config.retrieval.limit,
|
|
6035
|
+
page: 1,
|
|
6036
|
+
user,
|
|
6037
|
+
role: user?.role?.id
|
|
6038
|
+
});
|
|
6039
|
+
const memoryItems = [];
|
|
6040
|
+
const followUp = async (text) => {
|
|
6041
|
+
const q = (text ?? "").trim().slice(0, MAX_QUERY_CHARS);
|
|
6042
|
+
if (!q) return [];
|
|
6043
|
+
try {
|
|
6044
|
+
const known = new Set(collector.list().map((m) => m.id));
|
|
6045
|
+
const freshIds = /* @__PURE__ */ new Set();
|
|
6046
|
+
const fresh = ((await search(q))?.chunks ?? []).filter((c) => {
|
|
6047
|
+
if (!c.item_id || known.has(c.item_id)) return false;
|
|
6048
|
+
if (!freshIds.has(c.item_id) && freshIds.size >= FOLLOW_UP_MAX_NEW) return false;
|
|
6049
|
+
freshIds.add(c.item_id);
|
|
6050
|
+
return true;
|
|
6051
|
+
});
|
|
6052
|
+
if (fresh.length === 0) return [];
|
|
6053
|
+
await collector.addFromChunks(fresh, "follow_up");
|
|
6054
|
+
const added = collector.list().filter((m) => !known.has(m.id));
|
|
6055
|
+
const addedIds = new Set(added.map((m) => m.id));
|
|
6056
|
+
memoryItems.push(...fresh.filter((c) => addedIds.has(c.item_id)));
|
|
6057
|
+
return added;
|
|
6058
|
+
} catch (e) {
|
|
6059
|
+
console.warn(`[EXULU] memory: follow-up recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
6060
|
+
return [];
|
|
6061
|
+
}
|
|
6062
|
+
};
|
|
6025
6063
|
let result;
|
|
6026
6064
|
try {
|
|
6027
|
-
result = await
|
|
6028
|
-
query: buildRecallQuery(query, previousUserTurns ?? []),
|
|
6029
|
-
itemFilters: [],
|
|
6030
|
-
chunkFilters: [],
|
|
6031
|
-
method: "hybridSearch",
|
|
6032
|
-
sort: { field: "updatedAt", direction: "desc" },
|
|
6033
|
-
trigger: "agent",
|
|
6034
|
-
limit: config.retrieval.limit,
|
|
6035
|
-
page: 1,
|
|
6036
|
-
user,
|
|
6037
|
-
role: user?.role?.id
|
|
6038
|
-
});
|
|
6065
|
+
result = await search(buildRecallQuery(query, previousUserTurns ?? []));
|
|
6039
6066
|
} catch (e) {
|
|
6040
6067
|
console.warn(`[EXULU] memory: recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
6041
|
-
return { collector, memoryItems
|
|
6068
|
+
return { collector, memoryItems, promptBlock: "", followUp };
|
|
6042
6069
|
}
|
|
6043
6070
|
const chunks = result?.chunks ?? [];
|
|
6044
|
-
if (chunks.length === 0) return { collector, memoryItems
|
|
6071
|
+
if (chunks.length === 0) return { collector, memoryItems, promptBlock: "", followUp };
|
|
6045
6072
|
await collector.addFromChunks(chunks, "prefetch");
|
|
6046
|
-
|
|
6073
|
+
memoryItems.push(...chunks);
|
|
6074
|
+
return { collector, memoryItems, promptBlock: buildMemoryPromptBlock(collector.list()), followUp };
|
|
6075
|
+
}
|
|
6076
|
+
|
|
6077
|
+
// src/exulu/memory/recall-step.ts
|
|
6078
|
+
var MAX_FOLLOW_UP_RECALLS = 4;
|
|
6079
|
+
var MAX_VALUE_CHARS = 200;
|
|
6080
|
+
function memoryRecallStep(recall, system) {
|
|
6081
|
+
if (!recall.followUp) return () => void 0;
|
|
6082
|
+
const followUp = recall.followUp;
|
|
6083
|
+
const found = [];
|
|
6084
|
+
const asked = /* @__PURE__ */ new Set();
|
|
6085
|
+
let lastStepSeen = 0;
|
|
6086
|
+
return async ({ steps }) => {
|
|
6087
|
+
const all = steps ?? [];
|
|
6088
|
+
for (let i = lastStepSeen; i < all.length; i++) {
|
|
6089
|
+
if (asked.size >= MAX_FOLLOW_UP_RECALLS) break;
|
|
6090
|
+
const query = toolCallQuery(all[i]?.toolCalls);
|
|
6091
|
+
if (!query || asked.has(query.toLowerCase())) continue;
|
|
6092
|
+
asked.add(query.toLowerCase());
|
|
6093
|
+
found.push(...await followUp(query));
|
|
6094
|
+
}
|
|
6095
|
+
lastStepSeen = all.length;
|
|
6096
|
+
return found.length > 0 ? { system: system + "\n\n" + buildFollowUpBlock(found) } : void 0;
|
|
6097
|
+
};
|
|
6098
|
+
}
|
|
6099
|
+
function buildFollowUpBlock(memories) {
|
|
6100
|
+
return [
|
|
6101
|
+
"More memories, found for what you looked up while working on this answer. They count like the memories above:",
|
|
6102
|
+
"use them where relevant, cite them the same way, and where one of them corrects or narrows another memory for the",
|
|
6103
|
+
"exact product or case at hand, follow the more specific one.",
|
|
6104
|
+
...memories.map(memoryPromptLine)
|
|
6105
|
+
].join("\n");
|
|
6106
|
+
}
|
|
6107
|
+
function toolCallQuery(toolCalls) {
|
|
6108
|
+
const words = [];
|
|
6109
|
+
const seen = /* @__PURE__ */ new Set();
|
|
6110
|
+
const add = (value) => {
|
|
6111
|
+
const v = value.trim();
|
|
6112
|
+
if (v.length < 2 || v.length > MAX_VALUE_CHARS || v.includes("\n")) return;
|
|
6113
|
+
if (UUID.test(v) || PATH.test(v)) return;
|
|
6114
|
+
for (const w of v.split(/\s+/)) {
|
|
6115
|
+
const key = w.toLowerCase();
|
|
6116
|
+
if (!w || seen.has(key)) continue;
|
|
6117
|
+
seen.add(key);
|
|
6118
|
+
words.push(w);
|
|
6119
|
+
}
|
|
6120
|
+
};
|
|
6121
|
+
const walk = (value, depth) => {
|
|
6122
|
+
if (typeof value === "string") add(value);
|
|
6123
|
+
else if (depth < 3 && Array.isArray(value)) value.forEach((v) => walk(v, depth + 1));
|
|
6124
|
+
else if (depth < 3 && value && typeof value === "object") Object.values(value).forEach((v) => walk(v, depth + 1));
|
|
6125
|
+
};
|
|
6126
|
+
for (const call of toolCalls ?? []) walk(call?.input, 0);
|
|
6127
|
+
return words.join(" ").slice(0, MAX_QUERY_CHARS).trim();
|
|
6047
6128
|
}
|
|
6129
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6130
|
+
var PATH = /^\S*\/\S*$|^\S+\.[a-z0-9]{1,5}$/i;
|
|
6048
6131
|
|
|
6049
6132
|
// src/exulu/message-language.ts
|
|
6050
6133
|
import { francAll } from "franc";
|
|
@@ -6733,7 +6816,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
6733
6816
|
// Stop after the image_generation tool fires — the widget IS the
|
|
6734
6817
|
// assistant's response, no follow-up text turn is wanted (same
|
|
6735
6818
|
// reasoning as question_ask: the UI artifact is the message).
|
|
6736
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6819
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6737
6820
|
stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
|
|
6738
6821
|
});
|
|
6739
6822
|
console.log("[EXULU] Output: " + JSON.stringify(output, null, 2));
|
|
@@ -6812,7 +6895,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
6812
6895
|
}),
|
|
6813
6896
|
maxRetries: 2,
|
|
6814
6897
|
tools,
|
|
6815
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6898
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6816
6899
|
stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
|
|
6817
6900
|
});
|
|
6818
6901
|
if (statistics) {
|
|
@@ -7181,7 +7264,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
7181
7264
|
// Log only — throwing here crashed the process (see stream-error.ts).
|
|
7182
7265
|
onError: onChatStreamError,
|
|
7183
7266
|
// todo allow configuring the step budget per skill
|
|
7184
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
7267
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
7185
7268
|
stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
|
|
7186
7269
|
});
|
|
7187
7270
|
return {
|
|
@@ -10540,6 +10623,18 @@ var processUiMessagesFlow = async ({
|
|
|
10540
10623
|
},
|
|
10541
10624
|
onFinish: async ({ messages }) => {
|
|
10542
10625
|
const metadata = messages[messages.length - 1]?.metadata;
|
|
10626
|
+
if (agent.memory && messages[messages.length - 1]?.id) {
|
|
10627
|
+
const { db: usageDb } = await postgresClient();
|
|
10628
|
+
await recordMemoryUsage({
|
|
10629
|
+
db: usageDb,
|
|
10630
|
+
recall: result.recall,
|
|
10631
|
+
contextId: agent.memory,
|
|
10632
|
+
agentId: agent.id,
|
|
10633
|
+
session: sessionId ?? null,
|
|
10634
|
+
messageId: messages[messages.length - 1].id,
|
|
10635
|
+
userId: typeof user?.id === "number" ? user.id : null
|
|
10636
|
+
});
|
|
10637
|
+
}
|
|
10543
10638
|
console.log("[EXULU] Stream finished with messages:", messages);
|
|
10544
10639
|
console.log("[EXULU] Stream metadata", metadata);
|
|
10545
10640
|
await Promise.all([
|
|
@@ -12856,7 +12951,7 @@ var epochMs = (d) => {
|
|
|
12856
12951
|
const date = d instanceof Date ? d : typeof d === "string" || typeof d === "number" ? new Date(d) : null;
|
|
12857
12952
|
return date && Number.isFinite(date.getTime()) ? date.getTime() : null;
|
|
12858
12953
|
};
|
|
12859
|
-
var
|
|
12954
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12860
12955
|
var clamp = (limit, fallback, max) => {
|
|
12861
12956
|
const asked = limit == null ? NaN : Number(limit);
|
|
12862
12957
|
return Math.max(1, Math.min(Number.isFinite(asked) ? asked : fallback, max));
|
|
@@ -12985,7 +13080,7 @@ async function contextMapItem({
|
|
|
12985
13080
|
user,
|
|
12986
13081
|
itemId
|
|
12987
13082
|
}) {
|
|
12988
|
-
if (!
|
|
13083
|
+
if (!UUID2.test(itemId)) return null;
|
|
12989
13084
|
const items = getTableName(context.id);
|
|
12990
13085
|
const table = convertContextToTableDefinition(context);
|
|
12991
13086
|
let q = db(`${items} as items`).where("items.id", itemId).whereRaw("items.archived IS NOT TRUE");
|
|
@@ -13024,7 +13119,7 @@ async function contextMapEdges({
|
|
|
13024
13119
|
mode = "DOCUMENTS",
|
|
13025
13120
|
limit
|
|
13026
13121
|
}) {
|
|
13027
|
-
if (!
|
|
13122
|
+
if (!UUID2.test(String(nodeId ?? ""))) return [];
|
|
13028
13123
|
const chunks = getChunksTableName(context.id);
|
|
13029
13124
|
const items = getTableName(context.id);
|
|
13030
13125
|
if (!await db.schema.hasTable(chunks)) return [];
|
|
@@ -20540,7 +20635,7 @@ import multer from "multer";
|
|
|
20540
20635
|
// src/exulu/channels/webhook.ts
|
|
20541
20636
|
var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
|
|
20542
20637
|
var LOG_PREFIX3 = "[EXULU-CHANNEL]";
|
|
20543
|
-
var
|
|
20638
|
+
var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20544
20639
|
var RATE_WINDOW_MS2 = 6e4;
|
|
20545
20640
|
var RATE_MAX_REQUESTS2 = 300;
|
|
20546
20641
|
var rateWindowStart2 = 0;
|
|
@@ -20598,7 +20693,7 @@ var createChannelWebhookHandler = (deps) => async (req, res) => {
|
|
|
20598
20693
|
return;
|
|
20599
20694
|
}
|
|
20600
20695
|
const channelId = String(req.params?.channelId ?? "");
|
|
20601
|
-
if (!
|
|
20696
|
+
if (!UUID3.test(channelId)) {
|
|
20602
20697
|
res.status(404).json({ detail: "not found" });
|
|
20603
20698
|
return;
|
|
20604
20699
|
}
|
package/ee/workers.ts
CHANGED
|
@@ -37,6 +37,7 @@ import { sanitizeToolName } from "@SRC/utils/sanitize-tool-name.ts";
|
|
|
37
37
|
import type { ExuluConfig } from "@SRC/exulu/app/index.ts";
|
|
38
38
|
import { updateStatistic } from "@SRC/exulu/statistics";
|
|
39
39
|
import { saveChat, getAgentMessages, generateStream } from "@SRC/exulu/generate-stream";
|
|
40
|
+
import { recordMemoryUsage } from "@SRC/exulu/memory/usage";
|
|
40
41
|
import { exuluApp } from "@SRC/exulu/app/singleton";
|
|
41
42
|
import { handleEmailIntake } from "@SRC/exulu/email-inbound/intake";
|
|
42
43
|
import { createChannelWorkerEnv, runChannelMessageJob } from "@SRC/exulu/channels/worker";
|
|
@@ -1978,6 +1979,21 @@ export const processUiMessagesFlow = async ({
|
|
|
1978
1979
|
},
|
|
1979
1980
|
onFinish: async ({ messages }) => {
|
|
1980
1981
|
const metadata = messages[messages.length - 1]?.metadata as any;
|
|
1982
|
+
// Usage tracking, as on the chat route (routes.ts): one row per
|
|
1983
|
+
// memory recalled into this step's answer. Without it routine
|
|
1984
|
+
// runs never showed which memories they used.
|
|
1985
|
+
if (agent.memory && messages[messages.length - 1]?.id) {
|
|
1986
|
+
const { db: usageDb } = await postgresClient();
|
|
1987
|
+
await recordMemoryUsage({
|
|
1988
|
+
db: usageDb,
|
|
1989
|
+
recall: result.recall,
|
|
1990
|
+
contextId: agent.memory,
|
|
1991
|
+
agentId: agent.id,
|
|
1992
|
+
session: sessionId ?? null,
|
|
1993
|
+
messageId: messages[messages.length - 1]!.id,
|
|
1994
|
+
userId: typeof user?.id === "number" ? user.id : null,
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1981
1997
|
console.log("[EXULU] Stream finished with messages:", messages);
|
|
1982
1998
|
console.log("[EXULU] Stream metadata", metadata);
|
|
1983
1999
|
await Promise.all([
|