@exulu/backend 5.23.0 → 5.25.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 +206 -35
- package/dist/index.d.cts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +193 -28
- 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;
|
|
@@ -27921,6 +27922,49 @@ var markSessionSeenForViewer = async ({
|
|
|
27921
27922
|
// src/graphql/mutations/index.ts
|
|
27922
27923
|
init_skill_access();
|
|
27923
27924
|
init_write_grant();
|
|
27925
|
+
|
|
27926
|
+
// src/graphql/utilities/user-self-service.ts
|
|
27927
|
+
init_cjs_shims();
|
|
27928
|
+
var USER_SELF_SERVICE_FIELDS = [
|
|
27929
|
+
"favourite_agents",
|
|
27930
|
+
"favourite_projects",
|
|
27931
|
+
"favourite_contexts",
|
|
27932
|
+
"favourite_items",
|
|
27933
|
+
"favourite_artifacts",
|
|
27934
|
+
"recently_viewed_items",
|
|
27935
|
+
"personal_system_prompt"
|
|
27936
|
+
];
|
|
27937
|
+
var sameId = (a, b) => a !== void 0 && a !== null && b !== void 0 && b !== null && String(a) === String(b);
|
|
27938
|
+
var pinsOwnId = (where, userId) => {
|
|
27939
|
+
const filters = Array.isArray(where) ? where : [where];
|
|
27940
|
+
if (filters.length !== 1) return false;
|
|
27941
|
+
const filter = filters[0];
|
|
27942
|
+
if (!filter || typeof filter !== "object") return false;
|
|
27943
|
+
const columns = Object.keys(filter);
|
|
27944
|
+
if (columns.length !== 1 || columns[0] !== "id") return false;
|
|
27945
|
+
const operators = filter.id;
|
|
27946
|
+
if (!operators || typeof operators !== "object") return false;
|
|
27947
|
+
const names = Object.keys(operators);
|
|
27948
|
+
if (names.length !== 1 || names[0] !== "eq") return false;
|
|
27949
|
+
return sameId(operators.eq, userId);
|
|
27950
|
+
};
|
|
27951
|
+
var isOwnUserSelfServiceWrite = ({
|
|
27952
|
+
tableNamePlural,
|
|
27953
|
+
user,
|
|
27954
|
+
rowId,
|
|
27955
|
+
inputKeys,
|
|
27956
|
+
where
|
|
27957
|
+
}) => {
|
|
27958
|
+
if (tableNamePlural !== "users") return false;
|
|
27959
|
+
if (!user || user.type === "api" || user.via_companion === true) return false;
|
|
27960
|
+
if (!sameId(rowId, user.id)) return false;
|
|
27961
|
+
if (where !== void 0 && !pinsOwnId(where, user.id)) return false;
|
|
27962
|
+
if (!Array.isArray(inputKeys) || inputKeys.length === 0) return false;
|
|
27963
|
+
const allowed = USER_SELF_SERVICE_FIELDS;
|
|
27964
|
+
return inputKeys.every((key) => allowed.includes(key));
|
|
27965
|
+
};
|
|
27966
|
+
|
|
27967
|
+
// src/graphql/mutations/index.ts
|
|
27924
27968
|
var VALID_RIGHTS_MODES3 = ["private", "users", "roles", "teams", "public"];
|
|
27925
27969
|
var postprocessDeletion = async ({
|
|
27926
27970
|
table,
|
|
@@ -28103,7 +28147,7 @@ var buildTranscriptsSettingsInfo = async () => {
|
|
|
28103
28147
|
function createMutations(table, contexts, tools, config) {
|
|
28104
28148
|
const tableNamePlural = table.name.plural.toLowerCase();
|
|
28105
28149
|
const tableNameSingular = table.name.singular.toLowerCase();
|
|
28106
|
-
const validateWriteAccess = async (id, context) => {
|
|
28150
|
+
const validateWriteAccess = async (id, context, selfService) => {
|
|
28107
28151
|
try {
|
|
28108
28152
|
const { db: db2, user } = context;
|
|
28109
28153
|
if (user.via_companion === true) {
|
|
@@ -28115,7 +28159,13 @@ function createMutations(table, contexts, tools, config) {
|
|
|
28115
28159
|
if (user.super_admin === true) {
|
|
28116
28160
|
return true;
|
|
28117
28161
|
}
|
|
28118
|
-
|
|
28162
|
+
const ownSelfServiceWrite = !!selfService && isOwnUserSelfServiceWrite({
|
|
28163
|
+
tableNamePlural: table.name.plural,
|
|
28164
|
+
user,
|
|
28165
|
+
rowId: id,
|
|
28166
|
+
...selfService
|
|
28167
|
+
});
|
|
28168
|
+
if (!user.super_admin && !ownSelfServiceWrite && (table.name.plural === "agents" || table.name.plural === "workflow_templates" || table.name.plural === "variables" || table.name.plural === "users" || table.name.plural === "test_cases" || table.name.plural === "eval_sets" || table.name.plural === "eval_runs") && (!user.role || !(table.name.plural === "agents" && user.role.agents === "write") && !(table.name.plural === "workflow_templates" && user.role.workflows === "write") && !(table.name.plural === "variables" && user.role.variables === "write") && !(table.name.plural === "users" && user.role.users === "write") && !((table.name.plural === "test_cases" || table.name.plural === "eval_sets" || table.name.plural === "eval_runs") && user.role.evals === "write"))) {
|
|
28119
28169
|
console.error(
|
|
28120
28170
|
"Access control error: no role found for current user or no access to entity type."
|
|
28121
28171
|
);
|
|
@@ -28365,6 +28415,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
28365
28415
|
[`${tableNamePlural}UpdateOne`]: async (_, args, context, info) => {
|
|
28366
28416
|
const { db: db2, req } = context;
|
|
28367
28417
|
let { where, input } = args;
|
|
28418
|
+
const inputKeys = Object.keys(input ?? {});
|
|
28368
28419
|
await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
|
|
28369
28420
|
const rbacData = input.RBAC;
|
|
28370
28421
|
delete input.RBAC;
|
|
@@ -28389,7 +28440,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
28389
28440
|
if (!item) {
|
|
28390
28441
|
throw new Error("Record not found");
|
|
28391
28442
|
}
|
|
28392
|
-
await validateWriteAccess(item.id, context);
|
|
28443
|
+
await validateWriteAccess(item.id, context, { inputKeys, where: where ?? null });
|
|
28393
28444
|
if (table.type === "items") {
|
|
28394
28445
|
await assertItemFileKeysReadable({
|
|
28395
28446
|
input,
|
|
@@ -28471,7 +28522,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
28471
28522
|
throw new Error("Embedding generation cannot be requested through the companion server.");
|
|
28472
28523
|
}
|
|
28473
28524
|
await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
|
|
28474
|
-
await validateWriteAccess(id, context);
|
|
28525
|
+
await validateWriteAccess(id, context, { inputKeys: Object.keys(input ?? {}) });
|
|
28475
28526
|
if (table.type === "items") {
|
|
28476
28527
|
await assertItemFileKeysReadable({
|
|
28477
28528
|
input,
|
|
@@ -29760,6 +29811,7 @@ function previousUserTexts(messages) {
|
|
|
29760
29811
|
}
|
|
29761
29812
|
|
|
29762
29813
|
// src/exulu/memory/recall.ts
|
|
29814
|
+
var FOLLOW_UP_MAX_NEW = 5;
|
|
29763
29815
|
var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
|
|
29764
29816
|
async function recallMemories({ agent, contexts, query, user, db: db2, previousUserTurns }) {
|
|
29765
29817
|
if (!agent?.memory || !query) return { ...EMPTY3 };
|
|
@@ -29771,30 +29823,113 @@ async function recallMemories({ agent, contexts, query, user, db: db2, previousU
|
|
|
29771
29823
|
const config = resolveMemoryConfig(agent.memory_config);
|
|
29772
29824
|
const collector = createRecallCollector(context, user, db2);
|
|
29773
29825
|
if (!config.retrieval.enabled) return { collector, memoryItems: void 0, promptBlock: "" };
|
|
29826
|
+
const search = (text) => context.search({
|
|
29827
|
+
query: text,
|
|
29828
|
+
itemFilters: [],
|
|
29829
|
+
chunkFilters: [],
|
|
29830
|
+
method: "hybridSearch",
|
|
29831
|
+
sort: { field: "updatedAt", direction: "desc" },
|
|
29832
|
+
trigger: "agent",
|
|
29833
|
+
limit: config.retrieval.limit,
|
|
29834
|
+
page: 1,
|
|
29835
|
+
user,
|
|
29836
|
+
role: user?.role?.id
|
|
29837
|
+
});
|
|
29838
|
+
const memoryItems = [];
|
|
29839
|
+
const followUp = async (text) => {
|
|
29840
|
+
const q = (text ?? "").trim().slice(0, MAX_QUERY_CHARS);
|
|
29841
|
+
if (!q) return [];
|
|
29842
|
+
try {
|
|
29843
|
+
const known = new Set(collector.list().map((m) => m.id));
|
|
29844
|
+
const freshIds = /* @__PURE__ */ new Set();
|
|
29845
|
+
const fresh = ((await search(q))?.chunks ?? []).filter((c) => {
|
|
29846
|
+
if (!c.item_id || known.has(c.item_id)) return false;
|
|
29847
|
+
if (!freshIds.has(c.item_id) && freshIds.size >= FOLLOW_UP_MAX_NEW) return false;
|
|
29848
|
+
freshIds.add(c.item_id);
|
|
29849
|
+
return true;
|
|
29850
|
+
});
|
|
29851
|
+
if (fresh.length === 0) return [];
|
|
29852
|
+
await collector.addFromChunks(fresh, "follow_up");
|
|
29853
|
+
const added = collector.list().filter((m) => !known.has(m.id));
|
|
29854
|
+
const addedIds = new Set(added.map((m) => m.id));
|
|
29855
|
+
memoryItems.push(...fresh.filter((c) => addedIds.has(c.item_id)));
|
|
29856
|
+
return added;
|
|
29857
|
+
} catch (e) {
|
|
29858
|
+
console.warn(`[EXULU] memory: follow-up recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
29859
|
+
return [];
|
|
29860
|
+
}
|
|
29861
|
+
};
|
|
29774
29862
|
let result;
|
|
29775
29863
|
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
|
-
});
|
|
29864
|
+
result = await search(buildRecallQuery(query, previousUserTurns ?? []));
|
|
29788
29865
|
} catch (e) {
|
|
29789
29866
|
console.warn(`[EXULU] memory: recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
29790
|
-
return { collector, memoryItems
|
|
29867
|
+
return { collector, memoryItems, promptBlock: "", followUp };
|
|
29791
29868
|
}
|
|
29792
29869
|
const chunks = result?.chunks ?? [];
|
|
29793
|
-
if (chunks.length === 0) return { collector, memoryItems
|
|
29870
|
+
if (chunks.length === 0) return { collector, memoryItems, promptBlock: "", followUp };
|
|
29794
29871
|
await collector.addFromChunks(chunks, "prefetch");
|
|
29795
|
-
|
|
29872
|
+
memoryItems.push(...chunks);
|
|
29873
|
+
return { collector, memoryItems, promptBlock: buildMemoryPromptBlock(collector.list()), followUp };
|
|
29796
29874
|
}
|
|
29797
29875
|
|
|
29876
|
+
// src/exulu/memory/recall-step.ts
|
|
29877
|
+
init_cjs_shims();
|
|
29878
|
+
init_recall_collector();
|
|
29879
|
+
var MAX_FOLLOW_UP_RECALLS = 4;
|
|
29880
|
+
var MAX_VALUE_CHARS = 200;
|
|
29881
|
+
function memoryRecallStep(recall, system) {
|
|
29882
|
+
if (!recall.followUp) return () => void 0;
|
|
29883
|
+
const followUp = recall.followUp;
|
|
29884
|
+
const found = [];
|
|
29885
|
+
const asked = /* @__PURE__ */ new Set();
|
|
29886
|
+
let lastStepSeen = 0;
|
|
29887
|
+
return async ({ steps }) => {
|
|
29888
|
+
const all = steps ?? [];
|
|
29889
|
+
for (let i = lastStepSeen; i < all.length; i++) {
|
|
29890
|
+
if (asked.size >= MAX_FOLLOW_UP_RECALLS) break;
|
|
29891
|
+
const query = toolCallQuery(all[i]?.toolCalls);
|
|
29892
|
+
if (!query || asked.has(query.toLowerCase())) continue;
|
|
29893
|
+
asked.add(query.toLowerCase());
|
|
29894
|
+
found.push(...await followUp(query));
|
|
29895
|
+
}
|
|
29896
|
+
lastStepSeen = all.length;
|
|
29897
|
+
return found.length > 0 ? { system: system + "\n\n" + buildFollowUpBlock(found) } : void 0;
|
|
29898
|
+
};
|
|
29899
|
+
}
|
|
29900
|
+
function buildFollowUpBlock(memories) {
|
|
29901
|
+
return [
|
|
29902
|
+
"More memories, found for what you looked up while working on this answer. They count like the memories above:",
|
|
29903
|
+
"use them where relevant, cite them the same way, and where one of them corrects or narrows another memory for the",
|
|
29904
|
+
"exact product or case at hand, follow the more specific one.",
|
|
29905
|
+
...memories.map(memoryPromptLine)
|
|
29906
|
+
].join("\n");
|
|
29907
|
+
}
|
|
29908
|
+
function toolCallQuery(toolCalls) {
|
|
29909
|
+
const words = [];
|
|
29910
|
+
const seen = /* @__PURE__ */ new Set();
|
|
29911
|
+
const add = (value) => {
|
|
29912
|
+
const v = value.trim();
|
|
29913
|
+
if (v.length < 2 || v.length > MAX_VALUE_CHARS || v.includes("\n")) return;
|
|
29914
|
+
if (UUID.test(v) || PATH.test(v)) return;
|
|
29915
|
+
for (const w of v.split(/\s+/)) {
|
|
29916
|
+
const key = w.toLowerCase();
|
|
29917
|
+
if (!w || seen.has(key)) continue;
|
|
29918
|
+
seen.add(key);
|
|
29919
|
+
words.push(w);
|
|
29920
|
+
}
|
|
29921
|
+
};
|
|
29922
|
+
const walk = (value, depth) => {
|
|
29923
|
+
if (typeof value === "string") add(value);
|
|
29924
|
+
else if (depth < 3 && Array.isArray(value)) value.forEach((v) => walk(v, depth + 1));
|
|
29925
|
+
else if (depth < 3 && value && typeof value === "object") Object.values(value).forEach((v) => walk(v, depth + 1));
|
|
29926
|
+
};
|
|
29927
|
+
for (const call2 of toolCalls ?? []) walk(call2?.input, 0);
|
|
29928
|
+
return words.join(" ").slice(0, MAX_QUERY_CHARS).trim();
|
|
29929
|
+
}
|
|
29930
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
29931
|
+
var PATH = /^\S*\/\S*$|^\S+\.[a-z0-9]{1,5}$/i;
|
|
29932
|
+
|
|
29798
29933
|
// src/exulu/generate-stream.ts
|
|
29799
29934
|
init_public_surface();
|
|
29800
29935
|
|
|
@@ -30499,7 +30634,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30499
30634
|
// Stop after the image_generation tool fires — the widget IS the
|
|
30500
30635
|
// assistant's response, no follow-up text turn is wanted (same
|
|
30501
30636
|
// reasoning as question_ask: the UI artifact is the message).
|
|
30502
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30637
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30503
30638
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30504
30639
|
});
|
|
30505
30640
|
console.log("[EXULU] Output: " + JSON.stringify(output, null, 2));
|
|
@@ -30578,7 +30713,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30578
30713
|
}),
|
|
30579
30714
|
maxRetries: 2,
|
|
30580
30715
|
tools,
|
|
30581
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30716
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30582
30717
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30583
30718
|
});
|
|
30584
30719
|
if (statistics) {
|
|
@@ -30947,7 +31082,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30947
31082
|
// Log only — throwing here crashed the process (see stream-error.ts).
|
|
30948
31083
|
onError: onChatStreamError,
|
|
30949
31084
|
// todo allow configuring the step budget per skill
|
|
30950
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
31085
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30951
31086
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30952
31087
|
});
|
|
30953
31088
|
return {
|
|
@@ -34371,6 +34506,18 @@ var processUiMessagesFlow = async ({
|
|
|
34371
34506
|
},
|
|
34372
34507
|
onFinish: async ({ messages }) => {
|
|
34373
34508
|
const metadata = messages[messages.length - 1]?.metadata;
|
|
34509
|
+
if (agent.memory && messages[messages.length - 1]?.id) {
|
|
34510
|
+
const { db: usageDb } = await postgresClient();
|
|
34511
|
+
await recordMemoryUsage({
|
|
34512
|
+
db: usageDb,
|
|
34513
|
+
recall: result.recall,
|
|
34514
|
+
contextId: agent.memory,
|
|
34515
|
+
agentId: agent.id,
|
|
34516
|
+
session: sessionId ?? null,
|
|
34517
|
+
messageId: messages[messages.length - 1].id,
|
|
34518
|
+
userId: typeof user?.id === "number" ? user.id : null
|
|
34519
|
+
});
|
|
34520
|
+
}
|
|
34374
34521
|
console.log("[EXULU] Stream finished with messages:", messages);
|
|
34375
34522
|
console.log("[EXULU] Stream metadata", metadata);
|
|
34376
34523
|
await Promise.all([
|
|
@@ -34594,6 +34741,20 @@ var mapRoutineRunRow = (row, routineById) => {
|
|
|
34594
34741
|
};
|
|
34595
34742
|
};
|
|
34596
34743
|
|
|
34744
|
+
// src/exulu/routines/run-for-session.ts
|
|
34745
|
+
init_cjs_shims();
|
|
34746
|
+
async function routineRunForSession(db2, sessionId, routineById) {
|
|
34747
|
+
const readableIds = [...routineById.keys()];
|
|
34748
|
+
if (!sessionId || readableIds.length === 0) return null;
|
|
34749
|
+
const row = await db2("job_results").where({ session: sessionId, type: "workflow" }).whereIn("workflow", readableIds).orderBy("createdAt", "desc").first();
|
|
34750
|
+
if (!row) return null;
|
|
34751
|
+
const routine = await loadRoutineWorkStatusConfig(db2, row.workflow);
|
|
34752
|
+
return {
|
|
34753
|
+
run: mapRoutineRunRow(row, routineById),
|
|
34754
|
+
work_statuses: routine?.config ?? { statuses: [], default: null }
|
|
34755
|
+
};
|
|
34756
|
+
}
|
|
34757
|
+
|
|
34597
34758
|
// src/graphql/schemas/index.ts
|
|
34598
34759
|
init_schemas();
|
|
34599
34760
|
init_entitlements();
|
|
@@ -36758,7 +36919,7 @@ var epochMs = (d) => {
|
|
|
36758
36919
|
const date = d instanceof Date ? d : typeof d === "string" || typeof d === "number" ? new Date(d) : null;
|
|
36759
36920
|
return date && Number.isFinite(date.getTime()) ? date.getTime() : null;
|
|
36760
36921
|
};
|
|
36761
|
-
var
|
|
36922
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
36762
36923
|
var clamp = (limit, fallback, max) => {
|
|
36763
36924
|
const asked = limit == null ? NaN : Number(limit);
|
|
36764
36925
|
return Math.max(1, Math.min(Number.isFinite(asked) ? asked : fallback, max));
|
|
@@ -36887,7 +37048,7 @@ async function contextMapItem({
|
|
|
36887
37048
|
user,
|
|
36888
37049
|
itemId
|
|
36889
37050
|
}) {
|
|
36890
|
-
if (!
|
|
37051
|
+
if (!UUID2.test(itemId)) return null;
|
|
36891
37052
|
const items = getTableName(context.id);
|
|
36892
37053
|
const table = convertContextToTableDefinition(context);
|
|
36893
37054
|
let q = db2(`${items} as items`).where("items.id", itemId).whereRaw("items.archived IS NOT TRUE");
|
|
@@ -36926,7 +37087,7 @@ async function contextMapEdges({
|
|
|
36926
37087
|
mode = "DOCUMENTS",
|
|
36927
37088
|
limit
|
|
36928
37089
|
}) {
|
|
36929
|
-
if (!
|
|
37090
|
+
if (!UUID2.test(String(nodeId ?? ""))) return [];
|
|
36930
37091
|
const chunks = getChunksTableName(context.id);
|
|
36931
37092
|
const items = getTableName(context.id);
|
|
36932
37093
|
if (!await db2.schema.hasTable(chunks)) return [];
|
|
@@ -38296,6 +38457,7 @@ type PageInfo {
|
|
|
38296
38457
|
typeDefs += `
|
|
38297
38458
|
routineRuns(page: Int, limit: Int, workflow: ID, states: [String!], triggers: [String!], from: Date, to: Date, search: String, needsAttention: Boolean, workStatuses: [String!], workStatusOpen: Boolean): RoutineRunPage
|
|
38298
38459
|
routineRunsNeedingAttentionCount: Float!
|
|
38460
|
+
routineRunForSession(session: ID!): RoutineRunForSession
|
|
38299
38461
|
`;
|
|
38300
38462
|
typeDefs += `
|
|
38301
38463
|
queue(queue: QueueEnum!): QueueResult
|
|
@@ -38585,6 +38747,11 @@ type RoutineRunPage {
|
|
|
38585
38747
|
items: [RoutineRun!]!
|
|
38586
38748
|
total: Float!
|
|
38587
38749
|
}
|
|
38750
|
+
|
|
38751
|
+
type RoutineRunForSession {
|
|
38752
|
+
run: RoutineRun!
|
|
38753
|
+
work_statuses: JSON!
|
|
38754
|
+
}
|
|
38588
38755
|
`;
|
|
38589
38756
|
modelDefs += `
|
|
38590
38757
|
type LiteLLMModel {
|
|
@@ -39213,6 +39380,10 @@ type EmbeddingModelOption {
|
|
|
39213
39380
|
total
|
|
39214
39381
|
};
|
|
39215
39382
|
};
|
|
39383
|
+
resolvers2.Query["routineRunForSession"] = async (_, args, context) => {
|
|
39384
|
+
const { db: db2 } = await postgresClient();
|
|
39385
|
+
return routineRunForSession(db2, args.session, await readableRoutines(db2, context.user));
|
|
39386
|
+
};
|
|
39216
39387
|
resolvers2.Query["routineRunsNeedingAttentionCount"] = async (_, args, context) => {
|
|
39217
39388
|
const user = context.user;
|
|
39218
39389
|
const { db: db2 } = await postgresClient();
|
|
@@ -44621,7 +44792,7 @@ var import_multer = __toESM(require("multer"), 1);
|
|
|
44621
44792
|
init_cjs_shims();
|
|
44622
44793
|
var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
|
|
44623
44794
|
var LOG_PREFIX3 = "[EXULU-CHANNEL]";
|
|
44624
|
-
var
|
|
44795
|
+
var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
44625
44796
|
var RATE_WINDOW_MS2 = 6e4;
|
|
44626
44797
|
var RATE_MAX_REQUESTS2 = 300;
|
|
44627
44798
|
var rateWindowStart2 = 0;
|
|
@@ -44679,7 +44850,7 @@ var createChannelWebhookHandler = (deps) => async (req, res) => {
|
|
|
44679
44850
|
return;
|
|
44680
44851
|
}
|
|
44681
44852
|
const channelId = String(req.params?.channelId ?? "");
|
|
44682
|
-
if (!
|
|
44853
|
+
if (!UUID3.test(channelId)) {
|
|
44683
44854
|
res.status(404).json({ detail: "not found" });
|
|
44684
44855
|
return;
|
|
44685
44856
|
}
|
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,
|
|
@@ -4245,6 +4246,46 @@ var markSessionSeenForViewer = async ({
|
|
|
4245
4246
|
return true;
|
|
4246
4247
|
};
|
|
4247
4248
|
|
|
4249
|
+
// src/graphql/utilities/user-self-service.ts
|
|
4250
|
+
var USER_SELF_SERVICE_FIELDS = [
|
|
4251
|
+
"favourite_agents",
|
|
4252
|
+
"favourite_projects",
|
|
4253
|
+
"favourite_contexts",
|
|
4254
|
+
"favourite_items",
|
|
4255
|
+
"favourite_artifacts",
|
|
4256
|
+
"recently_viewed_items",
|
|
4257
|
+
"personal_system_prompt"
|
|
4258
|
+
];
|
|
4259
|
+
var sameId = (a, b) => a !== void 0 && a !== null && b !== void 0 && b !== null && String(a) === String(b);
|
|
4260
|
+
var pinsOwnId = (where, userId) => {
|
|
4261
|
+
const filters = Array.isArray(where) ? where : [where];
|
|
4262
|
+
if (filters.length !== 1) return false;
|
|
4263
|
+
const filter = filters[0];
|
|
4264
|
+
if (!filter || typeof filter !== "object") return false;
|
|
4265
|
+
const columns = Object.keys(filter);
|
|
4266
|
+
if (columns.length !== 1 || columns[0] !== "id") return false;
|
|
4267
|
+
const operators = filter.id;
|
|
4268
|
+
if (!operators || typeof operators !== "object") return false;
|
|
4269
|
+
const names = Object.keys(operators);
|
|
4270
|
+
if (names.length !== 1 || names[0] !== "eq") return false;
|
|
4271
|
+
return sameId(operators.eq, userId);
|
|
4272
|
+
};
|
|
4273
|
+
var isOwnUserSelfServiceWrite = ({
|
|
4274
|
+
tableNamePlural,
|
|
4275
|
+
user,
|
|
4276
|
+
rowId,
|
|
4277
|
+
inputKeys,
|
|
4278
|
+
where
|
|
4279
|
+
}) => {
|
|
4280
|
+
if (tableNamePlural !== "users") return false;
|
|
4281
|
+
if (!user || user.type === "api" || user.via_companion === true) return false;
|
|
4282
|
+
if (!sameId(rowId, user.id)) return false;
|
|
4283
|
+
if (where !== void 0 && !pinsOwnId(where, user.id)) return false;
|
|
4284
|
+
if (!Array.isArray(inputKeys) || inputKeys.length === 0) return false;
|
|
4285
|
+
const allowed = USER_SELF_SERVICE_FIELDS;
|
|
4286
|
+
return inputKeys.every((key) => allowed.includes(key));
|
|
4287
|
+
};
|
|
4288
|
+
|
|
4248
4289
|
// src/graphql/mutations/index.ts
|
|
4249
4290
|
var VALID_RIGHTS_MODES3 = ["private", "users", "roles", "teams", "public"];
|
|
4250
4291
|
var postprocessDeletion = async ({
|
|
@@ -4428,7 +4469,7 @@ var buildTranscriptsSettingsInfo = async () => {
|
|
|
4428
4469
|
function createMutations(table, contexts, tools, config) {
|
|
4429
4470
|
const tableNamePlural = table.name.plural.toLowerCase();
|
|
4430
4471
|
const tableNameSingular = table.name.singular.toLowerCase();
|
|
4431
|
-
const validateWriteAccess = async (id, context) => {
|
|
4472
|
+
const validateWriteAccess = async (id, context, selfService) => {
|
|
4432
4473
|
try {
|
|
4433
4474
|
const { db, user } = context;
|
|
4434
4475
|
if (user.via_companion === true) {
|
|
@@ -4440,7 +4481,13 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4440
4481
|
if (user.super_admin === true) {
|
|
4441
4482
|
return true;
|
|
4442
4483
|
}
|
|
4443
|
-
|
|
4484
|
+
const ownSelfServiceWrite = !!selfService && isOwnUserSelfServiceWrite({
|
|
4485
|
+
tableNamePlural: table.name.plural,
|
|
4486
|
+
user,
|
|
4487
|
+
rowId: id,
|
|
4488
|
+
...selfService
|
|
4489
|
+
});
|
|
4490
|
+
if (!user.super_admin && !ownSelfServiceWrite && (table.name.plural === "agents" || table.name.plural === "workflow_templates" || table.name.plural === "variables" || table.name.plural === "users" || table.name.plural === "test_cases" || table.name.plural === "eval_sets" || table.name.plural === "eval_runs") && (!user.role || !(table.name.plural === "agents" && user.role.agents === "write") && !(table.name.plural === "workflow_templates" && user.role.workflows === "write") && !(table.name.plural === "variables" && user.role.variables === "write") && !(table.name.plural === "users" && user.role.users === "write") && !((table.name.plural === "test_cases" || table.name.plural === "eval_sets" || table.name.plural === "eval_runs") && user.role.evals === "write"))) {
|
|
4444
4491
|
console.error(
|
|
4445
4492
|
"Access control error: no role found for current user or no access to entity type."
|
|
4446
4493
|
);
|
|
@@ -4690,6 +4737,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4690
4737
|
[`${tableNamePlural}UpdateOne`]: async (_, args, context, info) => {
|
|
4691
4738
|
const { db, req } = context;
|
|
4692
4739
|
let { where, input } = args;
|
|
4740
|
+
const inputKeys = Object.keys(input ?? {});
|
|
4693
4741
|
await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
|
|
4694
4742
|
const rbacData = input.RBAC;
|
|
4695
4743
|
delete input.RBAC;
|
|
@@ -4714,7 +4762,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4714
4762
|
if (!item) {
|
|
4715
4763
|
throw new Error("Record not found");
|
|
4716
4764
|
}
|
|
4717
|
-
await validateWriteAccess(item.id, context);
|
|
4765
|
+
await validateWriteAccess(item.id, context, { inputKeys, where: where ?? null });
|
|
4718
4766
|
if (table.type === "items") {
|
|
4719
4767
|
await assertItemFileKeysReadable({
|
|
4720
4768
|
input,
|
|
@@ -4796,7 +4844,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4796
4844
|
throw new Error("Embedding generation cannot be requested through the companion server.");
|
|
4797
4845
|
}
|
|
4798
4846
|
await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
|
|
4799
|
-
await validateWriteAccess(id, context);
|
|
4847
|
+
await validateWriteAccess(id, context, { inputKeys: Object.keys(input ?? {}) });
|
|
4800
4848
|
if (table.type === "items") {
|
|
4801
4849
|
await assertItemFileKeysReadable({
|
|
4802
4850
|
input,
|
|
@@ -6011,6 +6059,7 @@ function previousUserTexts(messages) {
|
|
|
6011
6059
|
}
|
|
6012
6060
|
|
|
6013
6061
|
// src/exulu/memory/recall.ts
|
|
6062
|
+
var FOLLOW_UP_MAX_NEW = 5;
|
|
6014
6063
|
var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
|
|
6015
6064
|
async function recallMemories({ agent, contexts, query, user, db, previousUserTurns }) {
|
|
6016
6065
|
if (!agent?.memory || !query) return { ...EMPTY3 };
|
|
@@ -6022,29 +6071,110 @@ async function recallMemories({ agent, contexts, query, user, db, previousUserTu
|
|
|
6022
6071
|
const config = resolveMemoryConfig(agent.memory_config);
|
|
6023
6072
|
const collector = createRecallCollector(context, user, db);
|
|
6024
6073
|
if (!config.retrieval.enabled) return { collector, memoryItems: void 0, promptBlock: "" };
|
|
6074
|
+
const search = (text) => context.search({
|
|
6075
|
+
query: text,
|
|
6076
|
+
itemFilters: [],
|
|
6077
|
+
chunkFilters: [],
|
|
6078
|
+
method: "hybridSearch",
|
|
6079
|
+
sort: { field: "updatedAt", direction: "desc" },
|
|
6080
|
+
trigger: "agent",
|
|
6081
|
+
limit: config.retrieval.limit,
|
|
6082
|
+
page: 1,
|
|
6083
|
+
user,
|
|
6084
|
+
role: user?.role?.id
|
|
6085
|
+
});
|
|
6086
|
+
const memoryItems = [];
|
|
6087
|
+
const followUp = async (text) => {
|
|
6088
|
+
const q = (text ?? "").trim().slice(0, MAX_QUERY_CHARS);
|
|
6089
|
+
if (!q) return [];
|
|
6090
|
+
try {
|
|
6091
|
+
const known = new Set(collector.list().map((m) => m.id));
|
|
6092
|
+
const freshIds = /* @__PURE__ */ new Set();
|
|
6093
|
+
const fresh = ((await search(q))?.chunks ?? []).filter((c) => {
|
|
6094
|
+
if (!c.item_id || known.has(c.item_id)) return false;
|
|
6095
|
+
if (!freshIds.has(c.item_id) && freshIds.size >= FOLLOW_UP_MAX_NEW) return false;
|
|
6096
|
+
freshIds.add(c.item_id);
|
|
6097
|
+
return true;
|
|
6098
|
+
});
|
|
6099
|
+
if (fresh.length === 0) return [];
|
|
6100
|
+
await collector.addFromChunks(fresh, "follow_up");
|
|
6101
|
+
const added = collector.list().filter((m) => !known.has(m.id));
|
|
6102
|
+
const addedIds = new Set(added.map((m) => m.id));
|
|
6103
|
+
memoryItems.push(...fresh.filter((c) => addedIds.has(c.item_id)));
|
|
6104
|
+
return added;
|
|
6105
|
+
} catch (e) {
|
|
6106
|
+
console.warn(`[EXULU] memory: follow-up recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
6107
|
+
return [];
|
|
6108
|
+
}
|
|
6109
|
+
};
|
|
6025
6110
|
let result;
|
|
6026
6111
|
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
|
-
});
|
|
6112
|
+
result = await search(buildRecallQuery(query, previousUserTurns ?? []));
|
|
6039
6113
|
} catch (e) {
|
|
6040
6114
|
console.warn(`[EXULU] memory: recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
6041
|
-
return { collector, memoryItems
|
|
6115
|
+
return { collector, memoryItems, promptBlock: "", followUp };
|
|
6042
6116
|
}
|
|
6043
6117
|
const chunks = result?.chunks ?? [];
|
|
6044
|
-
if (chunks.length === 0) return { collector, memoryItems
|
|
6118
|
+
if (chunks.length === 0) return { collector, memoryItems, promptBlock: "", followUp };
|
|
6045
6119
|
await collector.addFromChunks(chunks, "prefetch");
|
|
6046
|
-
|
|
6120
|
+
memoryItems.push(...chunks);
|
|
6121
|
+
return { collector, memoryItems, promptBlock: buildMemoryPromptBlock(collector.list()), followUp };
|
|
6122
|
+
}
|
|
6123
|
+
|
|
6124
|
+
// src/exulu/memory/recall-step.ts
|
|
6125
|
+
var MAX_FOLLOW_UP_RECALLS = 4;
|
|
6126
|
+
var MAX_VALUE_CHARS = 200;
|
|
6127
|
+
function memoryRecallStep(recall, system) {
|
|
6128
|
+
if (!recall.followUp) return () => void 0;
|
|
6129
|
+
const followUp = recall.followUp;
|
|
6130
|
+
const found = [];
|
|
6131
|
+
const asked = /* @__PURE__ */ new Set();
|
|
6132
|
+
let lastStepSeen = 0;
|
|
6133
|
+
return async ({ steps }) => {
|
|
6134
|
+
const all = steps ?? [];
|
|
6135
|
+
for (let i = lastStepSeen; i < all.length; i++) {
|
|
6136
|
+
if (asked.size >= MAX_FOLLOW_UP_RECALLS) break;
|
|
6137
|
+
const query = toolCallQuery(all[i]?.toolCalls);
|
|
6138
|
+
if (!query || asked.has(query.toLowerCase())) continue;
|
|
6139
|
+
asked.add(query.toLowerCase());
|
|
6140
|
+
found.push(...await followUp(query));
|
|
6141
|
+
}
|
|
6142
|
+
lastStepSeen = all.length;
|
|
6143
|
+
return found.length > 0 ? { system: system + "\n\n" + buildFollowUpBlock(found) } : void 0;
|
|
6144
|
+
};
|
|
6047
6145
|
}
|
|
6146
|
+
function buildFollowUpBlock(memories) {
|
|
6147
|
+
return [
|
|
6148
|
+
"More memories, found for what you looked up while working on this answer. They count like the memories above:",
|
|
6149
|
+
"use them where relevant, cite them the same way, and where one of them corrects or narrows another memory for the",
|
|
6150
|
+
"exact product or case at hand, follow the more specific one.",
|
|
6151
|
+
...memories.map(memoryPromptLine)
|
|
6152
|
+
].join("\n");
|
|
6153
|
+
}
|
|
6154
|
+
function toolCallQuery(toolCalls) {
|
|
6155
|
+
const words = [];
|
|
6156
|
+
const seen = /* @__PURE__ */ new Set();
|
|
6157
|
+
const add = (value) => {
|
|
6158
|
+
const v = value.trim();
|
|
6159
|
+
if (v.length < 2 || v.length > MAX_VALUE_CHARS || v.includes("\n")) return;
|
|
6160
|
+
if (UUID.test(v) || PATH.test(v)) return;
|
|
6161
|
+
for (const w of v.split(/\s+/)) {
|
|
6162
|
+
const key = w.toLowerCase();
|
|
6163
|
+
if (!w || seen.has(key)) continue;
|
|
6164
|
+
seen.add(key);
|
|
6165
|
+
words.push(w);
|
|
6166
|
+
}
|
|
6167
|
+
};
|
|
6168
|
+
const walk = (value, depth) => {
|
|
6169
|
+
if (typeof value === "string") add(value);
|
|
6170
|
+
else if (depth < 3 && Array.isArray(value)) value.forEach((v) => walk(v, depth + 1));
|
|
6171
|
+
else if (depth < 3 && value && typeof value === "object") Object.values(value).forEach((v) => walk(v, depth + 1));
|
|
6172
|
+
};
|
|
6173
|
+
for (const call of toolCalls ?? []) walk(call?.input, 0);
|
|
6174
|
+
return words.join(" ").slice(0, MAX_QUERY_CHARS).trim();
|
|
6175
|
+
}
|
|
6176
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6177
|
+
var PATH = /^\S*\/\S*$|^\S+\.[a-z0-9]{1,5}$/i;
|
|
6048
6178
|
|
|
6049
6179
|
// src/exulu/message-language.ts
|
|
6050
6180
|
import { francAll } from "franc";
|
|
@@ -6733,7 +6863,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
6733
6863
|
// Stop after the image_generation tool fires — the widget IS the
|
|
6734
6864
|
// assistant's response, no follow-up text turn is wanted (same
|
|
6735
6865
|
// reasoning as question_ask: the UI artifact is the message).
|
|
6736
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6866
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6737
6867
|
stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
|
|
6738
6868
|
});
|
|
6739
6869
|
console.log("[EXULU] Output: " + JSON.stringify(output, null, 2));
|
|
@@ -6812,7 +6942,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
6812
6942
|
}),
|
|
6813
6943
|
maxRetries: 2,
|
|
6814
6944
|
tools,
|
|
6815
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6945
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
6816
6946
|
stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
|
|
6817
6947
|
});
|
|
6818
6948
|
if (statistics) {
|
|
@@ -7181,7 +7311,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
7181
7311
|
// Log only — throwing here crashed the process (see stream-error.ts).
|
|
7182
7312
|
onError: onChatStreamError,
|
|
7183
7313
|
// todo allow configuring the step budget per skill
|
|
7184
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
7314
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
7185
7315
|
stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
|
|
7186
7316
|
});
|
|
7187
7317
|
return {
|
|
@@ -10540,6 +10670,18 @@ var processUiMessagesFlow = async ({
|
|
|
10540
10670
|
},
|
|
10541
10671
|
onFinish: async ({ messages }) => {
|
|
10542
10672
|
const metadata = messages[messages.length - 1]?.metadata;
|
|
10673
|
+
if (agent.memory && messages[messages.length - 1]?.id) {
|
|
10674
|
+
const { db: usageDb } = await postgresClient();
|
|
10675
|
+
await recordMemoryUsage({
|
|
10676
|
+
db: usageDb,
|
|
10677
|
+
recall: result.recall,
|
|
10678
|
+
contextId: agent.memory,
|
|
10679
|
+
agentId: agent.id,
|
|
10680
|
+
session: sessionId ?? null,
|
|
10681
|
+
messageId: messages[messages.length - 1].id,
|
|
10682
|
+
userId: typeof user?.id === "number" ? user.id : null
|
|
10683
|
+
});
|
|
10684
|
+
}
|
|
10543
10685
|
console.log("[EXULU] Stream finished with messages:", messages);
|
|
10544
10686
|
console.log("[EXULU] Stream metadata", metadata);
|
|
10545
10687
|
await Promise.all([
|
|
@@ -10757,6 +10899,19 @@ var mapRoutineRunRow = (row, routineById) => {
|
|
|
10757
10899
|
};
|
|
10758
10900
|
};
|
|
10759
10901
|
|
|
10902
|
+
// src/exulu/routines/run-for-session.ts
|
|
10903
|
+
async function routineRunForSession(db, sessionId, routineById) {
|
|
10904
|
+
const readableIds = [...routineById.keys()];
|
|
10905
|
+
if (!sessionId || readableIds.length === 0) return null;
|
|
10906
|
+
const row = await db("job_results").where({ session: sessionId, type: "workflow" }).whereIn("workflow", readableIds).orderBy("createdAt", "desc").first();
|
|
10907
|
+
if (!row) return null;
|
|
10908
|
+
const routine = await loadRoutineWorkStatusConfig(db, row.workflow);
|
|
10909
|
+
return {
|
|
10910
|
+
run: mapRoutineRunRow(row, routineById),
|
|
10911
|
+
work_statuses: routine?.config ?? { statuses: [], default: null }
|
|
10912
|
+
};
|
|
10913
|
+
}
|
|
10914
|
+
|
|
10760
10915
|
// src/graphql/schemas/index.ts
|
|
10761
10916
|
import "fs";
|
|
10762
10917
|
|
|
@@ -12856,7 +13011,7 @@ var epochMs = (d) => {
|
|
|
12856
13011
|
const date = d instanceof Date ? d : typeof d === "string" || typeof d === "number" ? new Date(d) : null;
|
|
12857
13012
|
return date && Number.isFinite(date.getTime()) ? date.getTime() : null;
|
|
12858
13013
|
};
|
|
12859
|
-
var
|
|
13014
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12860
13015
|
var clamp = (limit, fallback, max) => {
|
|
12861
13016
|
const asked = limit == null ? NaN : Number(limit);
|
|
12862
13017
|
return Math.max(1, Math.min(Number.isFinite(asked) ? asked : fallback, max));
|
|
@@ -12985,7 +13140,7 @@ async function contextMapItem({
|
|
|
12985
13140
|
user,
|
|
12986
13141
|
itemId
|
|
12987
13142
|
}) {
|
|
12988
|
-
if (!
|
|
13143
|
+
if (!UUID2.test(itemId)) return null;
|
|
12989
13144
|
const items = getTableName(context.id);
|
|
12990
13145
|
const table = convertContextToTableDefinition(context);
|
|
12991
13146
|
let q = db(`${items} as items`).where("items.id", itemId).whereRaw("items.archived IS NOT TRUE");
|
|
@@ -13024,7 +13179,7 @@ async function contextMapEdges({
|
|
|
13024
13179
|
mode = "DOCUMENTS",
|
|
13025
13180
|
limit
|
|
13026
13181
|
}) {
|
|
13027
|
-
if (!
|
|
13182
|
+
if (!UUID2.test(String(nodeId ?? ""))) return [];
|
|
13028
13183
|
const chunks = getChunksTableName(context.id);
|
|
13029
13184
|
const items = getTableName(context.id);
|
|
13030
13185
|
if (!await db.schema.hasTable(chunks)) return [];
|
|
@@ -14376,6 +14531,7 @@ type PageInfo {
|
|
|
14376
14531
|
typeDefs += `
|
|
14377
14532
|
routineRuns(page: Int, limit: Int, workflow: ID, states: [String!], triggers: [String!], from: Date, to: Date, search: String, needsAttention: Boolean, workStatuses: [String!], workStatusOpen: Boolean): RoutineRunPage
|
|
14378
14533
|
routineRunsNeedingAttentionCount: Float!
|
|
14534
|
+
routineRunForSession(session: ID!): RoutineRunForSession
|
|
14379
14535
|
`;
|
|
14380
14536
|
typeDefs += `
|
|
14381
14537
|
queue(queue: QueueEnum!): QueueResult
|
|
@@ -14665,6 +14821,11 @@ type RoutineRunPage {
|
|
|
14665
14821
|
items: [RoutineRun!]!
|
|
14666
14822
|
total: Float!
|
|
14667
14823
|
}
|
|
14824
|
+
|
|
14825
|
+
type RoutineRunForSession {
|
|
14826
|
+
run: RoutineRun!
|
|
14827
|
+
work_statuses: JSON!
|
|
14828
|
+
}
|
|
14668
14829
|
`;
|
|
14669
14830
|
modelDefs += `
|
|
14670
14831
|
type LiteLLMModel {
|
|
@@ -15293,6 +15454,10 @@ type EmbeddingModelOption {
|
|
|
15293
15454
|
total
|
|
15294
15455
|
};
|
|
15295
15456
|
};
|
|
15457
|
+
resolvers.Query["routineRunForSession"] = async (_, args, context) => {
|
|
15458
|
+
const { db } = await postgresClient();
|
|
15459
|
+
return routineRunForSession(db, args.session, await readableRoutines(db, context.user));
|
|
15460
|
+
};
|
|
15296
15461
|
resolvers.Query["routineRunsNeedingAttentionCount"] = async (_, args, context) => {
|
|
15297
15462
|
const user = context.user;
|
|
15298
15463
|
const { db } = await postgresClient();
|
|
@@ -20540,7 +20705,7 @@ import multer from "multer";
|
|
|
20540
20705
|
// src/exulu/channels/webhook.ts
|
|
20541
20706
|
var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
|
|
20542
20707
|
var LOG_PREFIX3 = "[EXULU-CHANNEL]";
|
|
20543
|
-
var
|
|
20708
|
+
var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20544
20709
|
var RATE_WINDOW_MS2 = 6e4;
|
|
20545
20710
|
var RATE_MAX_REQUESTS2 = 300;
|
|
20546
20711
|
var rateWindowStart2 = 0;
|
|
@@ -20598,7 +20763,7 @@ var createChannelWebhookHandler = (deps) => async (req, res) => {
|
|
|
20598
20763
|
return;
|
|
20599
20764
|
}
|
|
20600
20765
|
const channelId = String(req.params?.channelId ?? "");
|
|
20601
|
-
if (!
|
|
20766
|
+
if (!UUID3.test(channelId)) {
|
|
20602
20767
|
res.status(404).json({ detail: "not found" });
|
|
20603
20768
|
return;
|
|
20604
20769
|
}
|
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([
|