@exulu/backend 5.22.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-6OAYOFEY.js → chunk-6HADZYCD.js} +148 -135
- package/dist/{chunk-43QIPMLT.js → chunk-BFIDSFRQ.js} +132 -0
- package/dist/{chunk-Q4DFJFUI.js → chunk-DAVYWGEE.js} +17 -3
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-DAC4VCWO.js → convert-exulu-tools-to-ai-sdk-tools-RBKOADD7.js} +2 -2
- package/dist/{doc_processor-VCFQZ5WI.js → doc_processor-SR7ZCECL.js} +2 -2
- package/dist/index.cjs +751 -222
- package/dist/index.d.cts +18 -1
- package/dist/index.d.ts +18 -1
- package/dist/index.js +491 -107
- package/ee/python/documents/processing/doc_processor.presentations.test.ts +55 -0
- package/ee/python/documents/processing/doc_processor.ts +17 -2
- package/ee/workers.ts +16 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -802,7 +802,7 @@ function buildStsPolicy(bucket, userId, s3prefix) {
|
|
|
802
802
|
]
|
|
803
803
|
};
|
|
804
804
|
}
|
|
805
|
-
var import_express, import_client_s3, import_s3_request_presigner, import_client_sts,
|
|
805
|
+
var import_express, import_client_s3, import_s3_request_presigner, import_client_sts, import_node_crypto2, expiresIn, s3Client, getPresignedUrl, addGeneralPrefixToKey, addUserPrefixToKey, addBucketPrefixToKey, uploadFile, listS3ObjectsByPrefix, encodeS3KeyForCopySource, copyS3Object, getS3ObjectContent, getS3ObjectStream, getS3ObjectEtag, getS3ObjectMetadataStrict, getS3ObjectSize, getS3ObjectBytes, getS3ObjectTextExact, getS3ObjectBytesWithInfo, headS3ObjectExact, putS3ObjectTextExact, deleteS3Object, listS3ObjectsExact, deleteS3ObjectsExact, getS3SignedUploadUrl, createUppyRoutes;
|
|
806
806
|
var init_uppy = __esm({
|
|
807
807
|
"src/uppy/index.ts"() {
|
|
808
808
|
"use strict";
|
|
@@ -814,7 +814,7 @@ var init_uppy = __esm({
|
|
|
814
814
|
import_client_s3 = require("@aws-sdk/client-s3");
|
|
815
815
|
import_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
|
|
816
816
|
import_client_sts = require("@aws-sdk/client-sts");
|
|
817
|
-
|
|
817
|
+
import_node_crypto2 = require("crypto");
|
|
818
818
|
init_project_files();
|
|
819
819
|
init_keys();
|
|
820
820
|
expiresIn = 60 * 60 * 24 * 1;
|
|
@@ -1506,7 +1506,7 @@ var init_uppy = __esm({
|
|
|
1506
1506
|
contentType: params.type
|
|
1507
1507
|
};
|
|
1508
1508
|
};
|
|
1509
|
-
const generateS3Key2 = (filename) => `${(0,
|
|
1509
|
+
const generateS3Key2 = (filename) => `${(0, import_node_crypto2.randomUUID)()}-_EXULU_${filename}`;
|
|
1510
1510
|
const signOnServer = async (req, res, next) => {
|
|
1511
1511
|
if (!config.fileUploads) {
|
|
1512
1512
|
throw new Error("File uploads are not configured");
|
|
@@ -1591,7 +1591,7 @@ var init_uppy = __esm({
|
|
|
1591
1591
|
if (typeof type !== "string") {
|
|
1592
1592
|
return res.status(400).json({ error: "s3: content type must be a string" });
|
|
1593
1593
|
}
|
|
1594
|
-
const key = `${(0,
|
|
1594
|
+
const key = `${(0, import_node_crypto2.randomUUID)()}-_EXULU_${filename}`;
|
|
1595
1595
|
let fullKey = key;
|
|
1596
1596
|
console.log("[EXULU] global", req.headers.global);
|
|
1597
1597
|
if (!req.headers.global) {
|
|
@@ -4958,7 +4958,11 @@ var init_access_control = __esm({
|
|
|
4958
4958
|
);
|
|
4959
4959
|
return query.whereRaw("1 = 0");
|
|
4960
4960
|
}
|
|
4961
|
-
|
|
4961
|
+
const viaCompanion = user?.via_companion === true;
|
|
4962
|
+
if (viaCompanion && table.RBAC !== true) {
|
|
4963
|
+
return query.whereRaw("1 = 0");
|
|
4964
|
+
}
|
|
4965
|
+
if (!viaCompanion && table.name.plural !== "agent_sessions" && user?.super_admin === true) {
|
|
4962
4966
|
return query;
|
|
4963
4967
|
}
|
|
4964
4968
|
if (user && !user?.super_admin && (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 === "read" || user.role.agents === "write")) && !(table.name.plural === "workflow_templates" && (user.role.workflows === "read" || user.role.workflows === "write")) && !(table.name.plural === "variables" && (user.role.variables === "read" || user.role.variables === "write")) && !(table.name.plural === "users" && (user.role.users === "read" || user.role.users === "write")) && !((table.name.plural === "test_cases" || table.name.plural === "eval_sets" || table.name.plural === "eval_runs") && (user.role.evals === "read" || user.role.evals === "write")))) {
|
|
@@ -4974,16 +4978,20 @@ var init_access_control = __esm({
|
|
|
4974
4978
|
if (!hasRBAC) {
|
|
4975
4979
|
return query;
|
|
4976
4980
|
}
|
|
4977
|
-
if (user?.super_admin) {
|
|
4981
|
+
if (!viaCompanion && user?.super_admin) {
|
|
4978
4982
|
return query;
|
|
4979
4983
|
}
|
|
4980
4984
|
const prefix = field_prefix ? field_prefix + "." : "";
|
|
4981
4985
|
console.log("[EXULU] applying access control with this prefix", prefix);
|
|
4982
4986
|
try {
|
|
4983
4987
|
query = query.where(function() {
|
|
4984
|
-
|
|
4988
|
+
if (!viaCompanion) {
|
|
4989
|
+
this.where(`${prefix}rights_mode`, "public");
|
|
4990
|
+
}
|
|
4985
4991
|
if (user) {
|
|
4986
|
-
|
|
4992
|
+
if (!viaCompanion) {
|
|
4993
|
+
this.orWhere(`${prefix}created_by`, user.id);
|
|
4994
|
+
}
|
|
4987
4995
|
this.orWhere(function() {
|
|
4988
4996
|
this.where(`${prefix}rights_mode`, "users").whereExists(function() {
|
|
4989
4997
|
this.select("*").from("rbac").whereRaw(
|
|
@@ -6733,6 +6741,9 @@ var init_core_schema = __esm({
|
|
|
6733
6741
|
// to protect. /settings and /panel are unaffected: both read row.agent_slots
|
|
6734
6742
|
// straight off the knex row, not through the generated GraphQL field.
|
|
6735
6743
|
{ name: "agent_slots", type: "json", hidden: true },
|
|
6744
|
+
// Released for the public companion server. Only meaningful for
|
|
6745
|
+
// auth_mode "regular" (validateExternalAccess). Not reported by /meta.
|
|
6746
|
+
{ name: "external_access", type: "boolean", default: false },
|
|
6736
6747
|
// Artifact library (2026-12): how a share presents itself and is found in
|
|
6737
6748
|
// the Artifacts screen. All optional, all additive — a database that never
|
|
6738
6749
|
// ran init-db for them reads them as absent, and every reader coerces.
|
|
@@ -9905,13 +9916,13 @@ function oauthBlobToRecord(b) {
|
|
|
9905
9916
|
expiresAt: b.expiresAt ? new Date(b.expiresAt) : null
|
|
9906
9917
|
};
|
|
9907
9918
|
}
|
|
9908
|
-
var import_crypto_js2,
|
|
9919
|
+
var import_crypto_js2, import_node_crypto3, OAUTH_CALLBACK_PATH, STATE_TTL_MS, EXPIRY_SKEW_MS, getOauthRedirectUri, toBase64Url, fromBase64Url, encryptOauthState, decryptOauthState, buildAuthorizationUrl, tokenResponseToRecord, postTokenEndpoint, exchangeCodeForTokens, refreshAccessToken, getValidAccessToken;
|
|
9909
9920
|
var init_flow = __esm({
|
|
9910
9921
|
"src/exulu/auth/flow.ts"() {
|
|
9911
9922
|
"use strict";
|
|
9912
9923
|
init_cjs_shims();
|
|
9913
9924
|
import_crypto_js2 = __toESM(require("crypto-js"), 1);
|
|
9914
|
-
|
|
9925
|
+
import_node_crypto3 = require("crypto");
|
|
9915
9926
|
init_credential_store();
|
|
9916
9927
|
init_provider_key();
|
|
9917
9928
|
OAUTH_CALLBACK_PATH = "/oauth/callback";
|
|
@@ -9963,7 +9974,7 @@ var init_flow = __esm({
|
|
|
9963
9974
|
config
|
|
9964
9975
|
}) => {
|
|
9965
9976
|
const pkce = config.pkce !== false;
|
|
9966
|
-
const codeVerifier = pkce ? (0,
|
|
9977
|
+
const codeVerifier = pkce ? (0, import_node_crypto3.randomBytes)(48).toString("base64url") : void 0;
|
|
9967
9978
|
const state = encryptOauthState({
|
|
9968
9979
|
provider: providerKeyFor(toolId, config),
|
|
9969
9980
|
toolId,
|
|
@@ -9982,7 +9993,7 @@ var init_flow = __esm({
|
|
|
9982
9993
|
if (codeVerifier) {
|
|
9983
9994
|
url.searchParams.set(
|
|
9984
9995
|
"code_challenge",
|
|
9985
|
-
(0,
|
|
9996
|
+
(0, import_node_crypto3.createHash)("sha256").update(codeVerifier).digest("base64url")
|
|
9986
9997
|
);
|
|
9987
9998
|
url.searchParams.set("code_challenge_method", "S256");
|
|
9988
9999
|
}
|
|
@@ -10303,7 +10314,7 @@ var init_rbac_resolver = __esm({
|
|
|
10303
10314
|
});
|
|
10304
10315
|
|
|
10305
10316
|
// src/exulu/shared-artifacts.ts
|
|
10306
|
-
var import_bcryptjs2, normalizeS3Key, isHtmlKey, deriveFilename, slugifyShareName, isExpired, validateCreateInput, validateAgentSlots, readAgentSlots, RIGHTS_MODES, canManageShare, validateUpdateInput, ownsObjectKey, planShareUpdate, hashSharePassword, verifySharePassword, contentHeadersFor, publicMetaFor, getSharedArtifactByName;
|
|
10317
|
+
var import_bcryptjs2, normalizeS3Key, isHtmlKey, deriveFilename, slugifyShareName, isExpired, validateCreateInput, validateAgentSlots, readAgentSlots, EXTERNAL_LOGIN_ONLY, EXTERNAL_NEEDS_TEAM, EXTERNAL_SUPER_ADMIN_ONLY, EXTERNAL_TEAM_NAME, validateExternalAccess, mayChangeExternalRelease, teamNamesByIds, externalAccessCheckApplies, externalAccessNeedsTeams, validateExternalAccessUpdate, resultingRightsMode, RIGHTS_MODES, canManageShare, validateUpdateInput, ownsObjectKey, planShareUpdate, hashSharePassword, verifySharePassword, contentHeadersFor, publicMetaFor, getSharedArtifactByName;
|
|
10307
10318
|
var init_shared_artifacts = __esm({
|
|
10308
10319
|
"src/exulu/shared-artifacts.ts"() {
|
|
10309
10320
|
"use strict";
|
|
@@ -10378,6 +10389,51 @@ var init_shared_artifacts = __esm({
|
|
|
10378
10389
|
})() : value;
|
|
10379
10390
|
return Array.isArray(parsed) ? parsed : [];
|
|
10380
10391
|
};
|
|
10392
|
+
EXTERNAL_LOGIN_ONLY = "External release requires a login share.";
|
|
10393
|
+
EXTERNAL_NEEDS_TEAM = "External release requires the share to be granted to at least one team.";
|
|
10394
|
+
EXTERNAL_SUPER_ADMIN_ONLY = "Only a super admin can release an artifact externally.";
|
|
10395
|
+
EXTERNAL_TEAM_NAME = "external";
|
|
10396
|
+
validateExternalAccess = (input) => {
|
|
10397
|
+
const flag2 = input.external_access;
|
|
10398
|
+
if (flag2 === void 0) return null;
|
|
10399
|
+
if (typeof flag2 !== "boolean") return "external_access must be a boolean.";
|
|
10400
|
+
if (!flag2) return null;
|
|
10401
|
+
if (input.auth_mode !== "regular") return EXTERNAL_LOGIN_ONLY;
|
|
10402
|
+
const teams = input.teams ?? [];
|
|
10403
|
+
if (input.rights_mode !== "teams" || teams.length === 0) return EXTERNAL_NEEDS_TEAM;
|
|
10404
|
+
if (teams.some((t) => String(t.name).trim().toLowerCase() === EXTERNAL_TEAM_NAME)) {
|
|
10405
|
+
return `The team "${EXTERNAL_TEAM_NAME}" holds self-registered guests and cannot be used for external release.`;
|
|
10406
|
+
}
|
|
10407
|
+
return null;
|
|
10408
|
+
};
|
|
10409
|
+
mayChangeExternalRelease = (user, requested, current) => requested !== true || current === true || user.super_admin === true;
|
|
10410
|
+
teamNamesByIds = async (db2, ids) => {
|
|
10411
|
+
const clean = ids.filter((id) => id !== void 0 && id !== null);
|
|
10412
|
+
if (!clean.length) return [];
|
|
10413
|
+
const rows = await db2("teams").whereIn("id", clean).select("name");
|
|
10414
|
+
return rows;
|
|
10415
|
+
};
|
|
10416
|
+
externalAccessCheckApplies = (input, row) => input.external_access !== void 0 || row.external_access === true;
|
|
10417
|
+
externalAccessNeedsTeams = (input, row) => {
|
|
10418
|
+
const mode = input.auth_mode ?? row.auth_mode;
|
|
10419
|
+
const effective = input.external_access !== void 0 ? input.external_access : row.external_access === true;
|
|
10420
|
+
return effective === true && mode === "regular";
|
|
10421
|
+
};
|
|
10422
|
+
validateExternalAccessUpdate = (input, row, teams) => {
|
|
10423
|
+
const mode = input.auth_mode ?? row.auth_mode;
|
|
10424
|
+
const effective = input.external_access !== void 0 ? input.external_access : row.external_access === true;
|
|
10425
|
+
return validateExternalAccess({
|
|
10426
|
+
external_access: effective,
|
|
10427
|
+
auth_mode: mode,
|
|
10428
|
+
rights_mode: resultingRightsMode(input, row),
|
|
10429
|
+
teams
|
|
10430
|
+
});
|
|
10431
|
+
};
|
|
10432
|
+
resultingRightsMode = (input, row) => {
|
|
10433
|
+
const mode = input.auth_mode ?? row.auth_mode;
|
|
10434
|
+
if (mode !== "regular") return "public";
|
|
10435
|
+
return input.rights_mode ?? (row.auth_mode === "regular" ? row.rights_mode ?? "private" : "private");
|
|
10436
|
+
};
|
|
10381
10437
|
RIGHTS_MODES = /* @__PURE__ */ new Set(["private", "users", "roles", "teams", "public"]);
|
|
10382
10438
|
canManageShare = (row, user) => user.super_admin === true || row.created_by != null && String(row.created_by) === String(user.id);
|
|
10383
10439
|
validateUpdateInput = (input, row, now) => {
|
|
@@ -10426,15 +10482,12 @@ var init_shared_artifacts = __esm({
|
|
|
10426
10482
|
if (input.content_type !== void 0) patch.content_type = input.content_type;
|
|
10427
10483
|
patch.password_hash = mode === "password" ? newPasswordHash ?? row.password_hash : null;
|
|
10428
10484
|
if (input.expires_at !== void 0) patch.expires_at = input.expires_at;
|
|
10429
|
-
|
|
10430
|
-
patch.rights_mode = input.rights_mode ?? (row.auth_mode === "regular" ? row.rights_mode ?? "private" : "private");
|
|
10431
|
-
} else {
|
|
10432
|
-
patch.rights_mode = "public";
|
|
10433
|
-
}
|
|
10485
|
+
patch.rights_mode = resultingRightsMode(input, row);
|
|
10434
10486
|
if (input.agent_slots !== void 0) {
|
|
10435
10487
|
const slotsResult = validateAgentSlots(input.agent_slots);
|
|
10436
10488
|
if (slotsResult.ok) patch.agent_slots = slotsResult.slots;
|
|
10437
10489
|
}
|
|
10490
|
+
if (typeof input.external_access === "boolean") patch.external_access = input.external_access;
|
|
10438
10491
|
return patch;
|
|
10439
10492
|
};
|
|
10440
10493
|
hashSharePassword = (password) => import_bcryptjs2.default.hash(password, 10);
|
|
@@ -11182,13 +11235,14 @@ function createRecallCollector(context, user, db2) {
|
|
|
11182
11235
|
loadUsers: (ids) => db2("users").whereIn("id", ids).select("id", "firstname", "lastname", "email")
|
|
11183
11236
|
});
|
|
11184
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
|
+
}
|
|
11185
11243
|
function buildMemoryPromptBlock(memories) {
|
|
11186
11244
|
if (memories.length === 0) return "";
|
|
11187
|
-
const lines = memories.map(
|
|
11188
|
-
const who = m.createdBy ? `saved by ${m.createdBy.name}` : "saved earlier";
|
|
11189
|
-
const when = m.createdAt ? ` on ${m.createdAt.slice(0, 10)}` : "";
|
|
11190
|
-
return `- {item_name: "${cite(m.title)}", item_id: "${m.id}", context: "${m.contextId}"} ${m.information} (${who}${when}, ${m.rights_mode})`;
|
|
11191
|
-
});
|
|
11245
|
+
const lines = memories.map(memoryPromptLine);
|
|
11192
11246
|
return [
|
|
11193
11247
|
"Memories: facts people saved earlier for this assistant. Use them where relevant and cite each memory you rely on",
|
|
11194
11248
|
"with its citation object exactly as given, e.g. {item_name: <title>, item_id: <id>, context: <contextId>}",
|
|
@@ -11540,6 +11594,39 @@ var init_decisions = __esm({
|
|
|
11540
11594
|
}
|
|
11541
11595
|
});
|
|
11542
11596
|
|
|
11597
|
+
// src/exulu/companion/write-grant.ts
|
|
11598
|
+
var idOf, hasCompanionWriteGrant;
|
|
11599
|
+
var init_write_grant = __esm({
|
|
11600
|
+
"src/exulu/companion/write-grant.ts"() {
|
|
11601
|
+
"use strict";
|
|
11602
|
+
init_cjs_shims();
|
|
11603
|
+
idOf = (v) => {
|
|
11604
|
+
const id = typeof v === "object" && v !== null ? v.id : v;
|
|
11605
|
+
if (typeof id === "number") return id;
|
|
11606
|
+
if (typeof id === "string" && id !== "") return id;
|
|
11607
|
+
return void 0;
|
|
11608
|
+
};
|
|
11609
|
+
hasCompanionWriteGrant = async (db2, entity, id, user, rightsMode) => {
|
|
11610
|
+
let grantee;
|
|
11611
|
+
if (rightsMode === "users") {
|
|
11612
|
+
grantee = { access_type: "User", user_id: user.id };
|
|
11613
|
+
} else if (rightsMode === "roles") {
|
|
11614
|
+
const roleId = idOf(user.role);
|
|
11615
|
+
if (roleId === void 0) return false;
|
|
11616
|
+
grantee = { access_type: "Role", role_id: roleId };
|
|
11617
|
+
} else if (rightsMode === "teams") {
|
|
11618
|
+
const teamId = idOf(user.team);
|
|
11619
|
+
if (teamId === void 0) return false;
|
|
11620
|
+
grantee = { access_type: "Team", team_id: teamId };
|
|
11621
|
+
} else {
|
|
11622
|
+
return false;
|
|
11623
|
+
}
|
|
11624
|
+
const grant = await db2.from("rbac").where({ entity, target_resource_id: id, rights: "write", ...grantee }).first();
|
|
11625
|
+
return !!grant;
|
|
11626
|
+
};
|
|
11627
|
+
}
|
|
11628
|
+
});
|
|
11629
|
+
|
|
11543
11630
|
// src/utils/check-item-write-access.ts
|
|
11544
11631
|
var checkItemWriteAccess;
|
|
11545
11632
|
var init_check_item_write_access = __esm({
|
|
@@ -11548,10 +11635,15 @@ var init_check_item_write_access = __esm({
|
|
|
11548
11635
|
init_cjs_shims();
|
|
11549
11636
|
init_client();
|
|
11550
11637
|
init_table_names();
|
|
11638
|
+
init_write_grant();
|
|
11551
11639
|
checkItemWriteAccess = async (context, record, user) => {
|
|
11552
11640
|
if (!user) {
|
|
11553
11641
|
return false;
|
|
11554
11642
|
}
|
|
11643
|
+
if (user.via_companion === true) {
|
|
11644
|
+
const { db: db3 } = await postgresClient();
|
|
11645
|
+
return hasCompanionWriteGrant(db3, getTableName(context.id), record.id, user, record.rights_mode);
|
|
11646
|
+
}
|
|
11555
11647
|
if (user.super_admin === true) {
|
|
11556
11648
|
return true;
|
|
11557
11649
|
}
|
|
@@ -12070,14 +12162,14 @@ var init_context_read_tools = __esm({
|
|
|
12070
12162
|
});
|
|
12071
12163
|
|
|
12072
12164
|
// src/templates/tools/context-write-tools.ts
|
|
12073
|
-
var import_zod7,
|
|
12165
|
+
var import_zod7, import_node_crypto4, MAX_CONTEXT_SEGMENT, contextToolSegment, itemNotFoundMessage, isHiddenField, RESERVED_INPUT_KEYS, buildWriteSchema, BARE_FILENAME, attachSessionFiles, canonicalizeEnumFields, pickContent, jobNote, createContextWriteTools, createKbEditorPickerTool, collectKbWriteTools;
|
|
12074
12166
|
var init_context_write_tools = __esm({
|
|
12075
12167
|
"src/templates/tools/context-write-tools.ts"() {
|
|
12076
12168
|
"use strict";
|
|
12077
12169
|
init_cjs_shims();
|
|
12078
12170
|
init_tool2();
|
|
12079
12171
|
import_zod7 = require("zod");
|
|
12080
|
-
|
|
12172
|
+
import_node_crypto4 = require("crypto");
|
|
12081
12173
|
init_session_files();
|
|
12082
12174
|
init_uppy();
|
|
12083
12175
|
init_sanitize_name();
|
|
@@ -12207,7 +12299,7 @@ var init_context_write_tools = __esm({
|
|
|
12207
12299
|
return `"${name}" has type "${ext || "none"}", but the ${field.input} field only accepts ${field.allowed.join(", ")}.`;
|
|
12208
12300
|
}
|
|
12209
12301
|
const sourceKey = `${sessionFilePrefix(deps.sessionOwnerId ?? owner ?? "api", sessionID, uploads.s3prefix)}${name}`;
|
|
12210
|
-
const destKey = `${general}user_${owner}/${(0,
|
|
12302
|
+
const destKey = `${general}user_${owner}/${(0, import_node_crypto4.randomUUID)()}-_EXULU_${name}`;
|
|
12211
12303
|
try {
|
|
12212
12304
|
await copy(sourceKey, destKey, exuluConfig);
|
|
12213
12305
|
} catch (error) {
|
|
@@ -12452,20 +12544,20 @@ function hasProjectAccess(args) {
|
|
|
12452
12544
|
case "users":
|
|
12453
12545
|
return granted(rbac.users, user.id);
|
|
12454
12546
|
case "roles":
|
|
12455
|
-
return granted(rbac.roles,
|
|
12547
|
+
return granted(rbac.roles, idOf2(user.role));
|
|
12456
12548
|
case "teams":
|
|
12457
|
-
return granted(rbac.teams,
|
|
12549
|
+
return granted(rbac.teams, idOf2(user.team));
|
|
12458
12550
|
default:
|
|
12459
12551
|
return false;
|
|
12460
12552
|
}
|
|
12461
12553
|
}
|
|
12462
|
-
var sameEntityId,
|
|
12554
|
+
var sameEntityId, idOf2;
|
|
12463
12555
|
var init_project_access = __esm({
|
|
12464
12556
|
"src/exulu/project-access.ts"() {
|
|
12465
12557
|
"use strict";
|
|
12466
12558
|
init_cjs_shims();
|
|
12467
12559
|
sameEntityId = (a, b) => a != null && b != null && a !== "" && b !== "" && String(a) === String(b);
|
|
12468
|
-
|
|
12560
|
+
idOf2 = (v) => typeof v === "object" && v ? v.id : v;
|
|
12469
12561
|
}
|
|
12470
12562
|
});
|
|
12471
12563
|
|
|
@@ -12633,7 +12725,7 @@ async function createProjectForUser(db2, user, input) {
|
|
|
12633
12725
|
const values = { name, ...description ? { description } : {} };
|
|
12634
12726
|
const validation = prepareItemWrite({ fields: projectFields(), existing: null, input: values });
|
|
12635
12727
|
if (!validation.ok) throw new Error(validation.message);
|
|
12636
|
-
const row = { ...values, id: (0,
|
|
12728
|
+
const row = { ...values, id: (0, import_node_crypto5.randomUUID)(), created_by: user.id, rights_mode: "private" };
|
|
12637
12729
|
const [created] = await db2("projects").insert(row).returning(["id", "name"]);
|
|
12638
12730
|
if (!created?.id) throw new Error("The project could not be created.");
|
|
12639
12731
|
return { id: String(created.id), name: String(created.name ?? name) };
|
|
@@ -12730,12 +12822,12 @@ function planMove(args) {
|
|
|
12730
12822
|
if (batch.length > 0) batches.push(batch);
|
|
12731
12823
|
return { batches, skipped };
|
|
12732
12824
|
}
|
|
12733
|
-
var
|
|
12825
|
+
var import_node_crypto5, MAX_PROJECT_NAME_LENGTH, MAX_PROJECT_DESCRIPTION_LENGTH, TOOL_OUTPUT_PREFIX, cachedProjectFields, projectFields, bareId, SKIP_CLASH, SKIP_UNKNOWN, SKIP_NESTED, SKIP_TOO_LARGE, SKIP_PROJECT_FULL, isDefaultMoveCandidate;
|
|
12734
12826
|
var init_project_create = __esm({
|
|
12735
12827
|
"src/exulu/project-create.ts"() {
|
|
12736
12828
|
"use strict";
|
|
12737
12829
|
init_cjs_shims();
|
|
12738
|
-
|
|
12830
|
+
import_node_crypto5 = require("crypto");
|
|
12739
12831
|
init_rbac_resolver();
|
|
12740
12832
|
init_artifact_filter();
|
|
12741
12833
|
init_core_schema();
|
|
@@ -13970,12 +14062,12 @@ async function resolveSkill(db2, ref) {
|
|
|
13970
14062
|
const byId = /^[0-9a-f-]{36}$/i.test(value) ? await db2("skills").where({ id: value }).first() : null;
|
|
13971
14063
|
return byId ?? await resolveSkillByName(db2, value);
|
|
13972
14064
|
}
|
|
13973
|
-
var
|
|
14065
|
+
var import_node_crypto6, import_zod11, MAX_READ_BYTES, defaultIo, err2, safeSkillPath, contentTypeFor, yamlString, ensureFrontmatter, generalPrefix3, relativePaths, normalizeFiles, actionsFileError, createSkillAuthorTools, createSkillAuthorPickerTool, collectSkillAuthorTools;
|
|
13974
14066
|
var init_skill_author_tools = __esm({
|
|
13975
14067
|
"src/templates/tools/skill-author-tools.ts"() {
|
|
13976
14068
|
"use strict";
|
|
13977
14069
|
init_cjs_shims();
|
|
13978
|
-
|
|
14070
|
+
import_node_crypto6 = require("crypto");
|
|
13979
14071
|
import_zod11 = require("zod");
|
|
13980
14072
|
init_tool2();
|
|
13981
14073
|
init_client();
|
|
@@ -14180,7 +14272,7 @@ ${content}`
|
|
|
14180
14272
|
const db2 = await getDb();
|
|
14181
14273
|
if (await resolveSkillByName(db2, name)) return err2(`A skill named "${name}" already exists. Use skill_update to change it, or choose another name.`);
|
|
14182
14274
|
const rights_mode = decision?.rights_mode ?? "private";
|
|
14183
|
-
const skillId = (0,
|
|
14275
|
+
const skillId = (0, import_node_crypto6.randomUUID)();
|
|
14184
14276
|
const stamp2 = now().toISOString();
|
|
14185
14277
|
for (const f of files) {
|
|
14186
14278
|
await io.upload(Buffer.from(f.content, "utf8"), `skills/${skillId}/v1/${f.path}`, exuluConfig, contentTypeFor(f.path));
|
|
@@ -14513,7 +14605,7 @@ async function syncProjectDir(args) {
|
|
|
14513
14605
|
await (0, import_promises2.rename)((0, import_node_path6.join)(old, name), (0, import_node_path6.join)(staging, name));
|
|
14514
14606
|
const moved = await (0, import_promises2.lstat)((0, import_node_path6.join)(staging, name)).catch(() => null);
|
|
14515
14607
|
if (!moved?.isFile()) {
|
|
14516
|
-
await (0, import_promises2.rename)((0, import_node_path6.join)(staging, name), (0, import_node_path6.join)(old, `.rejected-${(0,
|
|
14608
|
+
await (0, import_promises2.rename)((0, import_node_path6.join)(staging, name), (0, import_node_path6.join)(old, `.rejected-${(0, import_node_crypto7.randomBytes)(4).toString("hex")}`)).catch(() => {
|
|
14517
14609
|
});
|
|
14518
14610
|
continue;
|
|
14519
14611
|
}
|
|
@@ -14569,13 +14661,13 @@ async function resolveSandboxProjectId(args, deps) {
|
|
|
14569
14661
|
return null;
|
|
14570
14662
|
}
|
|
14571
14663
|
}
|
|
14572
|
-
var import_promises2,
|
|
14664
|
+
var import_promises2, import_node_crypto7, import_node_path6, import_node_child_process3, import_node_util2, isFlatName, HELPER_KINDS, helperRoot, helperPath, execFileAsync2, DAY_MS3, errCode;
|
|
14573
14665
|
var init_project_sync = __esm({
|
|
14574
14666
|
"ee/invoke-skills/project-sync.ts"() {
|
|
14575
14667
|
"use strict";
|
|
14576
14668
|
init_cjs_shims();
|
|
14577
14669
|
import_promises2 = require("fs/promises");
|
|
14578
|
-
|
|
14670
|
+
import_node_crypto7 = require("crypto");
|
|
14579
14671
|
import_node_path6 = require("path");
|
|
14580
14672
|
import_node_child_process3 = require("child_process");
|
|
14581
14673
|
import_node_util2 = require("util");
|
|
@@ -14585,7 +14677,7 @@ var init_project_sync = __esm({
|
|
|
14585
14677
|
isFlatName = (name) => !!name && !name.includes("/") && !name.includes("\\") && name !== "." && name !== "..";
|
|
14586
14678
|
HELPER_KINDS = [".project-staging", ".project-trash"];
|
|
14587
14679
|
helperRoot = (sessionDir, kind) => (0, import_node_path6.join)((0, import_node_path6.dirname)(sessionDir), kind);
|
|
14588
|
-
helperPath = (sessionDir, kind) => (0, import_node_path6.join)(helperRoot(sessionDir, kind), `${(0, import_node_path6.basename)(sessionDir)}-${(0,
|
|
14680
|
+
helperPath = (sessionDir, kind) => (0, import_node_path6.join)(helperRoot(sessionDir, kind), `${(0, import_node_path6.basename)(sessionDir)}-${(0, import_node_crypto7.randomBytes)(8).toString("hex")}`);
|
|
14589
14681
|
execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
|
|
14590
14682
|
DAY_MS3 = 24 * 60 * 60 * 1e3;
|
|
14591
14683
|
errCode = (err4) => err4?.code;
|
|
@@ -14688,7 +14780,7 @@ async function writeFileInside(sessionDir, relativePath, bytes, opts = {}) {
|
|
|
14688
14780
|
if (opts.notUnder !== void 0 && await landsInside(sessionDir, destination, opts.notUnder)) {
|
|
14689
14781
|
throw new UnsafeSessionPathError(`Refusing to write ${destination}: it lands in ${opts.notUnder}/.`);
|
|
14690
14782
|
}
|
|
14691
|
-
const temp = (0, import_node_path7.join)(parent, `.exulu-write-${(0,
|
|
14783
|
+
const temp = (0, import_node_path7.join)(parent, `.exulu-write-${(0, import_node_crypto8.randomBytes)(8).toString("hex")}`);
|
|
14692
14784
|
await (0, import_promises3.writeFile)(temp, bytes, { flag: "wx" });
|
|
14693
14785
|
try {
|
|
14694
14786
|
await (0, import_promises3.rename)(temp, destination);
|
|
@@ -14754,14 +14846,14 @@ async function landsInside(sessionDir, path4, relativeDir) {
|
|
|
14754
14846
|
return errCode2(err4) !== "ENOTDIR";
|
|
14755
14847
|
}
|
|
14756
14848
|
}
|
|
14757
|
-
var import_node_fs4, import_promises3,
|
|
14849
|
+
var import_node_fs4, import_promises3, import_node_crypto8, import_node_path7, UnsafeSessionPathError, errCode2, isInside, MAX_LINK_HOPS;
|
|
14758
14850
|
var init_safe_fs = __esm({
|
|
14759
14851
|
"ee/invoke-skills/safe-fs.ts"() {
|
|
14760
14852
|
"use strict";
|
|
14761
14853
|
init_cjs_shims();
|
|
14762
14854
|
import_node_fs4 = require("fs");
|
|
14763
14855
|
import_promises3 = require("fs/promises");
|
|
14764
|
-
|
|
14856
|
+
import_node_crypto8 = require("crypto");
|
|
14765
14857
|
init_project_sync();
|
|
14766
14858
|
import_node_path7 = require("path");
|
|
14767
14859
|
init_session_file_adopt();
|
|
@@ -14778,12 +14870,12 @@ var init_safe_fs = __esm({
|
|
|
14778
14870
|
});
|
|
14779
14871
|
|
|
14780
14872
|
// ee/invoke-skills/skill-actions/tool.ts
|
|
14781
|
-
var
|
|
14873
|
+
var import_node_crypto9, import_promises4, import_node_path8, import_zod12, RUN_SKILL_ACTION_TOOL_ID, TEXT_MAX_CHARS, ITEMS_DEFAULT_LIMIT, ITEMS_MAX_LIMIT, ARGS_FILE_STEM, isPlainObject3, listOrNone, createRunSkillActionTool, RESULT_MARGIN_CHARS, STDERR_SHARE, fitResult, disabledSearchContexts, deriveConnectedContextIds;
|
|
14782
14874
|
var init_tool = __esm({
|
|
14783
14875
|
"ee/invoke-skills/skill-actions/tool.ts"() {
|
|
14784
14876
|
"use strict";
|
|
14785
14877
|
init_cjs_shims();
|
|
14786
|
-
|
|
14878
|
+
import_node_crypto9 = require("crypto");
|
|
14787
14879
|
import_promises4 = require("fs/promises");
|
|
14788
14880
|
import_node_path8 = require("path");
|
|
14789
14881
|
import_zod12 = require("zod");
|
|
@@ -14946,7 +15038,7 @@ var init_tool = __esm({
|
|
|
14946
15038
|
files.push({ file: `${ARGS_FILE_STEM}.json`, content: textArgs });
|
|
14947
15039
|
}
|
|
14948
15040
|
const sessionDir = handle.sessionDir;
|
|
14949
|
-
const runId = (0,
|
|
15041
|
+
const runId = (0, import_node_crypto9.randomUUID)();
|
|
14950
15042
|
const runRelative = `${ACTION_INPUTS_DIR}/${runId}`;
|
|
14951
15043
|
try {
|
|
14952
15044
|
const parent = await ensureRealDirectory(sessionDir, ACTION_INPUTS_DIR);
|
|
@@ -17347,16 +17439,16 @@ var init_routine_status_tool = __esm({
|
|
|
17347
17439
|
});
|
|
17348
17440
|
|
|
17349
17441
|
// src/templates/tools/tool-upload.ts
|
|
17350
|
-
var import_client_s33,
|
|
17442
|
+
var import_client_s33, import_node_crypto10, generateS3Key, s3Client2, buildToolUpload;
|
|
17351
17443
|
var init_tool_upload = __esm({
|
|
17352
17444
|
"src/templates/tools/tool-upload.ts"() {
|
|
17353
17445
|
"use strict";
|
|
17354
17446
|
init_cjs_shims();
|
|
17355
17447
|
import_client_s33 = require("@aws-sdk/client-s3");
|
|
17356
|
-
|
|
17448
|
+
import_node_crypto10 = require("crypto");
|
|
17357
17449
|
init_session_file_write();
|
|
17358
17450
|
init_uppy();
|
|
17359
|
-
generateS3Key = (filename) => `${(0,
|
|
17451
|
+
generateS3Key = (filename) => `${(0, import_node_crypto10.randomUUID)()}-${filename}`;
|
|
17360
17452
|
buildToolUpload = (exuluConfig, user) => {
|
|
17361
17453
|
const uploads = exuluConfig?.fileUploads;
|
|
17362
17454
|
if (!uploads?.s3endpoint || !uploads?.s3key || !uploads?.s3secret || !uploads?.s3Bucket) {
|
|
@@ -17538,19 +17630,19 @@ var init_context_budget = __esm({
|
|
|
17538
17630
|
});
|
|
17539
17631
|
|
|
17540
17632
|
// src/exulu/tool-output-offload.ts
|
|
17541
|
-
var
|
|
17633
|
+
var import_node_crypto11, PREVIEW_CHARS, storeAsSessionFile, buildNotice, guardToolOutput, guardExtractedFileText;
|
|
17542
17634
|
var init_tool_output_offload = __esm({
|
|
17543
17635
|
"src/exulu/tool-output-offload.ts"() {
|
|
17544
17636
|
"use strict";
|
|
17545
17637
|
init_cjs_shims();
|
|
17546
|
-
|
|
17638
|
+
import_node_crypto11 = require("crypto");
|
|
17547
17639
|
init_uppy();
|
|
17548
17640
|
init_context_budget();
|
|
17549
17641
|
PREVIEW_CHARS = 4e3;
|
|
17550
17642
|
storeAsSessionFile = async (serialized, ctx) => {
|
|
17551
17643
|
if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
|
|
17552
17644
|
const safeTool = ctx.toolName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
|
|
17553
|
-
const name = `tool-output-${safeTool}-${(0,
|
|
17645
|
+
const name = `tool-output-${safeTool}-${(0, import_node_crypto11.randomUUID)().slice(0, 8)}.txt`;
|
|
17554
17646
|
try {
|
|
17555
17647
|
await uploadFile(
|
|
17556
17648
|
Buffer.from(serialized, "utf-8"),
|
|
@@ -17800,6 +17892,33 @@ async function convertLegacyOfficeToModern(bytes, ext) {
|
|
|
17800
17892
|
await (0, import_promises6.rm)(dir, { recursive: true, force: true });
|
|
17801
17893
|
}
|
|
17802
17894
|
}
|
|
17895
|
+
function isPresentationFormat(ext) {
|
|
17896
|
+
return PRESENTATION_EXTENSIONS.has(ext.toLowerCase());
|
|
17897
|
+
}
|
|
17898
|
+
async function convertOfficeToPdf(bytes, ext) {
|
|
17899
|
+
const dir = await (0, import_promises6.mkdtemp)((0, import_node_path11.join)((0, import_node_os2.tmpdir)(), "exulu-office2pdf-"));
|
|
17900
|
+
try {
|
|
17901
|
+
const inputPath = (0, import_node_path11.join)(dir, `input${ext.toLowerCase()}`);
|
|
17902
|
+
await (0, import_promises6.writeFile)(inputPath, bytes);
|
|
17903
|
+
try {
|
|
17904
|
+
await execFileAsync3(
|
|
17905
|
+
"soffice",
|
|
17906
|
+
// Own profile directory: two conversions at once otherwise fight over the user profile lock.
|
|
17907
|
+
[`-env:UserInstallation=file://${(0, import_node_path11.join)(dir, "profile")}`, "--headless", "--convert-to", "pdf", inputPath, "--outdir", dir],
|
|
17908
|
+
{ timeout: 18e4, maxBuffer: MAX_STDOUT_BYTES }
|
|
17909
|
+
);
|
|
17910
|
+
} catch (err4) {
|
|
17911
|
+
throw new Error(`LibreOffice could not convert the "${ext}" file to PDF: ` + (err4 instanceof Error ? err4.message : String(err4)));
|
|
17912
|
+
}
|
|
17913
|
+
const outputPath = (0, import_node_path11.join)(dir, "input.pdf");
|
|
17914
|
+
if (!(0, import_node_fs8.existsSync)(outputPath)) {
|
|
17915
|
+
throw new Error(`LibreOffice produced no PDF for the "${ext}" file`);
|
|
17916
|
+
}
|
|
17917
|
+
return await (0, import_promises6.readFile)(outputPath);
|
|
17918
|
+
} finally {
|
|
17919
|
+
await (0, import_promises6.rm)(dir, { recursive: true, force: true });
|
|
17920
|
+
}
|
|
17921
|
+
}
|
|
17803
17922
|
async function pdfToText(pdf) {
|
|
17804
17923
|
const dir = await (0, import_promises6.mkdtemp)((0, import_node_path11.join)((0, import_node_os2.tmpdir)(), "exulu-parse-"));
|
|
17805
17924
|
try {
|
|
@@ -17849,7 +17968,7 @@ async function renderPdfPageToPng(pdf, page, scaleTo) {
|
|
|
17849
17968
|
await (0, import_promises6.rm)(dir, { recursive: true, force: true });
|
|
17850
17969
|
}
|
|
17851
17970
|
}
|
|
17852
|
-
var import_node_child_process6, import_node_util5, import_node_fs8, import_promises6, import_node_os2, import_node_path11, execFileAsync3, MAX_STDOUT_BYTES, LEGACY_OFFICE_CONVERSION_TARGETS;
|
|
17971
|
+
var import_node_child_process6, import_node_util5, import_node_fs8, import_promises6, import_node_os2, import_node_path11, execFileAsync3, MAX_STDOUT_BYTES, LEGACY_OFFICE_CONVERSION_TARGETS, PRESENTATION_EXTENSIONS;
|
|
17853
17972
|
var init_document_render_helpers = __esm({
|
|
17854
17973
|
"src/templates/tools/document-render-helpers.ts"() {
|
|
17855
17974
|
"use strict";
|
|
@@ -17868,6 +17987,7 @@ var init_document_render_helpers = __esm({
|
|
|
17868
17987
|
".ppt": "pptx",
|
|
17869
17988
|
".rtf": "docx"
|
|
17870
17989
|
};
|
|
17990
|
+
PRESENTATION_EXTENSIONS = /* @__PURE__ */ new Set([".pptx", ".ppt", ".pptm", ".odp"]);
|
|
17871
17991
|
}
|
|
17872
17992
|
});
|
|
17873
17993
|
|
|
@@ -18622,6 +18742,19 @@ async function processDocument(filePath, fileType, buffer, tempDir, config, verb
|
|
|
18622
18742
|
case "webp":
|
|
18623
18743
|
result = await processImage(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
|
|
18624
18744
|
break;
|
|
18745
|
+
// A presentation is rendered to PDF and then read like any PDF, with whatever
|
|
18746
|
+
// processor is configured. The caller does not choose a parser by file type:
|
|
18747
|
+
// slides keep their pictures, charts and screenshots through OCR and the vision pass.
|
|
18748
|
+
case "pptx":
|
|
18749
|
+
case "ppt":
|
|
18750
|
+
case "pptm":
|
|
18751
|
+
case "odp": {
|
|
18752
|
+
const pdf = await convertOfficeToPdf(buffer, `.${stripped}`);
|
|
18753
|
+
const pdfPath = path3.join(tempDir, "converted.pdf");
|
|
18754
|
+
await fs2.promises.writeFile(pdfPath, pdf);
|
|
18755
|
+
result = await processPdf(pdf, { ...paths, source: pdfPath }, config, verbose, tolerateVisionFailures, onProgress, limiters);
|
|
18756
|
+
break;
|
|
18757
|
+
}
|
|
18625
18758
|
// Todo other file types with docx and officeparser
|
|
18626
18759
|
default:
|
|
18627
18760
|
throw new Error(`[EXULU] Unsupported file type: ${fileType}`);
|
|
@@ -18835,13 +18968,13 @@ async function documentProcessor({
|
|
|
18835
18968
|
let supportedTypes = [];
|
|
18836
18969
|
switch (config?.processor.name) {
|
|
18837
18970
|
case "officeparser":
|
|
18838
|
-
supportedTypes = ["docx", "pptx", "xlsx", "odt", "odp", "ods", "pdf", "rtf", "csv", "md", "html"];
|
|
18971
|
+
supportedTypes = ["docx", "pptx", "ppt", "pptm", "xlsx", "odt", "odp", "ods", "pdf", "rtf", "csv", "md", "html"];
|
|
18839
18972
|
break;
|
|
18840
18973
|
case "liteparse":
|
|
18841
18974
|
supportedTypes = ["pdf", "doc", "docx", "docm", "odt", "rtf", "ppt", "pptx", "pptm", "odp", "xls", "xlsx", "xlsm", "ods", "csv", "tsv"];
|
|
18842
18975
|
break;
|
|
18843
18976
|
case "mistral":
|
|
18844
|
-
supportedTypes = ["pdf", "docx", "doc", "txt", "md", "jpg", "jpeg", "png", "gif", "webp"];
|
|
18977
|
+
supportedTypes = ["pdf", "docx", "doc", "pptx", "ppt", "pptm", "odp", "txt", "md", "jpg", "jpeg", "png", "gif", "webp"];
|
|
18845
18978
|
break;
|
|
18846
18979
|
}
|
|
18847
18980
|
if (!supportedTypes.includes(fileType.toLowerCase())) {
|
|
@@ -18898,16 +19031,17 @@ var init_doc_processor = __esm({
|
|
|
18898
19031
|
init_resolve_ocr();
|
|
18899
19032
|
init_resolve_model();
|
|
18900
19033
|
init_limits();
|
|
19034
|
+
init_document_render_helpers();
|
|
18901
19035
|
loadFile = async (file, name, tempDir) => {
|
|
18902
19036
|
let filePath = file;
|
|
18903
19037
|
let fileType = name?.split(".").pop();
|
|
18904
19038
|
if (!fileType) {
|
|
18905
19039
|
throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
|
|
18906
19040
|
}
|
|
18907
|
-
const
|
|
19041
|
+
const UUID4 = (0, import_crypto4.randomUUID)();
|
|
18908
19042
|
let buffer;
|
|
18909
19043
|
if (Buffer.isBuffer(file)) {
|
|
18910
|
-
filePath = path3.join(tempDir, `${
|
|
19044
|
+
filePath = path3.join(tempDir, `${UUID4}.${fileType}`);
|
|
18911
19045
|
await fs2.promises.writeFile(filePath, file);
|
|
18912
19046
|
buffer = file;
|
|
18913
19047
|
} else {
|
|
@@ -18915,7 +19049,7 @@ var init_doc_processor = __esm({
|
|
|
18915
19049
|
if (filePath.startsWith("http")) {
|
|
18916
19050
|
const response = await fetch(filePath);
|
|
18917
19051
|
const array = await response.arrayBuffer();
|
|
18918
|
-
const tempFilePath = path3.join(tempDir, `${
|
|
19052
|
+
const tempFilePath = path3.join(tempDir, `${UUID4}.${fileType}`);
|
|
18919
19053
|
await fs2.promises.writeFile(tempFilePath, Buffer.from(array));
|
|
18920
19054
|
buffer = Buffer.from(array);
|
|
18921
19055
|
filePath = tempFilePath;
|
|
@@ -18962,7 +19096,17 @@ function degradedPagesOf(result) {
|
|
|
18962
19096
|
}
|
|
18963
19097
|
async function extractDocument(input) {
|
|
18964
19098
|
const config = input.exuluConfig?.attachments?.documentProcessor;
|
|
19099
|
+
const original = input;
|
|
18965
19100
|
if (config) {
|
|
19101
|
+
const ext = input.filename.slice(input.filename.lastIndexOf(".")).toLowerCase();
|
|
19102
|
+
if (isPresentationFormat(ext)) {
|
|
19103
|
+
try {
|
|
19104
|
+
const pdf = await (input.toPdf ?? convertOfficeToPdf)(input.bytes, ext);
|
|
19105
|
+
input = { ...input, bytes: pdf, filename: `${input.filename.slice(0, -ext.length)}.pdf` };
|
|
19106
|
+
} catch (error) {
|
|
19107
|
+
console.warn(`[EXULU] Could not render ${input.filename} to PDF:`, error instanceof Error ? error.message : String(error));
|
|
19108
|
+
}
|
|
19109
|
+
}
|
|
18966
19110
|
if (input.filename.toLowerCase().endsWith(".pdf")) {
|
|
18967
19111
|
const forTool = input.maxPages !== void 0;
|
|
18968
19112
|
const maxPages = input.maxPages ?? attachmentMaxPages();
|
|
@@ -18976,7 +19120,7 @@ async function extractDocument(input) {
|
|
|
18976
19120
|
console.warn(`[EXULU] ${input.filename} has ${pageCount} pages, over the ${forTool ? "document" : "attachment"} cap of ${maxPages}; not read.`);
|
|
18977
19121
|
return {
|
|
18978
19122
|
pages: [],
|
|
18979
|
-
text: (forTool ? tooLongForToolNotice : tooLongNotice)(
|
|
19123
|
+
text: (forTool ? tooLongForToolNotice : tooLongNotice)(original.filename, pageCount, maxPages),
|
|
18980
19124
|
engine: "document-processor",
|
|
18981
19125
|
tooLong: { pageCount, maxPages }
|
|
18982
19126
|
};
|
|
@@ -19012,7 +19156,7 @@ async function extractDocument(input) {
|
|
|
19012
19156
|
);
|
|
19013
19157
|
}
|
|
19014
19158
|
}
|
|
19015
|
-
const text = (await (input.officeParse ?? defaultOfficeParse)(
|
|
19159
|
+
const text = (await (input.officeParse ?? defaultOfficeParse)(original.bytes)).trim();
|
|
19016
19160
|
return { pages: [{ page: 1, text }], text, engine: "officeparser" };
|
|
19017
19161
|
}
|
|
19018
19162
|
function validateAttachmentsConfig(config, license) {
|
|
@@ -20595,7 +20739,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
|
|
|
20595
20739
|
});
|
|
20596
20740
|
|
|
20597
20741
|
// src/exulu/tool.ts
|
|
20598
|
-
var import_ai4, import_zod19,
|
|
20742
|
+
var import_ai4, import_zod19, import_node_crypto12, PUBLIC_TOOL_TYPES, ExuluTool;
|
|
20599
20743
|
var init_tool2 = __esm({
|
|
20600
20744
|
"src/exulu/tool.ts"() {
|
|
20601
20745
|
"use strict";
|
|
@@ -20603,7 +20747,7 @@ var init_tool2 = __esm({
|
|
|
20603
20747
|
import_ai4 = require("ai");
|
|
20604
20748
|
import_zod19 = require("zod");
|
|
20605
20749
|
init_sanitize_name();
|
|
20606
|
-
|
|
20750
|
+
import_node_crypto12 = require("crypto");
|
|
20607
20751
|
init_singleton();
|
|
20608
20752
|
init_resolve_model();
|
|
20609
20753
|
init_validate();
|
|
@@ -20748,7 +20892,7 @@ var init_tool2 = __esm({
|
|
|
20748
20892
|
throw new Error("Tool " + sanitizeName(this.name) + " not found in " + JSON.stringify(tools));
|
|
20749
20893
|
}
|
|
20750
20894
|
console.log("[EXULU] Tool found", this.name);
|
|
20751
|
-
const toolCallId = this.id + "_" + (0,
|
|
20895
|
+
const toolCallId = this.id + "_" + (0, import_node_crypto12.randomUUID)();
|
|
20752
20896
|
console.log("[EXULU] Calling tool execute", {
|
|
20753
20897
|
inputs,
|
|
20754
20898
|
toolCallId,
|
|
@@ -23778,6 +23922,153 @@ var import_express6 = require("express");
|
|
|
23778
23922
|
|
|
23779
23923
|
// src/exulu/routes.ts
|
|
23780
23924
|
init_cjs_shims();
|
|
23925
|
+
|
|
23926
|
+
// src/exulu/companion/operation-guard.ts
|
|
23927
|
+
init_cjs_shims();
|
|
23928
|
+
var import_graphql = require("graphql");
|
|
23929
|
+
var companionAllowedOperations = (tables) => {
|
|
23930
|
+
const allowed = /* @__PURE__ */ new Set();
|
|
23931
|
+
for (const table of tables) {
|
|
23932
|
+
const plural = table.name.plural.toLowerCase();
|
|
23933
|
+
const singular = table.name.singular.toLowerCase();
|
|
23934
|
+
allowed.add(`${plural}Pagination`);
|
|
23935
|
+
allowed.add(`${singular}ById`);
|
|
23936
|
+
allowed.add(`${plural}UpdateOneById`);
|
|
23937
|
+
}
|
|
23938
|
+
return allowed;
|
|
23939
|
+
};
|
|
23940
|
+
var fieldNamesOf = (operation, document2) => {
|
|
23941
|
+
const fragments = /* @__PURE__ */ new Map();
|
|
23942
|
+
for (const def of document2.definitions) {
|
|
23943
|
+
if (def.kind === import_graphql.Kind.FRAGMENT_DEFINITION) fragments.set(def.name.value, def.selectionSet);
|
|
23944
|
+
}
|
|
23945
|
+
const names = [];
|
|
23946
|
+
const seen = /* @__PURE__ */ new Set();
|
|
23947
|
+
const walk = (set) => {
|
|
23948
|
+
for (const selection of set.selections) {
|
|
23949
|
+
if (selection.kind === import_graphql.Kind.FIELD) names.push(selection.name.value);
|
|
23950
|
+
else if (selection.kind === import_graphql.Kind.INLINE_FRAGMENT) walk(selection.selectionSet);
|
|
23951
|
+
else {
|
|
23952
|
+
const name = selection.name.value;
|
|
23953
|
+
const fragment = fragments.get(name);
|
|
23954
|
+
if (fragment && !seen.has(name)) {
|
|
23955
|
+
seen.add(name);
|
|
23956
|
+
walk(fragment);
|
|
23957
|
+
}
|
|
23958
|
+
}
|
|
23959
|
+
}
|
|
23960
|
+
};
|
|
23961
|
+
walk(operation.selectionSet);
|
|
23962
|
+
return names;
|
|
23963
|
+
};
|
|
23964
|
+
var companionOperationGuard = (allowed) => ({
|
|
23965
|
+
async requestDidStart() {
|
|
23966
|
+
return {
|
|
23967
|
+
async didResolveOperation({ contextValue, document: document2, operation }) {
|
|
23968
|
+
if (!contextValue?.user?.via_companion) return;
|
|
23969
|
+
const names = operation ? fieldNamesOf(operation, document2) : [];
|
|
23970
|
+
const permitted = names.length > 0 && names.every((name) => name === "__typename" || allowed.has(name));
|
|
23971
|
+
if (!permitted) {
|
|
23972
|
+
throw new import_graphql.GraphQLError("This operation is not available through the companion server.", {
|
|
23973
|
+
extensions: { code: "FORBIDDEN", http: { status: 403 } }
|
|
23974
|
+
});
|
|
23975
|
+
}
|
|
23976
|
+
}
|
|
23977
|
+
};
|
|
23978
|
+
}
|
|
23979
|
+
});
|
|
23980
|
+
|
|
23981
|
+
// src/exulu/companion/request.ts
|
|
23982
|
+
init_cjs_shims();
|
|
23983
|
+
var import_node_crypto = require("crypto");
|
|
23984
|
+
var import_graphql2 = require("graphql");
|
|
23985
|
+
|
|
23986
|
+
// src/exulu/external-rate-limit.ts
|
|
23987
|
+
init_cjs_shims();
|
|
23988
|
+
var MINUTE_MS = 6e4;
|
|
23989
|
+
var HOUR_MS = 36e5;
|
|
23990
|
+
var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
|
|
23991
|
+
var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
|
|
23992
|
+
var windows = /* @__PURE__ */ new Map();
|
|
23993
|
+
var externalRateLimitExceeded = (userId, now = Date.now()) => {
|
|
23994
|
+
const state = windows.get(userId) ?? {
|
|
23995
|
+
minuteStart: now,
|
|
23996
|
+
minuteCount: 0,
|
|
23997
|
+
hourStart: now,
|
|
23998
|
+
hourCount: 0,
|
|
23999
|
+
lastSeen: now
|
|
24000
|
+
};
|
|
24001
|
+
if (now - state.minuteStart >= MINUTE_MS) {
|
|
24002
|
+
state.minuteStart = now;
|
|
24003
|
+
state.minuteCount = 0;
|
|
24004
|
+
}
|
|
24005
|
+
if (now - state.hourStart >= HOUR_MS) {
|
|
24006
|
+
state.hourStart = now;
|
|
24007
|
+
state.hourCount = 0;
|
|
24008
|
+
}
|
|
24009
|
+
state.minuteCount += 1;
|
|
24010
|
+
state.hourCount += 1;
|
|
24011
|
+
state.lastSeen = now;
|
|
24012
|
+
windows.set(userId, state);
|
|
24013
|
+
if (windows.size > 1e4) {
|
|
24014
|
+
for (const [key, value] of windows) {
|
|
24015
|
+
if (now - value.lastSeen >= HOUR_MS) windows.delete(key);
|
|
24016
|
+
}
|
|
24017
|
+
if (windows.size > 1e4) {
|
|
24018
|
+
const sorted = [...windows.entries()].sort(
|
|
24019
|
+
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
24020
|
+
);
|
|
24021
|
+
for (const [key] of sorted) {
|
|
24022
|
+
if (windows.size <= 1e4) break;
|
|
24023
|
+
windows.delete(key);
|
|
24024
|
+
}
|
|
24025
|
+
}
|
|
24026
|
+
}
|
|
24027
|
+
const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
|
|
24028
|
+
const hourLimitExceeded = state.hourCount > perHourLimit();
|
|
24029
|
+
const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
|
|
24030
|
+
if (limitExceeded) {
|
|
24031
|
+
const limits = {
|
|
24032
|
+
perMinute: perMinuteLimit(),
|
|
24033
|
+
perHour: perHourLimit()
|
|
24034
|
+
};
|
|
24035
|
+
const current = {
|
|
24036
|
+
minute: state.minuteCount,
|
|
24037
|
+
hour: state.hourCount
|
|
24038
|
+
};
|
|
24039
|
+
console.warn(
|
|
24040
|
+
`[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
|
|
24041
|
+
);
|
|
24042
|
+
}
|
|
24043
|
+
return limitExceeded;
|
|
24044
|
+
};
|
|
24045
|
+
var isExternalUser = (user) => {
|
|
24046
|
+
return user?.role?.name === "external";
|
|
24047
|
+
};
|
|
24048
|
+
|
|
24049
|
+
// src/exulu/companion/request.ts
|
|
24050
|
+
var COMPANION_HEADER = "x-exulu-companion";
|
|
24051
|
+
var companionRequestState = (headers, env = process.env) => {
|
|
24052
|
+
const received = headers[COMPANION_HEADER];
|
|
24053
|
+
if (received === void 0) return "absent";
|
|
24054
|
+
const expected = env.EXULU_COMPANION_KEY;
|
|
24055
|
+
if (typeof received !== "string" || received === "" || !expected) return "invalid";
|
|
24056
|
+
const a = Buffer.from(received);
|
|
24057
|
+
const b = Buffer.from(expected);
|
|
24058
|
+
if (a.length !== b.length) return "invalid";
|
|
24059
|
+
return (0, import_node_crypto.timingSafeEqual)(a, b) ? "valid" : "invalid";
|
|
24060
|
+
};
|
|
24061
|
+
var forbidden = (message) => new import_graphql2.GraphQLError(message, { extensions: { code: "FORBIDDEN", http: { status: 403 } } });
|
|
24062
|
+
var admitCompanionUser = (state, user) => {
|
|
24063
|
+
if (state === "absent") return user;
|
|
24064
|
+
if (state === "invalid") throw forbidden("Companion key rejected.");
|
|
24065
|
+
if (user.super_admin || !isExternalUser(user)) {
|
|
24066
|
+
throw forbidden("This account cannot be used through the companion server.");
|
|
24067
|
+
}
|
|
24068
|
+
return { ...user, via_companion: true };
|
|
24069
|
+
};
|
|
24070
|
+
|
|
24071
|
+
// src/exulu/routes.ts
|
|
23781
24072
|
var import_express2 = require("express");
|
|
23782
24073
|
|
|
23783
24074
|
// src/exulu/channels/lifecycle.ts
|
|
@@ -24402,8 +24693,8 @@ init_skill_author_tools();
|
|
|
24402
24693
|
|
|
24403
24694
|
// src/graphql/types/index.ts
|
|
24404
24695
|
init_cjs_shims();
|
|
24405
|
-
var
|
|
24406
|
-
var GraphQLDate = new
|
|
24696
|
+
var import_graphql3 = require("graphql");
|
|
24697
|
+
var GraphQLDate = new import_graphql3.GraphQLScalarType({
|
|
24407
24698
|
name: "Date",
|
|
24408
24699
|
description: "Date custom scalar type",
|
|
24409
24700
|
serialize(value) {
|
|
@@ -24428,10 +24719,10 @@ var GraphQLDate = new import_graphql.GraphQLScalarType({
|
|
|
24428
24719
|
return value;
|
|
24429
24720
|
},
|
|
24430
24721
|
parseLiteral(ast) {
|
|
24431
|
-
if (ast.kind ===
|
|
24722
|
+
if (ast.kind === import_graphql3.Kind.STRING) {
|
|
24432
24723
|
return new Date(ast.value);
|
|
24433
24724
|
}
|
|
24434
|
-
if (ast.kind ===
|
|
24725
|
+
if (ast.kind === import_graphql3.Kind.INT) {
|
|
24435
24726
|
return new Date(parseInt(ast.value, 10));
|
|
24436
24727
|
}
|
|
24437
24728
|
return null;
|
|
@@ -24509,6 +24800,14 @@ var contextItemsProcessorHandler = async (context, config, items, user, role) =>
|
|
|
24509
24800
|
init_access_control();
|
|
24510
24801
|
init_rbac_resolver();
|
|
24511
24802
|
|
|
24803
|
+
// src/graphql/schemas/rbac-field.ts
|
|
24804
|
+
init_cjs_shims();
|
|
24805
|
+
init_rbac_resolver();
|
|
24806
|
+
var resolveRbacField = async (table, parent, context) => {
|
|
24807
|
+
if (context.user?.via_companion === true) return null;
|
|
24808
|
+
return RBACResolver(context.db, table.name.singular, parent.id, parent.rights_mode);
|
|
24809
|
+
};
|
|
24810
|
+
|
|
24512
24811
|
// src/graphql/resolvers/index.ts
|
|
24513
24812
|
init_cjs_shims();
|
|
24514
24813
|
|
|
@@ -25863,7 +26162,7 @@ function registerImportQueue() {
|
|
|
25863
26162
|
|
|
25864
26163
|
// src/exulu/import/start-import.ts
|
|
25865
26164
|
init_cjs_shims();
|
|
25866
|
-
var
|
|
26165
|
+
var import_node_crypto13 = require("crypto");
|
|
25867
26166
|
|
|
25868
26167
|
// src/utils/serialize-error.ts
|
|
25869
26168
|
init_cjs_shims();
|
|
@@ -26050,7 +26349,7 @@ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
26050
26349
|
function isUuid(value) {
|
|
26051
26350
|
return UUID_RE.test(value);
|
|
26052
26351
|
}
|
|
26053
|
-
function
|
|
26352
|
+
function idOf3(value) {
|
|
26054
26353
|
if (typeof value === "string") return value;
|
|
26055
26354
|
if (value != null && typeof value === "object" && "id" in value) {
|
|
26056
26355
|
const id = value.id;
|
|
@@ -26071,14 +26370,14 @@ function canWrite(existing, user) {
|
|
|
26071
26370
|
);
|
|
26072
26371
|
}
|
|
26073
26372
|
if (existing.rights_mode === "roles") {
|
|
26074
|
-
const roleId =
|
|
26373
|
+
const roleId = idOf3(user.role);
|
|
26075
26374
|
if (!roleId) return false;
|
|
26076
26375
|
return grantsOf(existing).some(
|
|
26077
26376
|
(g) => g.access_type === "Role" && String(g.role_id) === roleId && g.rights === "write"
|
|
26078
26377
|
);
|
|
26079
26378
|
}
|
|
26080
26379
|
if (existing.rights_mode === "teams") {
|
|
26081
|
-
const teamId =
|
|
26380
|
+
const teamId = idOf3(user.team);
|
|
26082
26381
|
if (!teamId) return false;
|
|
26083
26382
|
return grantsOf(existing).some(
|
|
26084
26383
|
(g) => g.access_type === "Team" && String(g.team_id) === teamId && g.rights === "write"
|
|
@@ -26154,7 +26453,7 @@ async function uploadErrorReport(csv, contextId, jobResultId, config, user) {
|
|
|
26154
26453
|
function buildWorkerDeps(input) {
|
|
26155
26454
|
const { db: db2, config, context, contextId, jobResultId, stream, fields, mapping, access, options, user, log: log7 } = input;
|
|
26156
26455
|
const tableName = getTableName(contextId);
|
|
26157
|
-
const roleId =
|
|
26456
|
+
const roleId = idOf3(user.role);
|
|
26158
26457
|
const generateEmbeddingsOverwrite = options.skipEmbeddings ? false : void 0;
|
|
26159
26458
|
const rbac = rbacGrantsFor(access);
|
|
26160
26459
|
const total = typeof input.total === "number" && input.total > 0 ? input.total : void 0;
|
|
@@ -26241,7 +26540,7 @@ async function startImport(deps, args) {
|
|
|
26241
26540
|
if (running) {
|
|
26242
26541
|
throw new StartImportError("IMPORT_ALREADY_RUNNING");
|
|
26243
26542
|
}
|
|
26244
|
-
const id = (uuid ??
|
|
26543
|
+
const id = (uuid ?? import_node_crypto13.randomUUID)();
|
|
26245
26544
|
const label = `Import ${args.fileName}`;
|
|
26246
26545
|
const userSnapshot = {
|
|
26247
26546
|
id: user.id,
|
|
@@ -27622,6 +27921,7 @@ var markSessionSeenForViewer = async ({
|
|
|
27622
27921
|
|
|
27623
27922
|
// src/graphql/mutations/index.ts
|
|
27624
27923
|
init_skill_access();
|
|
27924
|
+
init_write_grant();
|
|
27625
27925
|
var VALID_RIGHTS_MODES3 = ["private", "users", "roles", "teams", "public"];
|
|
27626
27926
|
var postprocessDeletion = async ({
|
|
27627
27927
|
table,
|
|
@@ -27807,6 +28107,12 @@ function createMutations(table, contexts, tools, config) {
|
|
|
27807
28107
|
const validateWriteAccess = async (id, context) => {
|
|
27808
28108
|
try {
|
|
27809
28109
|
const { db: db2, user } = context;
|
|
28110
|
+
if (user.via_companion === true) {
|
|
28111
|
+
const row = table.RBAC === true ? await db2.from(tableNamePlural).select(["rights_mode"]).where({ id }).first() : void 0;
|
|
28112
|
+
const grant = !!row && await hasCompanionWriteGrant(db2, table.name.singular, id, user, row.rights_mode);
|
|
28113
|
+
if (grant) return true;
|
|
28114
|
+
throw new Error("Insufficient permissions to edit this record");
|
|
28115
|
+
}
|
|
27810
28116
|
if (user.super_admin === true) {
|
|
27811
28117
|
return true;
|
|
27812
28118
|
}
|
|
@@ -28157,6 +28463,14 @@ function createMutations(table, contexts, tools, config) {
|
|
|
28157
28463
|
[`${tableNamePlural}UpdateOneById`]: async (_, args, context, info) => {
|
|
28158
28464
|
const { db: db2, req } = context;
|
|
28159
28465
|
let { id, input } = args;
|
|
28466
|
+
if (context.user?.via_companion === true && ["rights_mode", "RBAC", "created_by", "id"].some(
|
|
28467
|
+
(key) => Object.prototype.hasOwnProperty.call(input ?? {}, key)
|
|
28468
|
+
)) {
|
|
28469
|
+
throw new Error("Access rights of a row cannot be changed through the companion server.");
|
|
28470
|
+
}
|
|
28471
|
+
if (context.user?.via_companion === true && args.generateEmbeddings === true) {
|
|
28472
|
+
throw new Error("Embedding generation cannot be requested through the companion server.");
|
|
28473
|
+
}
|
|
28160
28474
|
await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
|
|
28161
28475
|
await validateWriteAccess(id, context);
|
|
28162
28476
|
if (table.type === "items") {
|
|
@@ -29447,6 +29761,7 @@ function previousUserTexts(messages) {
|
|
|
29447
29761
|
}
|
|
29448
29762
|
|
|
29449
29763
|
// src/exulu/memory/recall.ts
|
|
29764
|
+
var FOLLOW_UP_MAX_NEW = 5;
|
|
29450
29765
|
var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
|
|
29451
29766
|
async function recallMemories({ agent, contexts, query, user, db: db2, previousUserTurns }) {
|
|
29452
29767
|
if (!agent?.memory || !query) return { ...EMPTY3 };
|
|
@@ -29458,29 +29773,112 @@ async function recallMemories({ agent, contexts, query, user, db: db2, previousU
|
|
|
29458
29773
|
const config = resolveMemoryConfig(agent.memory_config);
|
|
29459
29774
|
const collector = createRecallCollector(context, user, db2);
|
|
29460
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
|
+
};
|
|
29461
29812
|
let result;
|
|
29462
29813
|
try {
|
|
29463
|
-
result = await
|
|
29464
|
-
query: buildRecallQuery(query, previousUserTurns ?? []),
|
|
29465
|
-
itemFilters: [],
|
|
29466
|
-
chunkFilters: [],
|
|
29467
|
-
method: "hybridSearch",
|
|
29468
|
-
sort: { field: "updatedAt", direction: "desc" },
|
|
29469
|
-
trigger: "agent",
|
|
29470
|
-
limit: config.retrieval.limit,
|
|
29471
|
-
page: 1,
|
|
29472
|
-
user,
|
|
29473
|
-
role: user?.role?.id
|
|
29474
|
-
});
|
|
29814
|
+
result = await search(buildRecallQuery(query, previousUserTurns ?? []));
|
|
29475
29815
|
} catch (e) {
|
|
29476
29816
|
console.warn(`[EXULU] memory: recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
|
|
29477
|
-
return { collector, memoryItems
|
|
29817
|
+
return { collector, memoryItems, promptBlock: "", followUp };
|
|
29478
29818
|
}
|
|
29479
29819
|
const chunks = result?.chunks ?? [];
|
|
29480
|
-
if (chunks.length === 0) return { collector, memoryItems
|
|
29820
|
+
if (chunks.length === 0) return { collector, memoryItems, promptBlock: "", followUp };
|
|
29481
29821
|
await collector.addFromChunks(chunks, "prefetch");
|
|
29482
|
-
|
|
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");
|
|
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();
|
|
29483
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;
|
|
29484
29882
|
|
|
29485
29883
|
// src/exulu/generate-stream.ts
|
|
29486
29884
|
init_public_surface();
|
|
@@ -29807,7 +30205,7 @@ async function recordMemoryUsage(input) {
|
|
|
29807
30205
|
}
|
|
29808
30206
|
|
|
29809
30207
|
// src/exulu/generate-stream.ts
|
|
29810
|
-
var
|
|
30208
|
+
var import_node_crypto14 = require("crypto");
|
|
29811
30209
|
var processFilePartsInMessages = async (messages, offloadCtx) => {
|
|
29812
30210
|
const processedMessages = await Promise.all(
|
|
29813
30211
|
messages.map(async (message) => {
|
|
@@ -30186,7 +30584,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30186
30584
|
// Stop after the image_generation tool fires — the widget IS the
|
|
30187
30585
|
// assistant's response, no follow-up text turn is wanted (same
|
|
30188
30586
|
// reasoning as question_ask: the UI artifact is the message).
|
|
30189
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30587
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30190
30588
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30191
30589
|
});
|
|
30192
30590
|
console.log("[EXULU] Output: " + JSON.stringify(output, null, 2));
|
|
@@ -30238,7 +30636,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30238
30636
|
contextId: agent.memory,
|
|
30239
30637
|
agentId: agent.id,
|
|
30240
30638
|
session: session ?? null,
|
|
30241
|
-
messageId: output.response?.id ?? (0,
|
|
30639
|
+
messageId: output.response?.id ?? (0, import_node_crypto14.randomUUID)(),
|
|
30242
30640
|
userId: user?.id ?? null
|
|
30243
30641
|
});
|
|
30244
30642
|
}
|
|
@@ -30265,7 +30663,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30265
30663
|
}),
|
|
30266
30664
|
maxRetries: 2,
|
|
30267
30665
|
tools,
|
|
30268
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30666
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30269
30667
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30270
30668
|
});
|
|
30271
30669
|
if (statistics) {
|
|
@@ -30314,7 +30712,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30314
30712
|
contextId: agent.memory,
|
|
30315
30713
|
agentId: agent.id,
|
|
30316
30714
|
session: session ?? null,
|
|
30317
|
-
messageId: response?.id ?? (0,
|
|
30715
|
+
messageId: response?.id ?? (0, import_node_crypto14.randomUUID)(),
|
|
30318
30716
|
userId: user?.id ?? null
|
|
30319
30717
|
});
|
|
30320
30718
|
}
|
|
@@ -30634,7 +31032,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
30634
31032
|
// Log only — throwing here crashed the process (see stream-error.ts).
|
|
30635
31033
|
onError: onChatStreamError,
|
|
30636
31034
|
// todo allow configuring the step budget per skill
|
|
30637
|
-
prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
31035
|
+
prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
|
|
30638
31036
|
stopWhen: [(0, import_ai7.stepCountIs)(turnBudget), (0, import_ai7.hasToolCall)("image_generation")]
|
|
30639
31037
|
});
|
|
30640
31038
|
return {
|
|
@@ -30884,7 +31282,7 @@ init_singleton();
|
|
|
30884
31282
|
|
|
30885
31283
|
// src/exulu/email-inbound/intake.ts
|
|
30886
31284
|
init_cjs_shims();
|
|
30887
|
-
var
|
|
31285
|
+
var import_node_crypto17 = require("crypto");
|
|
30888
31286
|
init_client();
|
|
30889
31287
|
init_uppy();
|
|
30890
31288
|
init_singleton();
|
|
@@ -30892,7 +31290,7 @@ init_run_session();
|
|
|
30892
31290
|
|
|
30893
31291
|
// src/exulu/email-inbound/normalize.ts
|
|
30894
31292
|
init_cjs_shims();
|
|
30895
|
-
var
|
|
31293
|
+
var import_node_crypto15 = require("crypto");
|
|
30896
31294
|
var import_mailparser = require("mailparser");
|
|
30897
31295
|
var htmlToText = (html) => html.replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<[^>]+>/g, " ").replace(/ /gi, " ").replace(/</gi, "<").replace(/>/gi, ">").replace(/&/gi, "&").replace(/\s+/g, " ").trim();
|
|
30898
31296
|
var headerValueToString = (value) => {
|
|
@@ -30933,7 +31331,7 @@ async function parseRawMime(raw) {
|
|
|
30933
31331
|
return {
|
|
30934
31332
|
// Message-ID is the dedup key (spec §4.4.5). A missing header gets a
|
|
30935
31333
|
// deterministic content hash so webhook/job retries still dedup.
|
|
30936
|
-
messageId: parsed.messageId ?? `generated-${(0,
|
|
31334
|
+
messageId: parsed.messageId ?? `generated-${(0, import_node_crypto15.createHash)("sha256").update(raw).digest("hex")}`,
|
|
30937
31335
|
from: {
|
|
30938
31336
|
address: fromEntry.address.toLowerCase(),
|
|
30939
31337
|
...fromEntry.name ? { name: fromEntry.name } : {}
|
|
@@ -30953,7 +31351,7 @@ async function parseRawMime(raw) {
|
|
|
30953
31351
|
|
|
30954
31352
|
// src/exulu/email-inbound/adapters.ts
|
|
30955
31353
|
init_cjs_shims();
|
|
30956
|
-
var
|
|
31354
|
+
var import_node_crypto16 = require("crypto");
|
|
30957
31355
|
var import_node_stream = require("stream");
|
|
30958
31356
|
var import_busboy = __toESM(require("busboy"), 1);
|
|
30959
31357
|
var htmlToText2 = (html) => html.replace(/<\s*(script|style)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, "").replace(/<[^>]+>/g, " ").replace(/ /gi, " ").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">").replace(/\s+/g, " ").trim();
|
|
@@ -31018,7 +31416,7 @@ function jsonToInboundEmail(raw) {
|
|
|
31018
31416
|
const subject = typeof obj.subject === "string" ? obj.subject : "";
|
|
31019
31417
|
const html = typeof obj.html === "string" ? obj.html : void 0;
|
|
31020
31418
|
const text = typeof obj.text === "string" && obj.text ? obj.text : html ? htmlToText2(html) : "";
|
|
31021
|
-
const messageId = typeof obj.message_id === "string" && obj.message_id ? obj.message_id : `<${(0,
|
|
31419
|
+
const messageId = typeof obj.message_id === "string" && obj.message_id ? obj.message_id : `<${(0, import_node_crypto16.randomUUID)()}@webhook.local>`;
|
|
31022
31420
|
const looksLikeAttachment = (a) => !!a && typeof a === "object" && !Array.isArray(a) && (typeof a.content_base64 === "string" || typeof a.filename === "string");
|
|
31023
31421
|
let rawAttachments;
|
|
31024
31422
|
if (obj.attachments === void 0 || obj.attachments === null) rawAttachments = [];
|
|
@@ -31067,7 +31465,7 @@ var DEFAULT_SENDER_RATE_LIMIT_PER_HOUR = 10;
|
|
|
31067
31465
|
var DEFAULT_FILTERED_RUN_RETENTION = 200;
|
|
31068
31466
|
var FILTER_BODY_BYTE_CAP = 10 * 1024;
|
|
31069
31467
|
var AUTO_REPLY_PRECEDENCE = /* @__PURE__ */ new Set(["bulk", "junk", "list"]);
|
|
31070
|
-
var
|
|
31468
|
+
var HOUR_MS2 = 60 * 60 * 1e3;
|
|
31071
31469
|
var isAutoReply = (email) => {
|
|
31072
31470
|
const autoSubmitted = email.headers.get("auto-submitted");
|
|
31073
31471
|
if (autoSubmitted !== void 0 && autoSubmitted.trim().toLowerCase() !== "no") {
|
|
@@ -31099,7 +31497,7 @@ var senderAllowed = (address, allowedSenders) => {
|
|
|
31099
31497
|
var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
|
|
31100
31498
|
if (!redis) return true;
|
|
31101
31499
|
try {
|
|
31102
|
-
const currentBucket = Math.floor(now /
|
|
31500
|
+
const currentBucket = Math.floor(now / HOUR_MS2);
|
|
31103
31501
|
const currentKey = `${key}:${currentBucket}`;
|
|
31104
31502
|
const previousKey = `${key}:${currentBucket - 1}`;
|
|
31105
31503
|
const count2 = await redis.incr(currentKey);
|
|
@@ -31108,7 +31506,7 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
|
|
|
31108
31506
|
}
|
|
31109
31507
|
const previousRaw = await redis.get(previousKey);
|
|
31110
31508
|
const previous = previousRaw ? Number(previousRaw) : 0;
|
|
31111
|
-
const elapsedFraction = now %
|
|
31509
|
+
const elapsedFraction = now % HOUR_MS2 / HOUR_MS2;
|
|
31112
31510
|
const weighted = count2 + previous * (1 - elapsedFraction);
|
|
31113
31511
|
return weighted <= limitPerHour;
|
|
31114
31512
|
} catch (err4) {
|
|
@@ -31288,7 +31686,7 @@ var fireRun = async (opts) => {
|
|
|
31288
31686
|
}
|
|
31289
31687
|
const warningNote = warnings.length ? "\n\n[Hinweis des Systems] " + warnings.map((w) => INTAKE_WARNING_TEXTS[w]).join(" ") : "";
|
|
31290
31688
|
const initialMessage = {
|
|
31291
|
-
id: (0,
|
|
31689
|
+
id: (0, import_node_crypto17.randomUUID)(),
|
|
31292
31690
|
role: "user",
|
|
31293
31691
|
parts: [
|
|
31294
31692
|
{
|
|
@@ -32101,71 +32499,6 @@ var createRunLock = (redis) => ({
|
|
|
32101
32499
|
|
|
32102
32500
|
// src/exulu/channels/wiring.ts
|
|
32103
32501
|
init_cjs_shims();
|
|
32104
|
-
|
|
32105
|
-
// src/exulu/external-rate-limit.ts
|
|
32106
|
-
init_cjs_shims();
|
|
32107
|
-
var MINUTE_MS = 6e4;
|
|
32108
|
-
var HOUR_MS2 = 36e5;
|
|
32109
|
-
var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
|
|
32110
|
-
var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
|
|
32111
|
-
var windows = /* @__PURE__ */ new Map();
|
|
32112
|
-
var externalRateLimitExceeded = (userId, now = Date.now()) => {
|
|
32113
|
-
const state = windows.get(userId) ?? {
|
|
32114
|
-
minuteStart: now,
|
|
32115
|
-
minuteCount: 0,
|
|
32116
|
-
hourStart: now,
|
|
32117
|
-
hourCount: 0,
|
|
32118
|
-
lastSeen: now
|
|
32119
|
-
};
|
|
32120
|
-
if (now - state.minuteStart >= MINUTE_MS) {
|
|
32121
|
-
state.minuteStart = now;
|
|
32122
|
-
state.minuteCount = 0;
|
|
32123
|
-
}
|
|
32124
|
-
if (now - state.hourStart >= HOUR_MS2) {
|
|
32125
|
-
state.hourStart = now;
|
|
32126
|
-
state.hourCount = 0;
|
|
32127
|
-
}
|
|
32128
|
-
state.minuteCount += 1;
|
|
32129
|
-
state.hourCount += 1;
|
|
32130
|
-
state.lastSeen = now;
|
|
32131
|
-
windows.set(userId, state);
|
|
32132
|
-
if (windows.size > 1e4) {
|
|
32133
|
-
for (const [key, value] of windows) {
|
|
32134
|
-
if (now - value.lastSeen >= HOUR_MS2) windows.delete(key);
|
|
32135
|
-
}
|
|
32136
|
-
if (windows.size > 1e4) {
|
|
32137
|
-
const sorted = [...windows.entries()].sort(
|
|
32138
|
-
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
32139
|
-
);
|
|
32140
|
-
for (const [key] of sorted) {
|
|
32141
|
-
if (windows.size <= 1e4) break;
|
|
32142
|
-
windows.delete(key);
|
|
32143
|
-
}
|
|
32144
|
-
}
|
|
32145
|
-
}
|
|
32146
|
-
const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
|
|
32147
|
-
const hourLimitExceeded = state.hourCount > perHourLimit();
|
|
32148
|
-
const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
|
|
32149
|
-
if (limitExceeded) {
|
|
32150
|
-
const limits = {
|
|
32151
|
-
perMinute: perMinuteLimit(),
|
|
32152
|
-
perHour: perHourLimit()
|
|
32153
|
-
};
|
|
32154
|
-
const current = {
|
|
32155
|
-
minute: state.minuteCount,
|
|
32156
|
-
hour: state.hourCount
|
|
32157
|
-
};
|
|
32158
|
-
console.warn(
|
|
32159
|
-
`[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
|
|
32160
|
-
);
|
|
32161
|
-
}
|
|
32162
|
-
return limitExceeded;
|
|
32163
|
-
};
|
|
32164
|
-
var isExternalUser = (user) => {
|
|
32165
|
-
return user?.role?.name === "external";
|
|
32166
|
-
};
|
|
32167
|
-
|
|
32168
|
-
// src/exulu/channels/wiring.ts
|
|
32169
32502
|
var channelStoreFromRedis = (client2) => ({
|
|
32170
32503
|
set: (key, value, opts) => client2.set(key, value, opts.NX ? { EX: opts.EX, NX: true } : { EX: opts.EX }),
|
|
32171
32504
|
getDel: (key) => client2.getDel(key),
|
|
@@ -34123,6 +34456,18 @@ var processUiMessagesFlow = async ({
|
|
|
34123
34456
|
},
|
|
34124
34457
|
onFinish: async ({ messages }) => {
|
|
34125
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
|
+
}
|
|
34126
34471
|
console.log("[EXULU] Stream finished with messages:", messages);
|
|
34127
34472
|
console.log("[EXULU] Stream metadata", metadata);
|
|
34128
34473
|
await Promise.all([
|
|
@@ -35921,7 +36266,7 @@ var liveRecordingService = {
|
|
|
35921
36266
|
|
|
35922
36267
|
// src/exulu/email-inbound/trigger-config.ts
|
|
35923
36268
|
init_cjs_shims();
|
|
35924
|
-
var
|
|
36269
|
+
var import_node_crypto18 = require("crypto");
|
|
35925
36270
|
var import_safe_regex = __toESM(require("safe-regex"), 1);
|
|
35926
36271
|
var MAX_FILTER_PATTERN_LENGTH = 200;
|
|
35927
36272
|
var FILTER_FIELDS = [
|
|
@@ -36015,10 +36360,10 @@ function validateEmailTriggerConfig(raw) {
|
|
|
36015
36360
|
return config;
|
|
36016
36361
|
}
|
|
36017
36362
|
function generateTriggerSecret() {
|
|
36018
|
-
return (0,
|
|
36363
|
+
return (0, import_node_crypto18.randomBytes)(32).toString("base64url");
|
|
36019
36364
|
}
|
|
36020
36365
|
function generateSigningSecret() {
|
|
36021
|
-
return (0,
|
|
36366
|
+
return (0, import_node_crypto18.randomBytes)(32).toString("base64url");
|
|
36022
36367
|
}
|
|
36023
36368
|
|
|
36024
36369
|
// src/graphql/schemas/index.ts
|
|
@@ -36058,11 +36403,11 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
|
|
|
36058
36403
|
|
|
36059
36404
|
// src/exulu/email-inbound/webhook.ts
|
|
36060
36405
|
init_cjs_shims();
|
|
36061
|
-
var
|
|
36406
|
+
var import_node_crypto20 = require("crypto");
|
|
36062
36407
|
|
|
36063
36408
|
// src/exulu/email-inbound/verify-signature.ts
|
|
36064
36409
|
init_cjs_shims();
|
|
36065
|
-
var
|
|
36410
|
+
var import_node_crypto19 = require("crypto");
|
|
36066
36411
|
var SIGNATURE_REPLAY_WINDOW_SECONDS = 300;
|
|
36067
36412
|
var REPLAY_TTL_SECONDS = 900;
|
|
36068
36413
|
function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secret) {
|
|
@@ -36071,11 +36416,11 @@ function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secre
|
|
|
36071
36416
|
const provided = signatureHeader.slice("sha256=".length);
|
|
36072
36417
|
if (!/^[0-9a-f]+$/i.test(provided)) return false;
|
|
36073
36418
|
const message = timestampHeader ? Buffer.concat([Buffer.from(`${timestampHeader}.`), rawBody]) : rawBody;
|
|
36074
|
-
const expected = (0,
|
|
36419
|
+
const expected = (0, import_node_crypto19.createHmac)("sha256", secret).update(message).digest("hex");
|
|
36075
36420
|
const expectedBuf = Buffer.from(expected, "utf8");
|
|
36076
36421
|
const providedBuf = Buffer.from(provided.toLowerCase(), "utf8");
|
|
36077
36422
|
if (expectedBuf.length !== providedBuf.length) return false;
|
|
36078
|
-
return (0,
|
|
36423
|
+
return (0, import_node_crypto19.timingSafeEqual)(expectedBuf, providedBuf);
|
|
36079
36424
|
}
|
|
36080
36425
|
async function isReplay(redis, signature, timestamp) {
|
|
36081
36426
|
const ts = Number(timestamp);
|
|
@@ -36180,7 +36525,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
|
|
|
36180
36525
|
);
|
|
36181
36526
|
try {
|
|
36182
36527
|
const ext = format === "json" ? "json" : "eml";
|
|
36183
|
-
const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${(0,
|
|
36528
|
+
const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${(0, import_node_crypto20.randomUUID)()}.${ext}`, payloadBytes);
|
|
36184
36529
|
await deps.enqueueIntake({ s3Key, triggerId: trigger.id, format });
|
|
36185
36530
|
} catch (error) {
|
|
36186
36531
|
console.error("[EXULU-WEBHOOK] persist/enqueue failed", error);
|
|
@@ -36192,7 +36537,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
|
|
|
36192
36537
|
|
|
36193
36538
|
// src/graphql/schemas/index.ts
|
|
36194
36539
|
init_uppy();
|
|
36195
|
-
var
|
|
36540
|
+
var import_node_crypto21 = require("crypto");
|
|
36196
36541
|
init_memory_base();
|
|
36197
36542
|
|
|
36198
36543
|
// src/graphql/resolvers/memory-base-stats.ts
|
|
@@ -36510,7 +36855,7 @@ var epochMs = (d) => {
|
|
|
36510
36855
|
const date = d instanceof Date ? d : typeof d === "string" || typeof d === "number" ? new Date(d) : null;
|
|
36511
36856
|
return date && Number.isFinite(date.getTime()) ? date.getTime() : null;
|
|
36512
36857
|
};
|
|
36513
|
-
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;
|
|
36514
36859
|
var clamp = (limit, fallback, max) => {
|
|
36515
36860
|
const asked = limit == null ? NaN : Number(limit);
|
|
36516
36861
|
return Math.max(1, Math.min(Number.isFinite(asked) ? asked : fallback, max));
|
|
@@ -36639,7 +36984,7 @@ async function contextMapItem({
|
|
|
36639
36984
|
user,
|
|
36640
36985
|
itemId
|
|
36641
36986
|
}) {
|
|
36642
|
-
if (!
|
|
36987
|
+
if (!UUID2.test(itemId)) return null;
|
|
36643
36988
|
const items = getTableName(context.id);
|
|
36644
36989
|
const table = convertContextToTableDefinition(context);
|
|
36645
36990
|
let q = db2(`${items} as items`).where("items.id", itemId).whereRaw("items.archived IS NOT TRUE");
|
|
@@ -36678,7 +37023,7 @@ async function contextMapEdges({
|
|
|
36678
37023
|
mode = "DOCUMENTS",
|
|
36679
37024
|
limit
|
|
36680
37025
|
}) {
|
|
36681
|
-
if (!
|
|
37026
|
+
if (!UUID2.test(String(nodeId ?? ""))) return [];
|
|
36682
37027
|
const chunks = getChunksTableName(context.id);
|
|
36683
37028
|
const items = getTableName(context.id);
|
|
36684
37029
|
if (!await db2.schema.hasTable(chunks)) return [];
|
|
@@ -38030,13 +38375,7 @@ type PageInfo {
|
|
|
38030
38375
|
if (!resolvers2[rbacResolverName]) {
|
|
38031
38376
|
resolvers2[rbacResolverName] = {};
|
|
38032
38377
|
}
|
|
38033
|
-
resolvers2[rbacResolverName].RBAC = async (parent, args, context) =>
|
|
38034
|
-
const { db: db2 } = context;
|
|
38035
|
-
const resourceId = parent.id;
|
|
38036
|
-
const entityName = table.name.singular;
|
|
38037
|
-
const rights_mode = parent.rights_mode;
|
|
38038
|
-
return RBACResolver(db2, entityName, resourceId, rights_mode);
|
|
38039
|
-
};
|
|
38378
|
+
resolvers2[rbacResolverName].RBAC = async (parent, args, context) => resolveRbacField(table, parent, context);
|
|
38040
38379
|
}
|
|
38041
38380
|
}
|
|
38042
38381
|
typeDefs += `
|
|
@@ -38734,7 +39073,7 @@ type EmbeddingModelOption {
|
|
|
38734
39073
|
const ext = format === "json" ? "json" : "eml";
|
|
38735
39074
|
const fullKey = await uploadFile(
|
|
38736
39075
|
bytes,
|
|
38737
|
-
`${EMAIL_INBOUND_S3_PREFIX}${(0,
|
|
39076
|
+
`${EMAIL_INBOUND_S3_PREFIX}${(0, import_node_crypto21.randomUUID)()}.${ext}`,
|
|
38738
39077
|
config,
|
|
38739
39078
|
{ contentType: "application/octet-stream" },
|
|
38740
39079
|
void 0,
|
|
@@ -40041,7 +40380,7 @@ var import_body_parser = __toESM(require("body-parser"), 1);
|
|
|
40041
40380
|
var import_crypto_js7 = require("crypto-js");
|
|
40042
40381
|
var import_openai = require("openai");
|
|
40043
40382
|
var import_fs5 = __toESM(require("fs"), 1);
|
|
40044
|
-
var
|
|
40383
|
+
var import_node_crypto26 = require("crypto");
|
|
40045
40384
|
var import_api3 = require("@opentelemetry/api");
|
|
40046
40385
|
init_check_record_access();
|
|
40047
40386
|
var import_jszip4 = __toESM(require("jszip"), 1);
|
|
@@ -40049,7 +40388,7 @@ var import_jszip4 = __toESM(require("jszip"), 1);
|
|
|
40049
40388
|
// src/skills/bundled.ts
|
|
40050
40389
|
init_cjs_shims();
|
|
40051
40390
|
var import_jszip3 = __toESM(require("jszip"), 1);
|
|
40052
|
-
var
|
|
40391
|
+
var import_node_crypto22 = require("crypto");
|
|
40053
40392
|
|
|
40054
40393
|
// src/skills/bundled.generated.ts
|
|
40055
40394
|
init_cjs_shims();
|
|
@@ -40074,7 +40413,7 @@ var BUNDLED_SKILLS = [
|
|
|
40074
40413
|
init_frontmatter();
|
|
40075
40414
|
var BUNDLED_LABEL = "Bundled with the IMP";
|
|
40076
40415
|
function bundledSkillHash(skill) {
|
|
40077
|
-
const h = (0,
|
|
40416
|
+
const h = (0, import_node_crypto22.createHash)("sha256");
|
|
40078
40417
|
for (const path4 of Object.keys(skill.files).sort()) {
|
|
40079
40418
|
h.update(path4).update("\0").update(skill.files[path4]).update("\0");
|
|
40080
40419
|
}
|
|
@@ -40135,7 +40474,7 @@ async function seedBundledSkills({
|
|
|
40135
40474
|
log7(`"${skill.name}" updated to v${nextVersion}`);
|
|
40136
40475
|
continue;
|
|
40137
40476
|
}
|
|
40138
|
-
const skillId = (0,
|
|
40477
|
+
const skillId = (0, import_node_crypto22.randomUUID)();
|
|
40139
40478
|
await extractBundleToVersion({ bytes: await bundledSkillZip(skill), skillId, version: 1, config });
|
|
40140
40479
|
await db2("skills").insert({
|
|
40141
40480
|
id: skillId,
|
|
@@ -40247,7 +40586,7 @@ var persistThroughDisconnect = () => ({
|
|
|
40247
40586
|
|
|
40248
40587
|
// src/exulu/compact-session.ts
|
|
40249
40588
|
init_cjs_shims();
|
|
40250
|
-
var
|
|
40589
|
+
var import_node_crypto23 = require("crypto");
|
|
40251
40590
|
var import_ai14 = require("ai");
|
|
40252
40591
|
init_truncate_tool_output();
|
|
40253
40592
|
init_context_budget();
|
|
@@ -40353,7 +40692,7 @@ Focus especially on: ${steer.trim()}` : SUMMARY_SYSTEM;
|
|
|
40353
40692
|
...steer?.trim() ? { steer: steer.trim() } : {}
|
|
40354
40693
|
};
|
|
40355
40694
|
const checkpoint = {
|
|
40356
|
-
id: `compaction_${(0,
|
|
40695
|
+
id: `compaction_${(0, import_node_crypto23.randomUUID)()}`,
|
|
40357
40696
|
role: "user",
|
|
40358
40697
|
parts: [{ type: "text", text: `[Conversation summary \u2014 earlier messages were compacted]
|
|
40359
40698
|
|
|
@@ -41389,13 +41728,13 @@ function isInside2(key, fullPrefix) {
|
|
|
41389
41728
|
return key.startsWith(fullPrefix) && !key.includes("..");
|
|
41390
41729
|
}
|
|
41391
41730
|
function registerProjectFileRoutes(app, deps) {
|
|
41392
|
-
const
|
|
41731
|
+
const idOf4 = (req) => String(req.params.projectId ?? "");
|
|
41393
41732
|
const rowId = (authed) => String(authed.project.id);
|
|
41394
41733
|
const listObjects = async (projectId) => (await deps.s3.list(projectFilePrefix(projectId, deps.s3prefix).projectPrefix)).filter(
|
|
41395
41734
|
(o) => !o.key.endsWith("/")
|
|
41396
41735
|
);
|
|
41397
41736
|
app.get("/projects/:projectId/files", async (req, res) => {
|
|
41398
|
-
const projectId =
|
|
41737
|
+
const projectId = idOf4(req);
|
|
41399
41738
|
const authed = await deps.loadAuthedProject(req, res, projectId, "read");
|
|
41400
41739
|
if (!authed) return;
|
|
41401
41740
|
const canWrite2 = await deps.canWrite(authed.user, authed.project);
|
|
@@ -41416,7 +41755,7 @@ function registerProjectFileRoutes(app, deps) {
|
|
|
41416
41755
|
res.json({ canWrite: canWrite2, files });
|
|
41417
41756
|
});
|
|
41418
41757
|
app.post("/projects/:projectId/files/upload-sign", async (req, res) => {
|
|
41419
|
-
const projectId =
|
|
41758
|
+
const projectId = idOf4(req);
|
|
41420
41759
|
const authed = await deps.loadAuthedProject(req, res, projectId, "write");
|
|
41421
41760
|
if (!authed) return;
|
|
41422
41761
|
const { filename, contentType, overwrite } = req.body ?? {};
|
|
@@ -41456,7 +41795,7 @@ function registerProjectFileRoutes(app, deps) {
|
|
|
41456
41795
|
}
|
|
41457
41796
|
});
|
|
41458
41797
|
app.delete("/projects/:projectId/files", async (req, res) => {
|
|
41459
|
-
const projectId =
|
|
41798
|
+
const projectId = idOf4(req);
|
|
41460
41799
|
const key = req.query.key;
|
|
41461
41800
|
if (!key || typeof key !== "string") {
|
|
41462
41801
|
res.status(400).json({ detail: "Missing or invalid 'key' query parameter." });
|
|
@@ -41481,7 +41820,7 @@ function registerProjectFileRoutes(app, deps) {
|
|
|
41481
41820
|
if (!req.headers.authorization && typeof req.query.auth === "string") {
|
|
41482
41821
|
req.headers.authorization = `Bearer ${req.query.auth}`;
|
|
41483
41822
|
}
|
|
41484
|
-
const projectId =
|
|
41823
|
+
const projectId = idOf4(req);
|
|
41485
41824
|
const key = req.query.key;
|
|
41486
41825
|
if (!key || typeof key !== "string") {
|
|
41487
41826
|
res.status(400).json({ detail: "Missing or invalid 'key' query parameter." });
|
|
@@ -41510,7 +41849,7 @@ function registerProjectFileRoutes(app, deps) {
|
|
|
41510
41849
|
}
|
|
41511
41850
|
});
|
|
41512
41851
|
app.post("/projects/:projectId/files/promote", async (req, res) => {
|
|
41513
|
-
const projectId =
|
|
41852
|
+
const projectId = idOf4(req);
|
|
41514
41853
|
const { sessionId, keys, overwrite } = req.body ?? {};
|
|
41515
41854
|
if (typeof sessionId !== "string" || !sessionId || !Array.isArray(keys)) {
|
|
41516
41855
|
res.status(400).json({ detail: "sessionId (string) and keys (array) are required." });
|
|
@@ -41597,9 +41936,142 @@ function registerViewerIdentityRoutes(app, deps) {
|
|
|
41597
41936
|
});
|
|
41598
41937
|
}
|
|
41599
41938
|
|
|
41939
|
+
// src/exulu/companion/external-share-route.ts
|
|
41940
|
+
init_cjs_shims();
|
|
41941
|
+
init_shared_artifacts();
|
|
41942
|
+
var SHARED_ARTIFACT_EXTERNAL_PATH = "/shared-artifacts/:name/external";
|
|
41943
|
+
function registerExternalShareRoute(app, deps) {
|
|
41944
|
+
app.get(SHARED_ARTIFACT_EXTERNAL_PATH, async (req, res) => {
|
|
41945
|
+
const notFound = () => res.status(404).json({ detail: "Not found." });
|
|
41946
|
+
try {
|
|
41947
|
+
if (companionRequestState(req.headers, deps.env ?? process.env) !== "valid") {
|
|
41948
|
+
notFound();
|
|
41949
|
+
return;
|
|
41950
|
+
}
|
|
41951
|
+
const db2 = await deps.getDb();
|
|
41952
|
+
const row = await getSharedArtifactByName(db2, req.params.name ?? "");
|
|
41953
|
+
if (!row || isExpired(row.expires_at, /* @__PURE__ */ new Date()) || row.auth_mode !== "regular" || row.external_access !== true) {
|
|
41954
|
+
notFound();
|
|
41955
|
+
return;
|
|
41956
|
+
}
|
|
41957
|
+
const grants = await db2("rbac").where({ entity: "shared_artifact", target_resource_id: row.id, access_type: "Team" }).select("team_id");
|
|
41958
|
+
const teams = await teamNamesByIds(db2, grants.map((g) => g.team_id));
|
|
41959
|
+
if (validateExternalAccess({
|
|
41960
|
+
external_access: true,
|
|
41961
|
+
auth_mode: row.auth_mode,
|
|
41962
|
+
rights_mode: row.rights_mode,
|
|
41963
|
+
teams
|
|
41964
|
+
}) !== null) {
|
|
41965
|
+
notFound();
|
|
41966
|
+
return;
|
|
41967
|
+
}
|
|
41968
|
+
res.status(204).end();
|
|
41969
|
+
} catch (e) {
|
|
41970
|
+
console.error("[EXULU] companion external check failed", e);
|
|
41971
|
+
notFound();
|
|
41972
|
+
}
|
|
41973
|
+
});
|
|
41974
|
+
}
|
|
41975
|
+
|
|
41976
|
+
// src/exulu/companion/status-routes.ts
|
|
41977
|
+
init_cjs_shims();
|
|
41978
|
+
|
|
41979
|
+
// src/exulu/companion/status.ts
|
|
41980
|
+
init_cjs_shims();
|
|
41981
|
+
var HEALTH_TIMEOUT_MS = 5e3;
|
|
41982
|
+
var CACHE_TTL_MS2 = 3e4;
|
|
41983
|
+
var VERSION_RE = /^[\w.+-]{1,32}$/;
|
|
41984
|
+
var HOST_RE = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:\d{1,5})?$/;
|
|
41985
|
+
var checkCompanion = async (deps) => {
|
|
41986
|
+
const host = deps.env.EXULU_COMPANION_HOST;
|
|
41987
|
+
const key = deps.env.EXULU_COMPANION_KEY;
|
|
41988
|
+
if (!host || !key || !HOST_RE.test(host)) return { state: "not_configured" };
|
|
41989
|
+
const checkedAt = deps.now().toISOString();
|
|
41990
|
+
const unreachable = { state: "unreachable", host, checkedAt };
|
|
41991
|
+
try {
|
|
41992
|
+
const res = await deps.fetch(`https://${host}/_companion/health`, {
|
|
41993
|
+
method: "GET",
|
|
41994
|
+
headers: { [COMPANION_HEADER]: key },
|
|
41995
|
+
redirect: "error",
|
|
41996
|
+
signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS)
|
|
41997
|
+
});
|
|
41998
|
+
if (res.status !== 200) return unreachable;
|
|
41999
|
+
const body = await res.json();
|
|
42000
|
+
if (!body || typeof body !== "object" || typeof body.version !== "string" || !VERSION_RE.test(body.version) || typeof body.upstream !== "boolean") {
|
|
42001
|
+
return unreachable;
|
|
42002
|
+
}
|
|
42003
|
+
const { version, upstream } = body;
|
|
42004
|
+
if (version.includes(key)) return unreachable;
|
|
42005
|
+
return { state: upstream ? "connected" : "no_tunnel", host, version, checkedAt };
|
|
42006
|
+
} catch {
|
|
42007
|
+
return unreachable;
|
|
42008
|
+
}
|
|
42009
|
+
};
|
|
42010
|
+
var createCompanionStatusCache = (deps) => {
|
|
42011
|
+
let cached = null;
|
|
42012
|
+
return {
|
|
42013
|
+
get: async (refresh = false) => {
|
|
42014
|
+
const t = deps.now().getTime();
|
|
42015
|
+
if (!refresh && cached && t - cached.at < CACHE_TTL_MS2 && t >= cached.at) return cached.value;
|
|
42016
|
+
const value = await checkCompanion(deps);
|
|
42017
|
+
cached = { at: t, value };
|
|
42018
|
+
return value;
|
|
42019
|
+
}
|
|
42020
|
+
};
|
|
42021
|
+
};
|
|
42022
|
+
var cachedCompanionStatus = createCompanionStatusCache({
|
|
42023
|
+
env: process.env,
|
|
42024
|
+
fetch: globalThis.fetch,
|
|
42025
|
+
now: () => /* @__PURE__ */ new Date()
|
|
42026
|
+
});
|
|
42027
|
+
|
|
42028
|
+
// src/exulu/companion/status-routes.ts
|
|
42029
|
+
function registerCompanionStatusRoutes(app, deps) {
|
|
42030
|
+
const status = deps.status ?? cachedCompanionStatus;
|
|
42031
|
+
const requireSuperAdmin = async (req, res) => {
|
|
42032
|
+
const auth = await deps.authenticate(req);
|
|
42033
|
+
if (!auth.user?.id) {
|
|
42034
|
+
res.status(auth.code ?? 401).json({ detail: auth.message });
|
|
42035
|
+
return false;
|
|
42036
|
+
}
|
|
42037
|
+
if (auth.user.super_admin !== true) {
|
|
42038
|
+
res.status(403).json({ detail: "Only a super admin can view the companion server." });
|
|
42039
|
+
return false;
|
|
42040
|
+
}
|
|
42041
|
+
return true;
|
|
42042
|
+
};
|
|
42043
|
+
app.get("/companion/status", async (req, res) => {
|
|
42044
|
+
if (!await requireSuperAdmin(req, res)) return;
|
|
42045
|
+
res.json(await status.get(req.query.refresh === "1"));
|
|
42046
|
+
});
|
|
42047
|
+
app.get("/companion/released", async (req, res) => {
|
|
42048
|
+
if (!await requireSuperAdmin(req, res)) return;
|
|
42049
|
+
try {
|
|
42050
|
+
const db2 = await deps.getDb();
|
|
42051
|
+
const shares = await db2("shared_artifacts").where({ external_access: true }).select("id", "name");
|
|
42052
|
+
const grants = shares.length ? await db2("rbac").where({ entity: "shared_artifact", access_type: "Team" }).whereIn("target_resource_id", shares.map((s) => s.id)).select("target_resource_id", "team_id") : [];
|
|
42053
|
+
const teamIds = [...new Set(grants.map((g) => g.team_id).filter(Boolean))];
|
|
42054
|
+
const teams = teamIds.length ? await db2("teams").whereIn("id", teamIds).select("id", "name") : [];
|
|
42055
|
+
const users = teamIds.length ? await db2("users").where({ type: "external" }).whereIn("team", teamIds).select("team") : [];
|
|
42056
|
+
const counts = /* @__PURE__ */ new Map();
|
|
42057
|
+
for (const u of users) counts.set(u.team, (counts.get(u.team) ?? 0) + 1);
|
|
42058
|
+
const teamName = new Map(teams.map((t) => [t.id, t.name]));
|
|
42059
|
+
res.json({
|
|
42060
|
+
items: shares.map((s) => ({
|
|
42061
|
+
name: s.name,
|
|
42062
|
+
teams: [...new Set(grants.filter((g) => g.target_resource_id === s.id).map((g) => g.team_id))].filter((id) => teamName.has(id)).map((id) => ({ id, name: teamName.get(id), users: counts.get(id) ?? 0 }))
|
|
42063
|
+
}))
|
|
42064
|
+
});
|
|
42065
|
+
} catch (e) {
|
|
42066
|
+
console.error("[EXULU] companion released listing failed", e);
|
|
42067
|
+
res.status(500).json({ detail: "Failed to list released artifacts." });
|
|
42068
|
+
}
|
|
42069
|
+
});
|
|
42070
|
+
}
|
|
42071
|
+
|
|
41600
42072
|
// src/exulu/tool-api-route.ts
|
|
41601
42073
|
init_cjs_shims();
|
|
41602
|
-
var
|
|
42074
|
+
var import_node_crypto24 = require("crypto");
|
|
41603
42075
|
init_progress();
|
|
41604
42076
|
var TOOL_API_ROUTE_PATH = "/tools/:id";
|
|
41605
42077
|
var toolConfigDefaults = (tool5) => Object.fromEntries(
|
|
@@ -41640,7 +42112,7 @@ function registerToolApiRoutes(app, deps) {
|
|
|
41640
42112
|
res.status(500).json({ detail: "Tool has no execute function." });
|
|
41641
42113
|
return;
|
|
41642
42114
|
}
|
|
41643
|
-
const toolCallId = `${tool5.id}_${(0,
|
|
42115
|
+
const toolCallId = `${tool5.id}_${(0, import_node_crypto24.randomUUID)()}`;
|
|
41644
42116
|
const started = Date.now();
|
|
41645
42117
|
let output;
|
|
41646
42118
|
let status = "ok";
|
|
@@ -41724,6 +42196,23 @@ function registerCreateShareRoute(app, deps) {
|
|
|
41724
42196
|
res.status(400).json({ detail: valid.message });
|
|
41725
42197
|
return;
|
|
41726
42198
|
}
|
|
42199
|
+
if (!mayChangeExternalRelease(auth.user, req.body.external_access, false)) {
|
|
42200
|
+
res.status(403).json({ detail: EXTERNAL_SUPER_ADMIN_ONLY });
|
|
42201
|
+
return;
|
|
42202
|
+
}
|
|
42203
|
+
if (req.body.external_access !== void 0) {
|
|
42204
|
+
const teamIds = req.body.external_access === true && Array.isArray(req.body.rbac?.teams) ? req.body.rbac.teams.map((t) => t?.id) : [];
|
|
42205
|
+
const externalError = validateExternalAccess({
|
|
42206
|
+
external_access: req.body.external_access,
|
|
42207
|
+
auth_mode: req.body.auth_mode,
|
|
42208
|
+
rights_mode: req.body.rights_mode ?? "private",
|
|
42209
|
+
teams: await teamNamesByIds(db2, teamIds)
|
|
42210
|
+
});
|
|
42211
|
+
if (externalError) {
|
|
42212
|
+
res.status(400).json({ detail: externalError });
|
|
42213
|
+
return;
|
|
42214
|
+
}
|
|
42215
|
+
}
|
|
41727
42216
|
const details = planDetails({ ...req.body, archived: void 0 }, now);
|
|
41728
42217
|
if (!details.ok) {
|
|
41729
42218
|
res.status(400).json({ detail: details.message });
|
|
@@ -41754,6 +42243,7 @@ function registerCreateShareRoute(app, deps) {
|
|
|
41754
42243
|
password_hash,
|
|
41755
42244
|
expires_at: req.body.expires_at ?? null,
|
|
41756
42245
|
content_type: req.body.content_type ?? null,
|
|
42246
|
+
external_access: req.body.external_access === true,
|
|
41757
42247
|
rights_mode,
|
|
41758
42248
|
created_by: auth.user.id,
|
|
41759
42249
|
...details.patch,
|
|
@@ -44228,7 +44718,7 @@ var import_multer = __toESM(require("multer"), 1);
|
|
|
44228
44718
|
init_cjs_shims();
|
|
44229
44719
|
var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
|
|
44230
44720
|
var LOG_PREFIX3 = "[EXULU-CHANNEL]";
|
|
44231
|
-
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;
|
|
44232
44722
|
var RATE_WINDOW_MS2 = 6e4;
|
|
44233
44723
|
var RATE_MAX_REQUESTS2 = 300;
|
|
44234
44724
|
var rateWindowStart2 = 0;
|
|
@@ -44286,7 +44776,7 @@ var createChannelWebhookHandler = (deps) => async (req, res) => {
|
|
|
44286
44776
|
return;
|
|
44287
44777
|
}
|
|
44288
44778
|
const channelId = String(req.params?.channelId ?? "");
|
|
44289
|
-
if (!
|
|
44779
|
+
if (!UUID3.test(channelId)) {
|
|
44290
44780
|
res.status(404).json({ detail: "not found" });
|
|
44291
44781
|
return;
|
|
44292
44782
|
}
|
|
@@ -44579,7 +45069,7 @@ init_flow();
|
|
|
44579
45069
|
|
|
44580
45070
|
// src/exulu/recall/verify.ts
|
|
44581
45071
|
init_cjs_shims();
|
|
44582
|
-
var
|
|
45072
|
+
var import_node_crypto25 = require("crypto");
|
|
44583
45073
|
var TOLERANCE_SECONDS = 5 * 60;
|
|
44584
45074
|
var header = (headers, ...names) => {
|
|
44585
45075
|
for (const name of names) {
|
|
@@ -44597,7 +45087,7 @@ var safeEqual = (a, b) => {
|
|
|
44597
45087
|
const bufA = Buffer.from(a);
|
|
44598
45088
|
const bufB = Buffer.from(b);
|
|
44599
45089
|
if (bufA.length !== bufB.length) return false;
|
|
44600
|
-
return (0,
|
|
45090
|
+
return (0, import_node_crypto25.timingSafeEqual)(bufA, bufB);
|
|
44601
45091
|
};
|
|
44602
45092
|
var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
|
|
44603
45093
|
if (!secret) {
|
|
@@ -44619,7 +45109,7 @@ var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()
|
|
|
44619
45109
|
}
|
|
44620
45110
|
const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
|
|
44621
45111
|
const signedContent = `${id}.${timestamp}.${body}`;
|
|
44622
|
-
const expected = (0,
|
|
45112
|
+
const expected = (0, import_node_crypto25.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
|
|
44623
45113
|
const passed = signatureHeader.split(" ").some((entry) => {
|
|
44624
45114
|
const [, sig] = entry.split(",");
|
|
44625
45115
|
return !!sig && safeEqual(sig, expected);
|
|
@@ -44992,7 +45482,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
44992
45482
|
const server = new import_server5.ApolloServer({
|
|
44993
45483
|
cache: new import_utils5.InMemoryLRUCache(),
|
|
44994
45484
|
schema: schema7,
|
|
44995
|
-
introspection: true
|
|
45485
|
+
introspection: true,
|
|
45486
|
+
plugins: [
|
|
45487
|
+
companionOperationGuard(
|
|
45488
|
+
companionAllowedOperations((contexts ?? []).map(convertContextToTableDefinition))
|
|
45489
|
+
)
|
|
45490
|
+
]
|
|
44996
45491
|
});
|
|
44997
45492
|
await server.start();
|
|
44998
45493
|
app.use(
|
|
@@ -45011,7 +45506,10 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
45011
45506
|
return {
|
|
45012
45507
|
req,
|
|
45013
45508
|
db: db2,
|
|
45014
|
-
user:
|
|
45509
|
+
user: admitCompanionUser(
|
|
45510
|
+
companionRequestState(req.headers),
|
|
45511
|
+
authenticationResult.user
|
|
45512
|
+
)
|
|
45015
45513
|
};
|
|
45016
45514
|
}
|
|
45017
45515
|
})
|
|
@@ -45146,7 +45644,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
45146
45644
|
inputs: payload
|
|
45147
45645
|
};
|
|
45148
45646
|
await queue.queue.add("email-intake", jobData, {
|
|
45149
|
-
jobId: (0,
|
|
45647
|
+
jobId: (0, import_node_crypto26.randomUUID)(),
|
|
45150
45648
|
attempts: 3,
|
|
45151
45649
|
removeOnComplete: 5e3,
|
|
45152
45650
|
removeOnFail: 1e4,
|
|
@@ -45554,7 +46052,7 @@ ${customInstructions}` : agent.instructions,
|
|
|
45554
46052
|
contextId: agent.memory,
|
|
45555
46053
|
agentId: agent.id,
|
|
45556
46054
|
session: headers.session ?? null,
|
|
45557
|
-
messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0,
|
|
46055
|
+
messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto26.randomUUID)(),
|
|
45558
46056
|
userId: user?.id ?? null
|
|
45559
46057
|
});
|
|
45560
46058
|
}
|
|
@@ -46247,7 +46745,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
|
|
|
46247
46745
|
const keys = [];
|
|
46248
46746
|
const revisedPrompts = [];
|
|
46249
46747
|
for (const img of images) {
|
|
46250
|
-
const filename = `${(0,
|
|
46748
|
+
const filename = `${(0, import_node_crypto26.randomUUID)()}.${img.extension}`;
|
|
46251
46749
|
const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
|
|
46252
46750
|
const fullKey = await uploadFile(
|
|
46253
46751
|
img.buffer,
|
|
@@ -46535,7 +47033,7 @@ ${style.markdown}` : params.prompt;
|
|
|
46535
47033
|
(d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
|
|
46536
47034
|
);
|
|
46537
47035
|
const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
|
|
46538
|
-
const messageId = (0,
|
|
47036
|
+
const messageId = (0, import_node_crypto26.randomUUID)();
|
|
46539
47037
|
const uiMessage = {
|
|
46540
47038
|
id: messageId,
|
|
46541
47039
|
role: "system",
|
|
@@ -47632,7 +48130,7 @@ ${style.markdown}` : params.prompt;
|
|
|
47632
48130
|
return;
|
|
47633
48131
|
}
|
|
47634
48132
|
const meta = await parseSkillFrontmatter(bytes);
|
|
47635
|
-
const skillId = (0,
|
|
48133
|
+
const skillId = (0, import_node_crypto26.randomUUID)();
|
|
47636
48134
|
try {
|
|
47637
48135
|
await extractBundleToVersion({ bytes, skillId, version: 1, config });
|
|
47638
48136
|
} catch (err4) {
|
|
@@ -47755,7 +48253,7 @@ ${style.markdown}` : params.prompt;
|
|
|
47755
48253
|
return;
|
|
47756
48254
|
}
|
|
47757
48255
|
if (!await ensureSkillWrite(db2, skill, authResult.user, res)) return;
|
|
47758
|
-
const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0,
|
|
48256
|
+
const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto26.randomUUID)()}${extension}`;
|
|
47759
48257
|
const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
|
|
47760
48258
|
const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
|
|
47761
48259
|
res.json({ uploadUrl, stagingKey });
|
|
@@ -48758,6 +49256,7 @@ ${style.markdown}` : params.prompt;
|
|
|
48758
49256
|
// Coerced, not `?? []`: see readAgentSlots on why a stored non-array is
|
|
48759
49257
|
// a real possibility and why a reader has to survive one.
|
|
48760
49258
|
agent_slots: readAgentSlots(row.agent_slots),
|
|
49259
|
+
external_access: row.external_access === true,
|
|
48761
49260
|
...detailsOf(row),
|
|
48762
49261
|
// Older files, newest first; at most MAX_OLDER_VERSIONS (artifact-library.ts).
|
|
48763
49262
|
versions: versions.map((v) => ({
|
|
@@ -48797,6 +49296,28 @@ ${style.markdown}` : params.prompt;
|
|
|
48797
49296
|
res.status(400).json({ detail: valid.message });
|
|
48798
49297
|
return;
|
|
48799
49298
|
}
|
|
49299
|
+
if (!mayChangeExternalRelease(auth.user, input.external_access, row.external_access)) {
|
|
49300
|
+
res.status(403).json({ detail: EXTERNAL_SUPER_ADMIN_ONLY });
|
|
49301
|
+
return;
|
|
49302
|
+
}
|
|
49303
|
+
if (externalAccessCheckApplies(input, row)) {
|
|
49304
|
+
let teams = [];
|
|
49305
|
+
if (externalAccessNeedsTeams(input, row)) {
|
|
49306
|
+
let teamIds;
|
|
49307
|
+
if (input.rbac && typeof input.rbac === "object") {
|
|
49308
|
+
teamIds = Array.isArray(input.rbac.teams) ? input.rbac.teams.map((t) => t?.id) : [];
|
|
49309
|
+
} else {
|
|
49310
|
+
const stored = await db2("rbac").where({ entity: "shared_artifact", target_resource_id: row.id, access_type: "Team" }).select("team_id");
|
|
49311
|
+
teamIds = stored.map((r) => r.team_id);
|
|
49312
|
+
}
|
|
49313
|
+
teams = await teamNamesByIds(db2, teamIds);
|
|
49314
|
+
}
|
|
49315
|
+
const externalError = validateExternalAccessUpdate(input, row, teams);
|
|
49316
|
+
if (externalError) {
|
|
49317
|
+
res.status(400).json({ detail: externalError });
|
|
49318
|
+
return;
|
|
49319
|
+
}
|
|
49320
|
+
}
|
|
48800
49321
|
const details = planDetails(input, now);
|
|
48801
49322
|
if (!details.ok) {
|
|
48802
49323
|
res.status(400).json({ detail: details.message });
|
|
@@ -48841,6 +49362,7 @@ ${style.markdown}` : params.prompt;
|
|
|
48841
49362
|
expires_at: updated.expires_at ?? null,
|
|
48842
49363
|
rights_mode: updated.rights_mode ?? null,
|
|
48843
49364
|
agent_slots: readAgentSlots(updated.agent_slots),
|
|
49365
|
+
external_access: updated.external_access === true,
|
|
48844
49366
|
...detailsOf(updated),
|
|
48845
49367
|
version_count: readVersions(updated.versions).length
|
|
48846
49368
|
});
|
|
@@ -48910,6 +49432,13 @@ ${style.markdown}` : params.prompt;
|
|
|
48910
49432
|
RBACResolver,
|
|
48911
49433
|
checkRecordAccess
|
|
48912
49434
|
});
|
|
49435
|
+
registerExternalShareRoute(app, {
|
|
49436
|
+
getDb: async () => (await postgresClient()).db
|
|
49437
|
+
});
|
|
49438
|
+
registerCompanionStatusRoutes(app, {
|
|
49439
|
+
authenticate: (req) => requestValidators.authenticate(req),
|
|
49440
|
+
getDb: async () => (await postgresClient()).db
|
|
49441
|
+
});
|
|
48913
49442
|
registerToolApiRoutes(app, {
|
|
48914
49443
|
authenticate: (req) => requestValidators.authenticate(req),
|
|
48915
49444
|
tools,
|
|
@@ -49257,7 +49786,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
|
|
|
49257
49786
|
// src/mcp/index.ts
|
|
49258
49787
|
init_cjs_shims();
|
|
49259
49788
|
var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
49260
|
-
var
|
|
49789
|
+
var import_node_crypto27 = require("crypto");
|
|
49261
49790
|
var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
49262
49791
|
var import_types14 = require("@modelcontextprotocol/sdk/types.js");
|
|
49263
49792
|
init_sanitize_tool_name();
|
|
@@ -49358,7 +49887,7 @@ var ExuluMCP = class {
|
|
|
49358
49887
|
throw new Error("Tool not found in converted tools array.");
|
|
49359
49888
|
}
|
|
49360
49889
|
const iterator = await convertedTool.execute(inputs, {
|
|
49361
|
-
toolCallId: tool5.id + "_" + (0,
|
|
49890
|
+
toolCallId: tool5.id + "_" + (0, import_node_crypto27.randomUUID)(),
|
|
49362
49891
|
messages: []
|
|
49363
49892
|
});
|
|
49364
49893
|
let result;
|
|
@@ -49548,7 +50077,7 @@ var ExuluMCP = class {
|
|
|
49548
50077
|
transport = this.transports[sessionId];
|
|
49549
50078
|
} else if (!sessionId && (0, import_types14.isInitializeRequest)(req.body)) {
|
|
49550
50079
|
transport = new import_streamableHttp.StreamableHTTPServerTransport({
|
|
49551
|
-
sessionIdGenerator: () => (0,
|
|
50080
|
+
sessionIdGenerator: () => (0, import_node_crypto27.randomUUID)(),
|
|
49552
50081
|
onsessioninitialized: (sessionId2) => {
|
|
49553
50082
|
this.transports[sessionId2] = transport;
|
|
49554
50083
|
}
|
|
@@ -50154,7 +50683,7 @@ var import_zod39 = __toESM(require("zod"), 1);
|
|
|
50154
50683
|
init_tool2();
|
|
50155
50684
|
init_check_record_access();
|
|
50156
50685
|
init_client();
|
|
50157
|
-
var
|
|
50686
|
+
var import_node_crypto28 = require("crypto");
|
|
50158
50687
|
var AnswerOptionSchema = import_zod39.default.object({
|
|
50159
50688
|
id: import_zod39.default.string().describe("Unique identifier for the answer option"),
|
|
50160
50689
|
text: import_zod39.default.string().describe("The text of the answer option")
|
|
@@ -50208,15 +50737,15 @@ var QuestionAskTool = new ExuluTool({
|
|
|
50208
50737
|
throw new Error("You don't have access to this session " + session.id + ".");
|
|
50209
50738
|
}
|
|
50210
50739
|
const answerOptionsWithIds = answerOptions.map((text) => ({
|
|
50211
|
-
id: (0,
|
|
50740
|
+
id: (0, import_node_crypto28.randomUUID)(),
|
|
50212
50741
|
text
|
|
50213
50742
|
}));
|
|
50214
50743
|
answerOptionsWithIds.push({
|
|
50215
|
-
id: (0,
|
|
50744
|
+
id: (0, import_node_crypto28.randomUUID)(),
|
|
50216
50745
|
text: "None of the above..."
|
|
50217
50746
|
});
|
|
50218
50747
|
const newQuestion = {
|
|
50219
|
-
id: (0,
|
|
50748
|
+
id: (0, import_node_crypto28.randomUUID)(),
|
|
50220
50749
|
question,
|
|
50221
50750
|
answerOptions: answerOptionsWithIds,
|
|
50222
50751
|
status: "pending"
|