@exulu/backend 5.15.0 → 5.17.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-KLPCQWM3.js → chunk-7UDWQTFZ.js} +1 -1
- package/dist/{chunk-NBDSN45T.js → chunk-NBAFO66K.js} +41 -39
- package/dist/{chunk-S4UXKMN5.js → chunk-ZNG2HEDN.js} +56 -3
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-GLRM3PM6.js → convert-exulu-tools-to-ai-sdk-tools-BCHKS5CK.js} +2 -2
- package/dist/{doc_processor-SVOSOVOY.js → doc_processor-RJNG7GGH.js} +2 -2
- package/dist/index.cjs +2676 -417
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3715 -1555
- package/ee/entitlements.ts +3 -0
- package/ee/queues/queues.ts +1 -0
- package/ee/schemas.ts +43 -0
- package/ee/workers.ts +11 -0
- package/package.json +6 -1
package/dist/index.cjs
CHANGED
|
@@ -41,6 +41,53 @@ var init_cjs_shims = __esm({
|
|
|
41
41
|
}
|
|
42
42
|
});
|
|
43
43
|
|
|
44
|
+
// ee/entitlements.ts
|
|
45
|
+
var ENTITLEMENTS, checkLicense;
|
|
46
|
+
var init_entitlements = __esm({
|
|
47
|
+
"ee/entitlements.ts"() {
|
|
48
|
+
"use strict";
|
|
49
|
+
init_cjs_shims();
|
|
50
|
+
ENTITLEMENTS = {
|
|
51
|
+
"rbac": false,
|
|
52
|
+
"advanced-markdown-chunker": false,
|
|
53
|
+
"agentic-retrieval": false,
|
|
54
|
+
"queues": false,
|
|
55
|
+
"custom-branding": false,
|
|
56
|
+
"evals": false,
|
|
57
|
+
"template-conversations": false,
|
|
58
|
+
"agent-feedback": false,
|
|
59
|
+
"multi-agent-tooling": false,
|
|
60
|
+
"advanced-document-processing": false,
|
|
61
|
+
"rate-limits": false,
|
|
62
|
+
"claim-check": false,
|
|
63
|
+
"channels": false
|
|
64
|
+
};
|
|
65
|
+
checkLicense = () => {
|
|
66
|
+
if (!process.env.EXULU_ENTERPRISE_LICENSE || process.env.EXULU_ENTERPRISE_LICENSE === "" || !process.env.EXULU_ENTERPRISE_LICENSE.startsWith("EXULU_EE_")) {
|
|
67
|
+
return ENTITLEMENTS;
|
|
68
|
+
} else {
|
|
69
|
+
return {
|
|
70
|
+
"rbac": true,
|
|
71
|
+
"advanced-markdown-chunker": true,
|
|
72
|
+
"agentic-retrieval": true,
|
|
73
|
+
"mcp": true,
|
|
74
|
+
"queues": true,
|
|
75
|
+
"prompt-library": true,
|
|
76
|
+
"custom-branding": true,
|
|
77
|
+
"evals": true,
|
|
78
|
+
"template-conversations": true,
|
|
79
|
+
"agent-feedback": true,
|
|
80
|
+
"multi-agent-tooling": true,
|
|
81
|
+
"advanced-document-processing": true,
|
|
82
|
+
"rate-limits": true,
|
|
83
|
+
"claim-check": true,
|
|
84
|
+
"channels": true
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
44
91
|
// types/models/user.ts
|
|
45
92
|
var init_user = __esm({
|
|
46
93
|
"types/models/user.ts"() {
|
|
@@ -1822,15 +1869,15 @@ var init_tokenizer = __esm({
|
|
|
1822
1869
|
if (cached) return cached;
|
|
1823
1870
|
const time = performance.now();
|
|
1824
1871
|
console.log("[EXULU] Loading tokenizer ranks.", encoding);
|
|
1825
|
-
const
|
|
1872
|
+
const pending2 = (0, import_load.load)(import_registry.default[encoding]).then((ranks) => {
|
|
1826
1873
|
console.log("[EXULU] Loaded tokenizer ranks.", encoding, performance.now() - time);
|
|
1827
1874
|
return ranks;
|
|
1828
1875
|
}).catch((error) => {
|
|
1829
1876
|
ranksByEncoding.delete(encoding);
|
|
1830
1877
|
throw error;
|
|
1831
1878
|
});
|
|
1832
|
-
ranksByEncoding.set(encoding,
|
|
1833
|
-
return
|
|
1879
|
+
ranksByEncoding.set(encoding, pending2);
|
|
1880
|
+
return pending2;
|
|
1834
1881
|
};
|
|
1835
1882
|
ExuluTokenizer = class {
|
|
1836
1883
|
constructor() {
|
|
@@ -3681,7 +3728,7 @@ function subtractDuration(date, duration) {
|
|
|
3681
3728
|
result.setUTCMonth(result.getUTCMonth() - Math.round(n));
|
|
3682
3729
|
return result;
|
|
3683
3730
|
}
|
|
3684
|
-
return new Date(date.getTime() - durationToDays(duration) *
|
|
3731
|
+
return new Date(date.getTime() - durationToDays(duration) * DAY_MS2);
|
|
3685
3732
|
}
|
|
3686
3733
|
function subtractOneCalendarMonth(date) {
|
|
3687
3734
|
const result = new Date(date);
|
|
@@ -3714,7 +3761,7 @@ async function enrichSpendFromActivity(map) {
|
|
|
3714
3761
|
try {
|
|
3715
3762
|
const spendByTag = await getTagSpendByWindow(
|
|
3716
3763
|
windows3,
|
|
3717
|
-
ymd(new Date(Date.now() +
|
|
3764
|
+
ymd(new Date(Date.now() + DAY_MS2))
|
|
3718
3765
|
);
|
|
3719
3766
|
for (const name of names) {
|
|
3720
3767
|
const spend = spendByTag[name];
|
|
@@ -3877,7 +3924,7 @@ async function getUserBudgetView(userId) {
|
|
|
3877
3924
|
return null;
|
|
3878
3925
|
}
|
|
3879
3926
|
}
|
|
3880
|
-
var SETTINGS_KEY,
|
|
3927
|
+
var SETTINGS_KEY, DAY_MS2, DEFAULT_SETTINGS, TAG_MAP_TTL_MS, tagMapCache, tagMapInflight, PROVISION_TTL_MS, provisionCache, READ_TTL_MS, readCache;
|
|
3881
3928
|
var init_budget_service = __esm({
|
|
3882
3929
|
"src/exulu/litellm/budget-service.ts"() {
|
|
3883
3930
|
"use strict";
|
|
@@ -3887,7 +3934,7 @@ var init_budget_service = __esm({
|
|
|
3887
3934
|
init_admin_client();
|
|
3888
3935
|
init_activity_client();
|
|
3889
3936
|
SETTINGS_KEY = "budget_settings";
|
|
3890
|
-
|
|
3937
|
+
DAY_MS2 = 24 * 60 * 60 * 1e3;
|
|
3891
3938
|
DEFAULT_SETTINGS = {
|
|
3892
3939
|
global_user_budget: { enabled: false, max_budget: 0, budget_duration: "30d" },
|
|
3893
3940
|
show_user_budget_in_chat: false,
|
|
@@ -5142,7 +5189,7 @@ var init_vector_methods = __esm({
|
|
|
5142
5189
|
});
|
|
5143
5190
|
|
|
5144
5191
|
// ee/schemas.ts
|
|
5145
|
-
var feedbackSchema, claimChecksSchema, rolesSchema, teamsSchema, statisticsSchema, testCasesSchema, evalSetsSchema, jobResultsSchema, evalRunsSchema, rbacSchema, workflowTemplatesSchema, workflowTriggersSchema;
|
|
5192
|
+
var feedbackSchema, claimChecksSchema, rolesSchema, teamsSchema, statisticsSchema, testCasesSchema, evalSetsSchema, jobResultsSchema, evalRunsSchema, rbacSchema, workflowTemplatesSchema, agentChannelsSchema, channelLinksSchema, workflowTriggersSchema;
|
|
5146
5193
|
var init_schemas = __esm({
|
|
5147
5194
|
"ee/schemas.ts"() {
|
|
5148
5195
|
"use strict";
|
|
@@ -5622,6 +5669,41 @@ var init_schemas = __esm({
|
|
|
5622
5669
|
}
|
|
5623
5670
|
]
|
|
5624
5671
|
};
|
|
5672
|
+
agentChannelsSchema = {
|
|
5673
|
+
type: "agent_channels",
|
|
5674
|
+
name: {
|
|
5675
|
+
plural: "agent_channels",
|
|
5676
|
+
singular: "agent_channel"
|
|
5677
|
+
},
|
|
5678
|
+
RBAC: false,
|
|
5679
|
+
graphql: false,
|
|
5680
|
+
fields: [
|
|
5681
|
+
{ name: "agent", type: "uuid", required: true, index: true },
|
|
5682
|
+
{ name: "type", type: "text", required: true },
|
|
5683
|
+
{ name: "enabled", type: "boolean", default: false },
|
|
5684
|
+
{ name: "config", type: "json" },
|
|
5685
|
+
{ name: "secrets", type: "text", hidden: true },
|
|
5686
|
+
{ name: "verify_token", type: "text", hidden: true }
|
|
5687
|
+
]
|
|
5688
|
+
};
|
|
5689
|
+
channelLinksSchema = {
|
|
5690
|
+
type: "channel_links",
|
|
5691
|
+
name: {
|
|
5692
|
+
plural: "channel_links",
|
|
5693
|
+
singular: "channel_link"
|
|
5694
|
+
},
|
|
5695
|
+
RBAC: false,
|
|
5696
|
+
graphql: false,
|
|
5697
|
+
fields: [
|
|
5698
|
+
{ name: "channel", type: "uuid", required: true, index: true },
|
|
5699
|
+
{ name: "identity", type: "text", required: true },
|
|
5700
|
+
{ name: "user", type: "number", required: true, index: true },
|
|
5701
|
+
{ name: "linked_at", type: "date" },
|
|
5702
|
+
{ name: "expires_at", type: "date" },
|
|
5703
|
+
{ name: "revoked_at", type: "date" },
|
|
5704
|
+
{ name: "last_seen_at", type: "date" }
|
|
5705
|
+
]
|
|
5706
|
+
};
|
|
5625
5707
|
workflowTriggersSchema = {
|
|
5626
5708
|
type: "workflow_triggers",
|
|
5627
5709
|
name: {
|
|
@@ -5682,51 +5764,6 @@ var init_schemas = __esm({
|
|
|
5682
5764
|
}
|
|
5683
5765
|
});
|
|
5684
5766
|
|
|
5685
|
-
// ee/entitlements.ts
|
|
5686
|
-
var ENTITLEMENTS, checkLicense;
|
|
5687
|
-
var init_entitlements = __esm({
|
|
5688
|
-
"ee/entitlements.ts"() {
|
|
5689
|
-
"use strict";
|
|
5690
|
-
init_cjs_shims();
|
|
5691
|
-
ENTITLEMENTS = {
|
|
5692
|
-
"rbac": false,
|
|
5693
|
-
"advanced-markdown-chunker": false,
|
|
5694
|
-
"agentic-retrieval": false,
|
|
5695
|
-
"queues": false,
|
|
5696
|
-
"custom-branding": false,
|
|
5697
|
-
"evals": false,
|
|
5698
|
-
"template-conversations": false,
|
|
5699
|
-
"agent-feedback": false,
|
|
5700
|
-
"multi-agent-tooling": false,
|
|
5701
|
-
"advanced-document-processing": false,
|
|
5702
|
-
"rate-limits": false,
|
|
5703
|
-
"claim-check": false
|
|
5704
|
-
};
|
|
5705
|
-
checkLicense = () => {
|
|
5706
|
-
if (!process.env.EXULU_ENTERPRISE_LICENSE || process.env.EXULU_ENTERPRISE_LICENSE === "" || !process.env.EXULU_ENTERPRISE_LICENSE.startsWith("EXULU_EE_")) {
|
|
5707
|
-
return ENTITLEMENTS;
|
|
5708
|
-
} else {
|
|
5709
|
-
return {
|
|
5710
|
-
"rbac": true,
|
|
5711
|
-
"advanced-markdown-chunker": true,
|
|
5712
|
-
"agentic-retrieval": true,
|
|
5713
|
-
"mcp": true,
|
|
5714
|
-
"queues": true,
|
|
5715
|
-
"prompt-library": true,
|
|
5716
|
-
"custom-branding": true,
|
|
5717
|
-
"evals": true,
|
|
5718
|
-
"template-conversations": true,
|
|
5719
|
-
"agent-feedback": true,
|
|
5720
|
-
"multi-agent-tooling": true,
|
|
5721
|
-
"advanced-document-processing": true,
|
|
5722
|
-
"rate-limits": true,
|
|
5723
|
-
"claim-check": true
|
|
5724
|
-
};
|
|
5725
|
-
}
|
|
5726
|
-
};
|
|
5727
|
-
}
|
|
5728
|
-
});
|
|
5729
|
-
|
|
5730
5767
|
// src/postgres/core-schema.ts
|
|
5731
5768
|
function userCredentialsSchema() {
|
|
5732
5769
|
return `
|
|
@@ -6009,6 +6046,14 @@ var init_core_schema = __esm({
|
|
|
6009
6046
|
name: "welcomemessage",
|
|
6010
6047
|
type: "text"
|
|
6011
6048
|
},
|
|
6049
|
+
{
|
|
6050
|
+
// The welcome message in further languages: { "<locale>": "<text>" },
|
|
6051
|
+
// e.g. { "de": "Hallo …" }. `welcomemessage` stays the default (English,
|
|
6052
|
+
// and any language without an entry). Read through welcomeTranslations()
|
|
6053
|
+
// in public-agents.ts. Auto-ALTERed on boot.
|
|
6054
|
+
name: "welcomemessage_translations",
|
|
6055
|
+
type: "json"
|
|
6056
|
+
},
|
|
6012
6057
|
{
|
|
6013
6058
|
name: "instructions",
|
|
6014
6059
|
type: "text"
|
|
@@ -6896,6 +6941,10 @@ var init_core_schema = __esm({
|
|
|
6896
6941
|
schemas.workflowTemplatesSchema = () => addCoreFields(workflowTemplatesSchema);
|
|
6897
6942
|
schemas.workflowTriggersSchema = () => addCoreFields(workflowTriggersSchema);
|
|
6898
6943
|
}
|
|
6944
|
+
if (license["channels"]) {
|
|
6945
|
+
schemas.agentChannelsSchema = () => addCoreFields(agentChannelsSchema);
|
|
6946
|
+
schemas.channelLinksSchema = () => addCoreFields(channelLinksSchema);
|
|
6947
|
+
}
|
|
6899
6948
|
if (license["queues"]) {
|
|
6900
6949
|
schemas.jobResultsSchema = () => addCoreFields(jobResultsSchema);
|
|
6901
6950
|
}
|
|
@@ -9746,7 +9795,7 @@ var init_registry = __esm({
|
|
|
9746
9795
|
// src/exulu/auth/credential-store.ts
|
|
9747
9796
|
async function get(provider, userId) {
|
|
9748
9797
|
const { db: db2 } = await postgresClient();
|
|
9749
|
-
const row = await db2.from(
|
|
9798
|
+
const row = await db2.from(TABLE3).where({ provider, user_id: String(userId) }).first();
|
|
9750
9799
|
if (!row) {
|
|
9751
9800
|
return null;
|
|
9752
9801
|
}
|
|
@@ -9760,7 +9809,7 @@ async function get(provider, userId) {
|
|
|
9760
9809
|
async function upsert(record) {
|
|
9761
9810
|
const { db: db2 } = await postgresClient();
|
|
9762
9811
|
const encrypted = encrypt(JSON.stringify(record.data));
|
|
9763
|
-
await db2.from(
|
|
9812
|
+
await db2.from(TABLE3).insert({
|
|
9764
9813
|
provider: record.provider,
|
|
9765
9814
|
user_id: String(record.userId),
|
|
9766
9815
|
auth_type: record.authType,
|
|
@@ -9770,7 +9819,7 @@ async function upsert(record) {
|
|
|
9770
9819
|
}
|
|
9771
9820
|
async function listByUser(userId) {
|
|
9772
9821
|
const { db: db2 } = await postgresClient();
|
|
9773
|
-
const list = await db2.from(
|
|
9822
|
+
const list = await db2.from(TABLE3).where({ user_id: String(userId) }).orderBy("provider");
|
|
9774
9823
|
return list.map((row) => ({
|
|
9775
9824
|
provider: row.provider,
|
|
9776
9825
|
authType: row.auth_type,
|
|
@@ -9780,16 +9829,16 @@ async function listByUser(userId) {
|
|
|
9780
9829
|
}
|
|
9781
9830
|
async function del(provider, userId) {
|
|
9782
9831
|
const { db: db2 } = await postgresClient();
|
|
9783
|
-
await db2.from(
|
|
9832
|
+
await db2.from(TABLE3).where({ provider, user_id: String(userId) }).del();
|
|
9784
9833
|
}
|
|
9785
|
-
var import_crypto_js,
|
|
9834
|
+
var import_crypto_js, TABLE3, encrypt, decrypt, credentialStore;
|
|
9786
9835
|
var init_credential_store = __esm({
|
|
9787
9836
|
"src/exulu/auth/credential-store.ts"() {
|
|
9788
9837
|
"use strict";
|
|
9789
9838
|
init_cjs_shims();
|
|
9790
9839
|
import_crypto_js = __toESM(require("crypto-js"), 1);
|
|
9791
9840
|
init_client();
|
|
9792
|
-
|
|
9841
|
+
TABLE3 = "user_credentials";
|
|
9793
9842
|
encrypt = (value) => import_crypto_js.default.AES.encrypt(value, process.env.NEXTAUTH_SECRET).toString();
|
|
9794
9843
|
decrypt = (value) => import_crypto_js.default.AES.decrypt(value, process.env.NEXTAUTH_SECRET).toString(import_crypto_js.default.enc.Utf8);
|
|
9795
9844
|
credentialStore = { get, upsert, listByUser, delete: del };
|
|
@@ -11334,11 +11383,11 @@ var init_context_read_tools = __esm({
|
|
|
11334
11383
|
};
|
|
11335
11384
|
readContextItem = async (context, args, caller, deps = {}) => {
|
|
11336
11385
|
const { user } = caller;
|
|
11337
|
-
const
|
|
11386
|
+
const NOT_FOUND2 = itemNotFoundMessage(context, "read");
|
|
11338
11387
|
const checkAccess = deps.checkAccess ?? checkItemReadAccess;
|
|
11339
11388
|
const readable = readableContextFields(context);
|
|
11340
11389
|
if (treatAsGuest(caller.req, user)) {
|
|
11341
|
-
return { ok: false, message:
|
|
11390
|
+
return { ok: false, message: NOT_FOUND2 };
|
|
11342
11391
|
}
|
|
11343
11392
|
if (!args.id && !args.external_id) {
|
|
11344
11393
|
return { ok: false, message: "Provide the id or external_id of the item to read." };
|
|
@@ -11352,10 +11401,10 @@ var init_context_read_tools = __esm({
|
|
|
11352
11401
|
item: { id: args.id, external_id: args.external_id }
|
|
11353
11402
|
});
|
|
11354
11403
|
if (!record?.id) {
|
|
11355
|
-
return { ok: false, message:
|
|
11404
|
+
return { ok: false, message: NOT_FOUND2 };
|
|
11356
11405
|
}
|
|
11357
11406
|
if (!await checkAccess(context, record, user)) {
|
|
11358
|
-
return { ok: false, message:
|
|
11407
|
+
return { ok: false, message: NOT_FOUND2 };
|
|
11359
11408
|
}
|
|
11360
11409
|
const explicit = Array.isArray(args.fields) && args.fields.length > 0;
|
|
11361
11410
|
return { ok: true, item: projectRow(record, selection.fields, explicit) };
|
|
@@ -11720,7 +11769,7 @@ var init_context_write_tools = __esm({
|
|
|
11720
11769
|
if (perms.update) {
|
|
11721
11770
|
const { shape, contentKeys, fileFields } = buildWriteSchema(context, "update");
|
|
11722
11771
|
const fileNote = fileFields.length ? " File fields take the name of a file from this session's files; omit them to keep the current file." : "";
|
|
11723
|
-
const
|
|
11772
|
+
const NOT_FOUND2 = itemNotFoundMessage(context, "write");
|
|
11724
11773
|
tools.push(
|
|
11725
11774
|
new ExuluTool({
|
|
11726
11775
|
id: `update_${segment}_item`,
|
|
@@ -11744,11 +11793,11 @@ var init_context_write_tools = __esm({
|
|
|
11744
11793
|
item: { id: params.id, external_id: params.external_id }
|
|
11745
11794
|
});
|
|
11746
11795
|
if (!existing?.id) {
|
|
11747
|
-
return { result:
|
|
11796
|
+
return { result: NOT_FOUND2 };
|
|
11748
11797
|
}
|
|
11749
11798
|
const allowed = await checkItemWriteAccess(context, existing, user);
|
|
11750
11799
|
if (!allowed) {
|
|
11751
|
-
return { result:
|
|
11800
|
+
return { result: NOT_FOUND2 };
|
|
11752
11801
|
}
|
|
11753
11802
|
const enumError = canonicalizeEnumFields(context, params);
|
|
11754
11803
|
if (enumError) {
|
|
@@ -12291,10 +12340,10 @@ async function createProjectAndAttach(db2, user, input) {
|
|
|
12291
12340
|
}
|
|
12292
12341
|
function planMove(args) {
|
|
12293
12342
|
const skipped = [];
|
|
12294
|
-
let
|
|
12343
|
+
let pool3;
|
|
12295
12344
|
if (args.requested) {
|
|
12296
12345
|
const byName = new Map(args.files.map((f) => [f.name, f]));
|
|
12297
|
-
|
|
12346
|
+
pool3 = [];
|
|
12298
12347
|
const seen = /* @__PURE__ */ new Set();
|
|
12299
12348
|
for (const raw of args.requested) {
|
|
12300
12349
|
const name = String(raw ?? "").trim();
|
|
@@ -12306,18 +12355,18 @@ function planMove(args) {
|
|
|
12306
12355
|
}
|
|
12307
12356
|
const hit = byName.get(name);
|
|
12308
12357
|
if (!hit) skipped.push({ name, reason: SKIP_UNKNOWN });
|
|
12309
|
-
else
|
|
12358
|
+
else pool3.push(hit);
|
|
12310
12359
|
}
|
|
12311
12360
|
} else {
|
|
12312
|
-
|
|
12361
|
+
pool3 = args.files.filter((f) => isDefaultMoveCandidate(f.name));
|
|
12313
12362
|
}
|
|
12314
12363
|
const groups = /* @__PURE__ */ new Map();
|
|
12315
|
-
for (const f of
|
|
12364
|
+
for (const f of pool3) {
|
|
12316
12365
|
const safe = sanitizeFilename(f.name);
|
|
12317
12366
|
groups.set(safe, [...groups.get(safe) ?? [], f]);
|
|
12318
12367
|
}
|
|
12319
12368
|
const usable = [];
|
|
12320
|
-
for (const f of
|
|
12369
|
+
for (const f of pool3) {
|
|
12321
12370
|
const safe = sanitizeFilename(f.name);
|
|
12322
12371
|
if (!safe) skipped.push({ name: f.name, reason: "Could not derive a safe filename." });
|
|
12323
12372
|
else if ((groups.get(safe) ?? []).length > 1) skipped.push({ name: f.name, reason: SKIP_CLASH });
|
|
@@ -12483,15 +12532,15 @@ function originFromMetadata(metadata) {
|
|
|
12483
12532
|
return metadata?.[ORIGIN_METADATA_KEY] === "agent" ? "agent" : "user";
|
|
12484
12533
|
}
|
|
12485
12534
|
function createOriginResolver(head) {
|
|
12486
|
-
const
|
|
12535
|
+
const cache3 = /* @__PURE__ */ new Map();
|
|
12487
12536
|
return async (file) => {
|
|
12488
12537
|
const stamp2 = file.lastModified instanceof Date ? file.lastModified.toISOString() : String(file.lastModified);
|
|
12489
12538
|
const id = `${file.key}\0${stamp2}`;
|
|
12490
|
-
const hit =
|
|
12539
|
+
const hit = cache3.get(id);
|
|
12491
12540
|
if (hit) return hit;
|
|
12492
12541
|
try {
|
|
12493
12542
|
const origin = originFromMetadata(await head(file.key));
|
|
12494
|
-
|
|
12543
|
+
cache3.set(id, origin);
|
|
12495
12544
|
return origin;
|
|
12496
12545
|
} catch {
|
|
12497
12546
|
return "user";
|
|
@@ -14055,7 +14104,7 @@ async function sweepStaleHelpers(sessionDir) {
|
|
|
14055
14104
|
for (const name of names) {
|
|
14056
14105
|
if (!name.startsWith(prefix)) continue;
|
|
14057
14106
|
const st = await (0, import_promises2.lstat)((0, import_node_path6.join)(root, name)).catch(() => null);
|
|
14058
|
-
if (st && Date.now() - st.mtimeMs >
|
|
14107
|
+
if (st && Date.now() - st.mtimeMs > DAY_MS3) await removeTreeSafely((0, import_node_path6.join)(root, name), sessionDir);
|
|
14059
14108
|
}
|
|
14060
14109
|
}
|
|
14061
14110
|
}
|
|
@@ -14180,7 +14229,7 @@ async function resolveSandboxProjectId(args, deps) {
|
|
|
14180
14229
|
return null;
|
|
14181
14230
|
}
|
|
14182
14231
|
}
|
|
14183
|
-
var import_promises2, import_node_crypto6, import_node_path6, import_node_child_process3, import_node_util2, isFlatName, HELPER_KINDS, helperRoot, helperPath, execFileAsync2,
|
|
14232
|
+
var import_promises2, import_node_crypto6, import_node_path6, import_node_child_process3, import_node_util2, isFlatName, HELPER_KINDS, helperRoot, helperPath, execFileAsync2, DAY_MS3, errCode;
|
|
14184
14233
|
var init_project_sync = __esm({
|
|
14185
14234
|
"ee/invoke-skills/project-sync.ts"() {
|
|
14186
14235
|
"use strict";
|
|
@@ -14198,7 +14247,7 @@ var init_project_sync = __esm({
|
|
|
14198
14247
|
helperRoot = (sessionDir, kind) => (0, import_node_path6.join)((0, import_node_path6.dirname)(sessionDir), kind);
|
|
14199
14248
|
helperPath = (sessionDir, kind) => (0, import_node_path6.join)(helperRoot(sessionDir, kind), `${(0, import_node_path6.basename)(sessionDir)}-${(0, import_node_crypto6.randomBytes)(8).toString("hex")}`);
|
|
14200
14249
|
execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
|
|
14201
|
-
|
|
14250
|
+
DAY_MS3 = 24 * 60 * 60 * 1e3;
|
|
14202
14251
|
errCode = (err4) => err4?.code;
|
|
14203
14252
|
}
|
|
14204
14253
|
});
|
|
@@ -14884,6 +14933,11 @@ var init_inventory = __esm({
|
|
|
14884
14933
|
DEBUG: "runtime",
|
|
14885
14934
|
BACKEND: "runtime",
|
|
14886
14935
|
FRONTEND: "runtime",
|
|
14936
|
+
// Public web addresses, like BACKEND/FRONTEND: the override and the last
|
|
14937
|
+
// fallback for the WhatsApp link page base (channels/config.ts linkPageUrl),
|
|
14938
|
+
// which normally comes from FRONTEND.
|
|
14939
|
+
CHANNEL_LINK_BASE_URL: "runtime",
|
|
14940
|
+
NEXTAUTH_URL: "runtime",
|
|
14887
14941
|
// Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
|
|
14888
14942
|
AUTH_MODE: "runtime",
|
|
14889
14943
|
// "password" | "otp" mode selector, echoed by GET /config
|
|
@@ -17135,9 +17189,9 @@ var init_auth_tool_model_output = __esm({
|
|
|
17135
17189
|
"use strict";
|
|
17136
17190
|
init_cjs_shims();
|
|
17137
17191
|
init_scrub_text();
|
|
17138
|
-
buildAuthToolModelOutput = (
|
|
17192
|
+
buildAuthToolModelOutput = (tool5) => ({ output }) => {
|
|
17139
17193
|
if (output && typeof output === "object" && output.credentialRequest) {
|
|
17140
|
-
const auth =
|
|
17194
|
+
const auth = tool5.authentication;
|
|
17141
17195
|
const labels = auth?.authType === "user_credentials" ? auth.fields.map((f) => f.label) : [];
|
|
17142
17196
|
const provider = output.credentialRequest.provider ?? (auth && "provider" in auth ? auth.provider : "unknown");
|
|
17143
17197
|
return { type: "text", value: credentialScrubText(provider, labels) };
|
|
@@ -18410,10 +18464,10 @@ var init_doc_processor = __esm({
|
|
|
18410
18464
|
if (!fileType) {
|
|
18411
18465
|
throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
|
|
18412
18466
|
}
|
|
18413
|
-
const
|
|
18467
|
+
const UUID3 = (0, import_crypto4.randomUUID)();
|
|
18414
18468
|
let buffer;
|
|
18415
18469
|
if (Buffer.isBuffer(file)) {
|
|
18416
|
-
filePath = path3.join(tempDir, `${
|
|
18470
|
+
filePath = path3.join(tempDir, `${UUID3}.${fileType}`);
|
|
18417
18471
|
await fs2.promises.writeFile(filePath, file);
|
|
18418
18472
|
buffer = file;
|
|
18419
18473
|
} else {
|
|
@@ -18421,7 +18475,7 @@ var init_doc_processor = __esm({
|
|
|
18421
18475
|
if (filePath.startsWith("http")) {
|
|
18422
18476
|
const response = await fetch(filePath);
|
|
18423
18477
|
const array = await response.arrayBuffer();
|
|
18424
|
-
const tempFilePath = path3.join(tempDir, `${
|
|
18478
|
+
const tempFilePath = path3.join(tempDir, `${UUID3}.${fileType}`);
|
|
18425
18479
|
await fs2.promises.writeFile(tempFilePath, Buffer.from(array));
|
|
18426
18480
|
buffer = Buffer.from(array);
|
|
18427
18481
|
filePath = tempFilePath;
|
|
@@ -18614,7 +18668,7 @@ async function readThroughDocument(args) {
|
|
|
18614
18668
|
const pointerAt = pointerKey(bucket, sourceKey, s3prefix);
|
|
18615
18669
|
const fromStoredText = (stored) => {
|
|
18616
18670
|
if (!stored) return null;
|
|
18617
|
-
if (now().getTime() - stored.lastModified.getTime() > cacheDays *
|
|
18671
|
+
if (now().getTime() - stored.lastModified.getTime() > cacheDays * DAY_MS4) return null;
|
|
18618
18672
|
const pages = Number(stored.metadata?.[PAGES_METADATA_KEY]);
|
|
18619
18673
|
const totalPages = Number.isInteger(pages) && pages > 0 ? pages : countPageMarkers(stored.text);
|
|
18620
18674
|
return { text: stored.text, totalPages, fromStore: true };
|
|
@@ -18721,7 +18775,7 @@ function createStoreIo(exuluConfig) {
|
|
|
18721
18775
|
putText: (key, text, metadata) => putS3ObjectTextExact(key, text, metadata, exuluConfig, key.endsWith(".json") ? "application/json" : void 0)
|
|
18722
18776
|
};
|
|
18723
18777
|
}
|
|
18724
|
-
var import_crypto5, inFlight,
|
|
18778
|
+
var import_crypto5, inFlight, DAY_MS4, sha256Hex, PAGES_METADATA_KEY, warn2;
|
|
18725
18779
|
var init_store3 = __esm({
|
|
18726
18780
|
"src/exulu/document-cache/store.ts"() {
|
|
18727
18781
|
"use strict";
|
|
@@ -18730,7 +18784,7 @@ var init_store3 = __esm({
|
|
|
18730
18784
|
init_uppy();
|
|
18731
18785
|
init_keys();
|
|
18732
18786
|
inFlight = /* @__PURE__ */ new Map();
|
|
18733
|
-
|
|
18787
|
+
DAY_MS4 = 24 * 60 * 60 * 1e3;
|
|
18734
18788
|
sha256Hex = (bytes) => (0, import_crypto5.createHash)("sha256").update(bytes).digest("hex");
|
|
18735
18789
|
PAGES_METADATA_KEY = "exulu-pages";
|
|
18736
18790
|
warn2 = (what, err4) => console.warn(`[EXULU] document store: ${what}:`, err4 instanceof Error ? err4.message : String(err4));
|
|
@@ -19576,9 +19630,9 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
|
|
|
19576
19630
|
};
|
|
19577
19631
|
OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
|
|
19578
19632
|
generateS3Key = (filename) => `${(0, import_node_crypto10.randomUUID)()}-${filename}`;
|
|
19579
|
-
hydrateVariables = async (
|
|
19633
|
+
hydrateVariables = async (tool5) => {
|
|
19580
19634
|
const { db: db2 } = await postgresClient();
|
|
19581
|
-
const promises2 =
|
|
19635
|
+
const promises2 = tool5.config.map(async (toolConfig) => {
|
|
19582
19636
|
if (!toolConfig.variable) {
|
|
19583
19637
|
return toolConfig;
|
|
19584
19638
|
}
|
|
@@ -19624,7 +19678,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
|
|
|
19624
19678
|
return toolConfig;
|
|
19625
19679
|
});
|
|
19626
19680
|
await Promise.all(promises2);
|
|
19627
|
-
return
|
|
19681
|
+
return tool5;
|
|
19628
19682
|
};
|
|
19629
19683
|
convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions, routineHandleFactory, resolvedProject, inRoutineRun) => {
|
|
19630
19684
|
if (!currentTools) return {};
|
|
@@ -19776,7 +19830,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
|
|
|
19776
19830
|
let projectSearchContextIds;
|
|
19777
19831
|
console.log("[EXULU] Creating agentic search tool", contexts?.length, model);
|
|
19778
19832
|
if (contexts?.length && model && !disabled.has("agentic_context_search")) {
|
|
19779
|
-
const index = currentTools.findIndex((
|
|
19833
|
+
const index = currentTools.findIndex((tool5) => tool5.id === "agentic_context_search");
|
|
19780
19834
|
const memoryContext = agent?.memory ? contexts.find((c) => c.id === agent.memory) : void 0;
|
|
19781
19835
|
if (index !== -1) {
|
|
19782
19836
|
const agenticSearchTool = createAgenticRetrievalTool({
|
|
@@ -19826,7 +19880,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
|
|
|
19826
19880
|
}
|
|
19827
19881
|
}
|
|
19828
19882
|
} else {
|
|
19829
|
-
const agenticSearchTool = currentTools.find((
|
|
19883
|
+
const agenticSearchTool = currentTools.find((tool5) => tool5.id === "agentic_context_search");
|
|
19830
19884
|
if (agenticSearchTool) {
|
|
19831
19885
|
currentTools.splice(currentTools.indexOf(agenticSearchTool), 1);
|
|
19832
19886
|
}
|
|
@@ -19863,9 +19917,9 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
|
|
|
19863
19917
|
);
|
|
19864
19918
|
}
|
|
19865
19919
|
}
|
|
19866
|
-
const sanitizedTools = currentTools ? currentTools.map((
|
|
19867
|
-
...
|
|
19868
|
-
name: sanitizeToolName(
|
|
19920
|
+
const sanitizedTools = currentTools ? currentTools.map((tool5) => ({
|
|
19921
|
+
...tool5,
|
|
19922
|
+
name: sanitizeToolName(tool5.name)
|
|
19869
19923
|
})) : [];
|
|
19870
19924
|
console.log(
|
|
19871
19925
|
"[EXULU] Sanitized tools",
|
|
@@ -20283,8 +20337,8 @@ var init_tool2 = __esm({
|
|
|
20283
20337
|
void 0,
|
|
20284
20338
|
agent
|
|
20285
20339
|
);
|
|
20286
|
-
const
|
|
20287
|
-
if (!
|
|
20340
|
+
const tool5 = tools[sanitizeName(this.name)] || tools[this.name] || tools[this.id];
|
|
20341
|
+
if (!tool5?.execute) {
|
|
20288
20342
|
throw new Error("Tool " + sanitizeName(this.name) + " not found in " + JSON.stringify(tools));
|
|
20289
20343
|
}
|
|
20290
20344
|
console.log("[EXULU] Tool found", this.name);
|
|
@@ -20294,7 +20348,7 @@ var init_tool2 = __esm({
|
|
|
20294
20348
|
toolCallId,
|
|
20295
20349
|
messages: []
|
|
20296
20350
|
});
|
|
20297
|
-
const generator =
|
|
20351
|
+
const generator = tool5.execute(inputs, {
|
|
20298
20352
|
toolCallId,
|
|
20299
20353
|
messages: []
|
|
20300
20354
|
});
|
|
@@ -20756,7 +20810,7 @@ var init_text_utils = __esm({
|
|
|
20756
20810
|
|
|
20757
20811
|
// ee/agentic-retrieval/pipeline/prefilter.ts
|
|
20758
20812
|
async function exactTokenPrefilter({
|
|
20759
|
-
cacheKey,
|
|
20813
|
+
cacheKey: cacheKey2,
|
|
20760
20814
|
tokens,
|
|
20761
20815
|
context,
|
|
20762
20816
|
fields,
|
|
@@ -20764,13 +20818,13 @@ async function exactTokenPrefilter({
|
|
|
20764
20818
|
minTokenLength = 3,
|
|
20765
20819
|
limit
|
|
20766
20820
|
}) {
|
|
20767
|
-
const
|
|
20821
|
+
const cache3 = await ensureItemsCache({ cacheKey: cacheKey2, context, fields, normalize });
|
|
20768
20822
|
const strip = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
20769
20823
|
const normalizedTokens = [...new Set(tokens.map(strip))].filter((t) => t.length >= minTokenLength);
|
|
20770
20824
|
if (!normalizedTokens.length) {
|
|
20771
20825
|
return [];
|
|
20772
20826
|
}
|
|
20773
|
-
const matches =
|
|
20827
|
+
const matches = cache3.items.filter((item) => {
|
|
20774
20828
|
const haystack = strip(item.normalized || "");
|
|
20775
20829
|
return normalizedTokens.some((token) => haystack.includes(token));
|
|
20776
20830
|
});
|
|
@@ -20782,7 +20836,7 @@ async function exactTokenPrefilter({
|
|
|
20782
20836
|
}));
|
|
20783
20837
|
}
|
|
20784
20838
|
async function fuzzyPrefilter({
|
|
20785
|
-
cacheKey,
|
|
20839
|
+
cacheKey: cacheKey2,
|
|
20786
20840
|
relevantKeywords,
|
|
20787
20841
|
importantKeyword,
|
|
20788
20842
|
context,
|
|
@@ -20793,14 +20847,14 @@ async function fuzzyPrefilter({
|
|
|
20793
20847
|
supplementSeparatorVariants = false,
|
|
20794
20848
|
supplementBudget = SUPPLEMENT_BUDGET
|
|
20795
20849
|
}) {
|
|
20796
|
-
const
|
|
20850
|
+
const cache3 = await ensureItemsCache({ cacheKey: cacheKey2, context, fields, normalize });
|
|
20797
20851
|
if (!relevantKeywords?.length) {
|
|
20798
20852
|
return [];
|
|
20799
20853
|
}
|
|
20800
20854
|
const uniqueKeywords = [...new Set(relevantKeywords.flatMap((k) => k.split(" ")))];
|
|
20801
|
-
const index = import_fuse.default.parseIndex(
|
|
20855
|
+
const index = import_fuse.default.parseIndex(cache3.fuseIndex);
|
|
20802
20856
|
const fuse = new import_fuse.default(
|
|
20803
|
-
|
|
20857
|
+
cache3.items,
|
|
20804
20858
|
{
|
|
20805
20859
|
includeScore: true,
|
|
20806
20860
|
useExtendedSearch: true,
|
|
@@ -20889,7 +20943,7 @@ async function fuzzyPrefilter({
|
|
|
20889
20943
|
].sort((a, b) => b.length - a.length);
|
|
20890
20944
|
if (supplementTokens.length > 0) {
|
|
20891
20945
|
const seen = new Set(prefiltered.map((p) => p.id));
|
|
20892
|
-
const candidates =
|
|
20946
|
+
const candidates = cache3.items.filter(
|
|
20893
20947
|
(item) => item.id && !seen.has(item.id) && supplementTokens.some((t) => (item.stripped ?? "").includes(t))
|
|
20894
20948
|
).map((item, idx) => {
|
|
20895
20949
|
const nameStripped = stripSeparators(item.name ?? "");
|
|
@@ -21009,12 +21063,12 @@ var init_prefilter = __esm({
|
|
|
21009
21063
|
SUPPLEMENT_BUDGET_WIDE = 50;
|
|
21010
21064
|
itemCaches = {};
|
|
21011
21065
|
ensureItemsCache = async ({
|
|
21012
|
-
cacheKey,
|
|
21066
|
+
cacheKey: cacheKey2,
|
|
21013
21067
|
context,
|
|
21014
21068
|
fields,
|
|
21015
21069
|
normalize
|
|
21016
21070
|
}) => {
|
|
21017
|
-
if (!itemCaches[
|
|
21071
|
+
if (!itemCaches[cacheKey2] || Date.now() - itemCaches[cacheKey2].tsp.getTime() > 5 * 60 * 1e3 || itemCaches[cacheKey2].items.length === 0) {
|
|
21018
21072
|
const result = await context.getItems({ fields, filters: [] });
|
|
21019
21073
|
const normalizedItems = result.map((item) => {
|
|
21020
21074
|
const normalized = normalize(item);
|
|
@@ -21031,14 +21085,14 @@ var init_prefilter = __esm({
|
|
|
21031
21085
|
stripped: stripSeparators(normalized ?? item.name ?? "")
|
|
21032
21086
|
};
|
|
21033
21087
|
});
|
|
21034
|
-
itemCaches[
|
|
21035
|
-
cacheKey,
|
|
21088
|
+
itemCaches[cacheKey2] = {
|
|
21089
|
+
cacheKey: cacheKey2,
|
|
21036
21090
|
items: normalizedItems,
|
|
21037
21091
|
tsp: /* @__PURE__ */ new Date(),
|
|
21038
21092
|
fuseIndex: import_fuse.default.createIndex(["normalized"], normalizedItems)
|
|
21039
21093
|
};
|
|
21040
21094
|
}
|
|
21041
|
-
return itemCaches[
|
|
21095
|
+
return itemCaches[cacheKey2];
|
|
21042
21096
|
};
|
|
21043
21097
|
FUZZY_EXTRACTION_PROMPT = (set) => `
|
|
21044
21098
|
You are checking whether the user's question references any "${set.name}".
|
|
@@ -22262,12 +22316,12 @@ async function rerankResults(opts) {
|
|
|
22262
22316
|
duplicateOf = /* @__PURE__ */ new Map();
|
|
22263
22317
|
}
|
|
22264
22318
|
}
|
|
22265
|
-
const selectDistinct = (
|
|
22266
|
-
if (duplicateOf.size === 0) return
|
|
22319
|
+
const selectDistinct = (pool3, n) => {
|
|
22320
|
+
if (duplicateOf.size === 0) return pool3.slice(0, n);
|
|
22267
22321
|
const picked = [];
|
|
22268
22322
|
const pickedIds = /* @__PURE__ */ new Set();
|
|
22269
22323
|
const deferred = [];
|
|
22270
|
-
for (const c of
|
|
22324
|
+
for (const c of pool3) {
|
|
22271
22325
|
if (picked.length >= n) break;
|
|
22272
22326
|
const id = c.chunk_id;
|
|
22273
22327
|
if (id && (duplicateOf.get(id) ?? []).some((other) => pickedIds.has(other))) {
|
|
@@ -23162,7 +23216,7 @@ __export(index_exports, {
|
|
|
23162
23216
|
});
|
|
23163
23217
|
module.exports = __toCommonJS(index_exports);
|
|
23164
23218
|
init_cjs_shims();
|
|
23165
|
-
var
|
|
23219
|
+
var import_config20 = require("dotenv/config");
|
|
23166
23220
|
|
|
23167
23221
|
// src/redis/client.ts
|
|
23168
23222
|
init_cjs_shims();
|
|
@@ -23282,6 +23336,140 @@ var import_express6 = require("express");
|
|
|
23282
23336
|
init_cjs_shims();
|
|
23283
23337
|
var import_express2 = require("express");
|
|
23284
23338
|
|
|
23339
|
+
// src/exulu/channels/lifecycle.ts
|
|
23340
|
+
init_cjs_shims();
|
|
23341
|
+
|
|
23342
|
+
// src/exulu/channels/licence.ts
|
|
23343
|
+
init_cjs_shims();
|
|
23344
|
+
init_entitlements();
|
|
23345
|
+
var channelsLicensed = () => checkLicense()["channels"] === true;
|
|
23346
|
+
|
|
23347
|
+
// src/exulu/channels/links.ts
|
|
23348
|
+
init_cjs_shims();
|
|
23349
|
+
var TABLE = "channel_links";
|
|
23350
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
23351
|
+
var timeOf = (v) => v instanceof Date ? v.getTime() : NaN;
|
|
23352
|
+
var linkState = (link, now) => {
|
|
23353
|
+
if (!link) return { state: "none" };
|
|
23354
|
+
if (link.revoked_at !== null && link.revoked_at !== void 0) return { state: "revoked" };
|
|
23355
|
+
const expiry = timeOf(link.expires_at);
|
|
23356
|
+
const at = timeOf(now);
|
|
23357
|
+
if (!Number.isFinite(expiry) || !Number.isFinite(at) || at >= expiry) return { state: "expired" };
|
|
23358
|
+
return { state: "valid", link };
|
|
23359
|
+
};
|
|
23360
|
+
var expiryFor = (linkedAt, linkTtlDays) => new Date(linkedAt.getTime() + linkTtlDays * DAY_MS);
|
|
23361
|
+
var toDate = (v) => v instanceof Date ? v : new Date(v);
|
|
23362
|
+
var toDateOrNull = (v) => v == null ? null : toDate(v);
|
|
23363
|
+
var fromRow = (row) => ({
|
|
23364
|
+
id: row.id,
|
|
23365
|
+
channel: row.channel,
|
|
23366
|
+
identity: row.identity,
|
|
23367
|
+
user: row.user,
|
|
23368
|
+
linked_at: toDate(row.linked_at),
|
|
23369
|
+
expires_at: toDate(row.expires_at),
|
|
23370
|
+
revoked_at: toDateOrNull(row.revoked_at),
|
|
23371
|
+
last_seen_at: toDateOrNull(row.last_seen_at)
|
|
23372
|
+
});
|
|
23373
|
+
var createLinkStore = (db2) => ({
|
|
23374
|
+
async find(channelId, identity) {
|
|
23375
|
+
const row = await db2(TABLE).where({ channel: channelId, identity }).first();
|
|
23376
|
+
return row ? fromRow(row) : void 0;
|
|
23377
|
+
},
|
|
23378
|
+
/** Atomic on the unique (channel, identity) index, so concurrent links cannot race. */
|
|
23379
|
+
async upsert(p) {
|
|
23380
|
+
const values = {
|
|
23381
|
+
user: p.userId,
|
|
23382
|
+
linked_at: p.now,
|
|
23383
|
+
expires_at: expiryFor(p.now, p.linkTtlDays),
|
|
23384
|
+
revoked_at: null,
|
|
23385
|
+
last_seen_at: null,
|
|
23386
|
+
updatedAt: p.now
|
|
23387
|
+
};
|
|
23388
|
+
const [row] = await db2(TABLE).insert({ channel: p.channelId, identity: p.identity, ...values }).onConflict(["channel", "identity"]).merge(values).returning("*");
|
|
23389
|
+
return fromRow(row);
|
|
23390
|
+
},
|
|
23391
|
+
async revoke(linkId, now) {
|
|
23392
|
+
await db2(TABLE).where({ id: linkId }).update({ revoked_at: now, updatedAt: now });
|
|
23393
|
+
},
|
|
23394
|
+
/** Records activity only; never touches expires_at. */
|
|
23395
|
+
async touch(linkId, now) {
|
|
23396
|
+
await db2(TABLE).where({ id: linkId }).update({ last_seen_at: now });
|
|
23397
|
+
},
|
|
23398
|
+
async listForChannel(channelId) {
|
|
23399
|
+
const rows = await db2(TABLE).where({ channel: channelId }).orderBy("linked_at", "desc");
|
|
23400
|
+
return rows.map(fromRow);
|
|
23401
|
+
},
|
|
23402
|
+
async listForUser(channelId, userId) {
|
|
23403
|
+
const rows = await db2(TABLE).where({ channel: channelId, user: userId }).orderBy("linked_at", "desc");
|
|
23404
|
+
return rows.map(fromRow);
|
|
23405
|
+
},
|
|
23406
|
+
/** All links of a user across channels (data export). */
|
|
23407
|
+
async listAllForUser(userId) {
|
|
23408
|
+
const rows = await db2(TABLE).where({ user: userId }).orderBy("linked_at", "desc");
|
|
23409
|
+
return rows.map(fromRow);
|
|
23410
|
+
},
|
|
23411
|
+
async deleteForUser(userId) {
|
|
23412
|
+
return db2(TABLE).where({ user: userId }).del();
|
|
23413
|
+
}
|
|
23414
|
+
});
|
|
23415
|
+
|
|
23416
|
+
// src/exulu/channels/log.ts
|
|
23417
|
+
init_cjs_shims();
|
|
23418
|
+
var ChannelSetupError = class extends Error {
|
|
23419
|
+
constructor(message) {
|
|
23420
|
+
super(message);
|
|
23421
|
+
this.name = "ChannelSetupError";
|
|
23422
|
+
}
|
|
23423
|
+
};
|
|
23424
|
+
var CODE = /^[A-Za-z0-9_.-]{1,32}$/;
|
|
23425
|
+
var safeError = (error) => {
|
|
23426
|
+
const name = error instanceof Error ? error.constructor?.name && error.constructor.name !== "Object" ? error.constructor.name : "Error" : typeof error;
|
|
23427
|
+
const code = error?.code;
|
|
23428
|
+
const safe = typeof code === "string" && CODE.test(code) ? { name, code } : { name };
|
|
23429
|
+
if (error instanceof ChannelSetupError) safe.message = error.message;
|
|
23430
|
+
return safe;
|
|
23431
|
+
};
|
|
23432
|
+
var sanitizedError = (context, error) => {
|
|
23433
|
+
const safe = safeError(error);
|
|
23434
|
+
return new Error(`${context} (${safe.name}${safe.code ? ` ${safe.code}` : ""}${safe.message ? `: ${safe.message}` : ""})`);
|
|
23435
|
+
};
|
|
23436
|
+
|
|
23437
|
+
// src/exulu/channels/lifecycle.ts
|
|
23438
|
+
var LOG = "[EXULU-CHANNEL]";
|
|
23439
|
+
var TABLE2 = "channel_links";
|
|
23440
|
+
var channelLinksForExport = async (db2, userId) => {
|
|
23441
|
+
if (!channelsLicensed()) return [];
|
|
23442
|
+
try {
|
|
23443
|
+
if (!await db2.schema.hasTable(TABLE2)) return [];
|
|
23444
|
+
const links = await createLinkStore(db2).listAllForUser(userId);
|
|
23445
|
+
return links.map((l) => ({
|
|
23446
|
+
channel: l.channel,
|
|
23447
|
+
identity: l.identity,
|
|
23448
|
+
linked_at: l.linked_at,
|
|
23449
|
+
expires_at: l.expires_at,
|
|
23450
|
+
revoked_at: l.revoked_at,
|
|
23451
|
+
last_seen_at: l.last_seen_at
|
|
23452
|
+
}));
|
|
23453
|
+
} catch (error) {
|
|
23454
|
+
console.error(`${LOG} reading the links for a data export failed`, safeError(error));
|
|
23455
|
+
return [];
|
|
23456
|
+
}
|
|
23457
|
+
};
|
|
23458
|
+
var afterUserDelete = async (db2, userId) => {
|
|
23459
|
+
const id = Number(userId);
|
|
23460
|
+
if (!Number.isFinite(id)) return;
|
|
23461
|
+
if (!channelsLicensed()) return;
|
|
23462
|
+
if (!await db2.schema.hasTable(TABLE2)) return;
|
|
23463
|
+
await createLinkStore(db2).deleteForUser(id);
|
|
23464
|
+
};
|
|
23465
|
+
var afterUserDeleteBestEffort = async (db2, userId) => {
|
|
23466
|
+
try {
|
|
23467
|
+
await afterUserDelete(db2, userId);
|
|
23468
|
+
} catch (error) {
|
|
23469
|
+
console.error(`${LOG} removing the links of deleted user ${Number(userId)} failed`, safeError(error));
|
|
23470
|
+
}
|
|
23471
|
+
};
|
|
23472
|
+
|
|
23285
23473
|
// src/validators/requests.ts
|
|
23286
23474
|
init_cjs_shims();
|
|
23287
23475
|
init_user();
|
|
@@ -23574,7 +23762,8 @@ init_entitlements();
|
|
|
23574
23762
|
var global_queues = {
|
|
23575
23763
|
eval_runs: "eval_runs",
|
|
23576
23764
|
email_intake: "email_intake",
|
|
23577
|
-
import: "import"
|
|
23765
|
+
import: "import",
|
|
23766
|
+
channel_inbound: "channel_inbound"
|
|
23578
23767
|
};
|
|
23579
23768
|
var ExuluQueues = class {
|
|
23580
23769
|
queues;
|
|
@@ -23983,9 +24172,9 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
|
|
|
23983
24172
|
if (result.tools) {
|
|
23984
24173
|
result.tools = await Promise.all(
|
|
23985
24174
|
result.tools.map(
|
|
23986
|
-
async (
|
|
24175
|
+
async (tool5) => {
|
|
23987
24176
|
let hydrated;
|
|
23988
|
-
if (
|
|
24177
|
+
if (tool5.id === "agentic_context_search") {
|
|
23989
24178
|
const instance2 = createAgenticRetrievalTool({
|
|
23990
24179
|
contexts: [],
|
|
23991
24180
|
user,
|
|
@@ -24000,22 +24189,22 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
|
|
|
24000
24189
|
name: instance2.name,
|
|
24001
24190
|
description: instance2.description,
|
|
24002
24191
|
category: instance2.category,
|
|
24003
|
-
config:
|
|
24192
|
+
config: tool5.config
|
|
24004
24193
|
};
|
|
24005
24194
|
}
|
|
24006
|
-
if (
|
|
24007
|
-
if (
|
|
24195
|
+
if (tool5.type === "agent") {
|
|
24196
|
+
if (tool5.id === result.id) {
|
|
24008
24197
|
return null;
|
|
24009
24198
|
}
|
|
24010
|
-
const instance2 = await exuluApp.get().agent(
|
|
24199
|
+
const instance2 = await exuluApp.get().agent(tool5.id);
|
|
24011
24200
|
if (!instance2) {
|
|
24012
24201
|
throw new Error(
|
|
24013
|
-
"Trying to load a tool of type 'agent', but the associated agent with id " +
|
|
24202
|
+
"Trying to load a tool of type 'agent', but the associated agent with id " + tool5.id + " was not found in the database."
|
|
24014
24203
|
);
|
|
24015
24204
|
}
|
|
24016
24205
|
if (!instance2.model) {
|
|
24017
24206
|
throw new Error(
|
|
24018
|
-
"Trying to load a tool of type 'agent', but the associated agent with id " +
|
|
24207
|
+
"Trying to load a tool of type 'agent', but the associated agent with id " + tool5.id + " does not have a model set for it."
|
|
24019
24208
|
);
|
|
24020
24209
|
}
|
|
24021
24210
|
const hasAccessToAgent = await checkRecordAccess(instance2, "read", user);
|
|
@@ -24035,13 +24224,13 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
|
|
|
24035
24224
|
throw new Error("Litellm not configured or running.");
|
|
24036
24225
|
}
|
|
24037
24226
|
} else {
|
|
24038
|
-
hydrated = tools.find((t) => t.id ===
|
|
24227
|
+
hydrated = tools.find((t) => t.id === tool5.id);
|
|
24039
24228
|
}
|
|
24040
24229
|
const hydratedTool = {
|
|
24041
|
-
...
|
|
24230
|
+
...tool5,
|
|
24042
24231
|
name: hydrated?.name || "",
|
|
24043
24232
|
description: hydrated?.description || "",
|
|
24044
|
-
category:
|
|
24233
|
+
category: tool5?.category || "default",
|
|
24045
24234
|
needsApproval: true
|
|
24046
24235
|
};
|
|
24047
24236
|
console.log("[EXULU] hydratedTool", hydratedTool);
|
|
@@ -24051,7 +24240,7 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
|
|
|
24051
24240
|
);
|
|
24052
24241
|
if (args.project) {
|
|
24053
24242
|
const hasAgentic = result.tools.some(
|
|
24054
|
-
(
|
|
24243
|
+
(tool5) => tool5?.id === "agentic_context_search"
|
|
24055
24244
|
);
|
|
24056
24245
|
if (!hasAgentic) {
|
|
24057
24246
|
const instance2 = createAgenticRetrievalTool({
|
|
@@ -24072,7 +24261,7 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
|
|
|
24072
24261
|
}
|
|
24073
24262
|
}
|
|
24074
24263
|
}
|
|
24075
|
-
result.tools = result.tools.filter((
|
|
24264
|
+
result.tools = result.tools.filter((tool5) => tool5 !== null);
|
|
24076
24265
|
} else {
|
|
24077
24266
|
result.tools = [];
|
|
24078
24267
|
}
|
|
@@ -25644,6 +25833,837 @@ var applyAgentGuestFieldTransforms = async (input) => {
|
|
|
25644
25833
|
return input;
|
|
25645
25834
|
};
|
|
25646
25835
|
|
|
25836
|
+
// src/exulu/channels/api.ts
|
|
25837
|
+
init_cjs_shims();
|
|
25838
|
+
var import_crypto7 = require("crypto");
|
|
25839
|
+
|
|
25840
|
+
// src/exulu/channels/access.ts
|
|
25841
|
+
init_cjs_shims();
|
|
25842
|
+
|
|
25843
|
+
// src/exulu/public-agents.ts
|
|
25844
|
+
init_cjs_shims();
|
|
25845
|
+
init_shared_artifacts();
|
|
25846
|
+
var LOCALE_KEY = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})?$/;
|
|
25847
|
+
var welcomeTranslations = (raw) => {
|
|
25848
|
+
let value = raw;
|
|
25849
|
+
if (typeof value === "string") {
|
|
25850
|
+
try {
|
|
25851
|
+
value = JSON.parse(value);
|
|
25852
|
+
} catch {
|
|
25853
|
+
return {};
|
|
25854
|
+
}
|
|
25855
|
+
}
|
|
25856
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
25857
|
+
const result = {};
|
|
25858
|
+
for (const [key, text] of Object.entries(value)) {
|
|
25859
|
+
if (!LOCALE_KEY.test(key) || typeof text !== "string") continue;
|
|
25860
|
+
const trimmed = text.trim();
|
|
25861
|
+
if (trimmed) result[key] = trimmed;
|
|
25862
|
+
}
|
|
25863
|
+
return result;
|
|
25864
|
+
};
|
|
25865
|
+
var publicAgentView = (row, slug) => ({
|
|
25866
|
+
id: row.id,
|
|
25867
|
+
name: row.name ?? "",
|
|
25868
|
+
description: row.description ?? "",
|
|
25869
|
+
image: row.image ?? null,
|
|
25870
|
+
welcomemessage: row.welcomemessage ?? "",
|
|
25871
|
+
welcomemessage_translations: welcomeTranslations(row.welcomemessage_translations),
|
|
25872
|
+
slug,
|
|
25873
|
+
guest_auth_mode: row.guest_auth_mode || "regular",
|
|
25874
|
+
guest_has_cover: !!row.guest_cover_image,
|
|
25875
|
+
guest_has_idle_animation: !!row.animation_idle,
|
|
25876
|
+
guest_has_responding_animation: !!row.animation_responding
|
|
25877
|
+
});
|
|
25878
|
+
var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
|
|
25879
|
+
if (agent.guest_access) {
|
|
25880
|
+
if (userId != null) return { allowed: true, via: "guest" };
|
|
25881
|
+
const mode = agent.guest_auth_mode || "regular";
|
|
25882
|
+
if (mode === "public") return { allowed: true, via: "guest" };
|
|
25883
|
+
if (mode === "password") {
|
|
25884
|
+
if (agent.guest_password_hash && guestPassword) {
|
|
25885
|
+
const ok = await verifySharePassword(guestPassword, agent.guest_password_hash);
|
|
25886
|
+
if (ok) return { allowed: true, via: "guest" };
|
|
25887
|
+
return { allowed: false, status: 401, message: "Incorrect password." };
|
|
25888
|
+
}
|
|
25889
|
+
return { allowed: false, status: 401, message: "Password required." };
|
|
25890
|
+
}
|
|
25891
|
+
return { allowed: false, status: 401, message: "Authentication required." };
|
|
25892
|
+
}
|
|
25893
|
+
if (userId == null && agent.rights_mode === "public") {
|
|
25894
|
+
return { allowed: true, via: "rbac-public" };
|
|
25895
|
+
}
|
|
25896
|
+
return { allowed: false, status: 401, message: "Authentication required." };
|
|
25897
|
+
};
|
|
25898
|
+
|
|
25899
|
+
// src/utils/check-api-key-scope.ts
|
|
25900
|
+
init_cjs_shims();
|
|
25901
|
+
function checkApiKeyScope(user, agentId) {
|
|
25902
|
+
if (!user || user.type !== "api") return { allowed: true };
|
|
25903
|
+
if (!user.scope_mode || user.scope_mode === "admin") return { allowed: true };
|
|
25904
|
+
if (user.scope_mode === "agents") {
|
|
25905
|
+
const ids = Array.isArray(user.agent_ids) ? user.agent_ids : [];
|
|
25906
|
+
if (!ids.includes(agentId)) {
|
|
25907
|
+
return {
|
|
25908
|
+
allowed: false,
|
|
25909
|
+
reason: `API key is not scoped to agent ${agentId}.`,
|
|
25910
|
+
code: 403
|
|
25911
|
+
};
|
|
25912
|
+
}
|
|
25913
|
+
return { allowed: true };
|
|
25914
|
+
}
|
|
25915
|
+
return { allowed: false, reason: "Unknown scope_mode.", code: 401 };
|
|
25916
|
+
}
|
|
25917
|
+
|
|
25918
|
+
// src/exulu/channels/config.ts
|
|
25919
|
+
init_cjs_shims();
|
|
25920
|
+
init_credential_store();
|
|
25921
|
+
|
|
25922
|
+
// src/exulu/channels/types.ts
|
|
25923
|
+
init_cjs_shims();
|
|
25924
|
+
var REPLY_KEYS = [
|
|
25925
|
+
"linkRequired",
|
|
25926
|
+
"linked",
|
|
25927
|
+
"codeInvalid",
|
|
25928
|
+
"textOnly",
|
|
25929
|
+
"rateLimited",
|
|
25930
|
+
"stillWorking",
|
|
25931
|
+
"runFailed",
|
|
25932
|
+
"newSession",
|
|
25933
|
+
"unlinked"
|
|
25934
|
+
];
|
|
25935
|
+
|
|
25936
|
+
// src/exulu/channels/config.ts
|
|
25937
|
+
var ChannelConfigError = class extends Error {
|
|
25938
|
+
field;
|
|
25939
|
+
constructor(field, message) {
|
|
25940
|
+
super(message);
|
|
25941
|
+
this.name = "ChannelConfigError";
|
|
25942
|
+
this.field = field;
|
|
25943
|
+
}
|
|
25944
|
+
};
|
|
25945
|
+
var DEFAULTS = { linkTtlDays: 7, sessionIdleHours: 8, locale: "de" };
|
|
25946
|
+
var parseMaybeJson = (value) => {
|
|
25947
|
+
if (typeof value !== "string") {
|
|
25948
|
+
return value;
|
|
25949
|
+
}
|
|
25950
|
+
try {
|
|
25951
|
+
return JSON.parse(value);
|
|
25952
|
+
} catch {
|
|
25953
|
+
throw new ChannelConfigError("config", "config is not valid JSON");
|
|
25954
|
+
}
|
|
25955
|
+
};
|
|
25956
|
+
var nonEmptyString = (field, value) => {
|
|
25957
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
25958
|
+
throw new ChannelConfigError(field, `${field} must be a non-empty string`);
|
|
25959
|
+
}
|
|
25960
|
+
return value;
|
|
25961
|
+
};
|
|
25962
|
+
var boundedInt = (field, value, fallback, max) => {
|
|
25963
|
+
if (value === void 0) {
|
|
25964
|
+
return fallback;
|
|
25965
|
+
}
|
|
25966
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max) {
|
|
25967
|
+
throw new ChannelConfigError(field, `${field} must be an integer between 1 and ${max}`);
|
|
25968
|
+
}
|
|
25969
|
+
return value;
|
|
25970
|
+
};
|
|
25971
|
+
var parseChannelConfig = (raw) => {
|
|
25972
|
+
const value = parseMaybeJson(raw);
|
|
25973
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
25974
|
+
throw new ChannelConfigError("config", "config must be an object");
|
|
25975
|
+
}
|
|
25976
|
+
const c = value;
|
|
25977
|
+
const locale = c.locale === void 0 ? DEFAULTS.locale : c.locale;
|
|
25978
|
+
if (locale !== "de" && locale !== "en") {
|
|
25979
|
+
throw new ChannelConfigError("locale", 'locale must be "de" or "en"');
|
|
25980
|
+
}
|
|
25981
|
+
const texts = {};
|
|
25982
|
+
if (c.texts !== void 0) {
|
|
25983
|
+
if (c.texts === null || typeof c.texts !== "object" || Array.isArray(c.texts)) {
|
|
25984
|
+
throw new ChannelConfigError("texts", "texts must be an object");
|
|
25985
|
+
}
|
|
25986
|
+
for (const [key, text] of Object.entries(c.texts)) {
|
|
25987
|
+
if (!REPLY_KEYS.includes(key)) {
|
|
25988
|
+
throw new ChannelConfigError("texts", `unknown text key "${key}"`);
|
|
25989
|
+
}
|
|
25990
|
+
if (typeof text !== "string") {
|
|
25991
|
+
throw new ChannelConfigError("texts", `text "${key}" must be a string`);
|
|
25992
|
+
}
|
|
25993
|
+
texts[key] = text;
|
|
25994
|
+
}
|
|
25995
|
+
}
|
|
25996
|
+
return {
|
|
25997
|
+
phoneNumberId: nonEmptyString("phoneNumberId", c.phoneNumberId),
|
|
25998
|
+
displayNumber: nonEmptyString("displayNumber", c.displayNumber),
|
|
25999
|
+
linkTtlDays: boundedInt("linkTtlDays", c.linkTtlDays, DEFAULTS.linkTtlDays, 365),
|
|
26000
|
+
sessionIdleHours: boundedInt("sessionIdleHours", c.sessionIdleHours, DEFAULTS.sessionIdleHours, 168),
|
|
26001
|
+
locale,
|
|
26002
|
+
texts
|
|
26003
|
+
};
|
|
26004
|
+
};
|
|
26005
|
+
var sealSecrets = (s) => encrypt(JSON.stringify({ accessToken: s.accessToken, appSecret: s.appSecret }));
|
|
26006
|
+
var readSecrets = (row) => {
|
|
26007
|
+
if (!row.secrets) {
|
|
26008
|
+
return null;
|
|
26009
|
+
}
|
|
26010
|
+
try {
|
|
26011
|
+
const parsed = JSON.parse(decrypt(row.secrets));
|
|
26012
|
+
if (typeof parsed?.accessToken === "string" && parsed.accessToken !== "" && typeof parsed?.appSecret === "string" && parsed.appSecret !== "") {
|
|
26013
|
+
return { accessToken: parsed.accessToken, appSecret: parsed.appSecret };
|
|
26014
|
+
}
|
|
26015
|
+
return null;
|
|
26016
|
+
} catch {
|
|
26017
|
+
return null;
|
|
26018
|
+
}
|
|
26019
|
+
};
|
|
26020
|
+
var canEnableChannel = (agent) => {
|
|
26021
|
+
if (!agent.guest_access) {
|
|
26022
|
+
return { ok: false, reason: "guest_access_off" };
|
|
26023
|
+
}
|
|
26024
|
+
if (agent.guest_auth_mode != null && agent.guest_auth_mode !== "regular") {
|
|
26025
|
+
return { ok: false, reason: "guest_mode_not_regular" };
|
|
26026
|
+
}
|
|
26027
|
+
return { ok: true };
|
|
26028
|
+
};
|
|
26029
|
+
var channelView = (row) => ({
|
|
26030
|
+
id: row.id,
|
|
26031
|
+
agent: row.agent,
|
|
26032
|
+
type: row.type,
|
|
26033
|
+
enabled: row.enabled,
|
|
26034
|
+
config: parseChannelConfig(row.config),
|
|
26035
|
+
hasSecrets: !!row.secrets,
|
|
26036
|
+
needsCredentials: readSecrets(row) === null
|
|
26037
|
+
});
|
|
26038
|
+
var maskIdentity = (identity) => identity.length < 4 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022 ${identity.slice(-4)}`;
|
|
26039
|
+
var linkPageUrl = (agentId) => {
|
|
26040
|
+
const base = [process.env.CHANNEL_LINK_BASE_URL, process.env.FRONTEND, process.env.NEXTAUTH_URL].map((v) => (v ?? "").trim()).find((v) => v !== "");
|
|
26041
|
+
if (!base) {
|
|
26042
|
+
throw new ChannelSetupError("None of CHANNEL_LINK_BASE_URL, FRONTEND and NEXTAUTH_URL is set; the channel link page has no URL");
|
|
26043
|
+
}
|
|
26044
|
+
return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp`;
|
|
26045
|
+
};
|
|
26046
|
+
|
|
26047
|
+
// src/exulu/channels/decide.ts
|
|
26048
|
+
init_cjs_shims();
|
|
26049
|
+
|
|
26050
|
+
// src/exulu/channels/link-codes.ts
|
|
26051
|
+
init_cjs_shims();
|
|
26052
|
+
var import_crypto6 = require("crypto");
|
|
26053
|
+
var CODE_TTL_SECONDS = 600;
|
|
26054
|
+
var ATTEMPT_WINDOW_SECONDS = 3600;
|
|
26055
|
+
var MAX_ATTEMPTS = 5;
|
|
26056
|
+
var PROMPT_WINDOW_SECONDS = 600;
|
|
26057
|
+
var ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
26058
|
+
var CODE_LENGTH = 8;
|
|
26059
|
+
var hashCode = (raw) => (0, import_crypto6.createHash)("sha256").update(raw).digest("hex");
|
|
26060
|
+
var codeKey = (raw) => `channel-link:code:${hashCode(raw)}`;
|
|
26061
|
+
var userKey = (channelId, userId) => `channel-link:user:${channelId}:${userId}`;
|
|
26062
|
+
var generateCode = () => {
|
|
26063
|
+
let raw = "";
|
|
26064
|
+
for (let i = 0; i < CODE_LENGTH; i++) raw += ALPHABET[(0, import_crypto6.randomInt)(ALPHABET.length)];
|
|
26065
|
+
return `${raw.slice(0, 4)}-${raw.slice(4)}`;
|
|
26066
|
+
};
|
|
26067
|
+
var CODE_SHAPE = /^([A-HJ-NP-Z2-9]{4})(?:-| +)?([A-HJ-NP-Z2-9]{4})$/i;
|
|
26068
|
+
var MAX_CODE_INPUT = 64;
|
|
26069
|
+
var normalizeCode = (text) => {
|
|
26070
|
+
const trimmed = text.trim();
|
|
26071
|
+
if (trimmed.length > MAX_CODE_INPUT) return null;
|
|
26072
|
+
const m = CODE_SHAPE.exec(trimmed);
|
|
26073
|
+
return m ? `${m[1]}-${m[2]}`.toUpperCase() : null;
|
|
26074
|
+
};
|
|
26075
|
+
var issueCode = async (kv, p) => {
|
|
26076
|
+
const pointer = userKey(p.channelId, p.userId);
|
|
26077
|
+
const previous = await kv.getDel(pointer);
|
|
26078
|
+
if (previous) await kv.del(`channel-link:code:${previous}`);
|
|
26079
|
+
const code = generateCode();
|
|
26080
|
+
const hash = hashCode(code.replace("-", ""));
|
|
26081
|
+
await kv.set(`channel-link:code:${hash}`, JSON.stringify({ channelId: p.channelId, userId: p.userId }), {
|
|
26082
|
+
EX: CODE_TTL_SECONDS
|
|
26083
|
+
});
|
|
26084
|
+
await kv.set(pointer, hash, { EX: CODE_TTL_SECONDS });
|
|
26085
|
+
return code;
|
|
26086
|
+
};
|
|
26087
|
+
var consumeCode = async (kv, code) => {
|
|
26088
|
+
const normalized = normalizeCode(code);
|
|
26089
|
+
if (!normalized) return null;
|
|
26090
|
+
const value = await kv.getDel(codeKey(normalized.replace("-", "")));
|
|
26091
|
+
if (!value) return null;
|
|
26092
|
+
let parsed;
|
|
26093
|
+
try {
|
|
26094
|
+
parsed = JSON.parse(value);
|
|
26095
|
+
} catch {
|
|
26096
|
+
return null;
|
|
26097
|
+
}
|
|
26098
|
+
await kv.del(userKey(parsed.channelId, parsed.userId));
|
|
26099
|
+
return { channelId: parsed.channelId, userId: parsed.userId };
|
|
26100
|
+
};
|
|
26101
|
+
var codeAttemptsExceeded = async (kv, channelId, identity) => {
|
|
26102
|
+
const key = `channel-link:attempts:${channelId}:${identity}`;
|
|
26103
|
+
const n = await kv.incr(key);
|
|
26104
|
+
if (n === 1 || await kv.ttl(key) === -1) await kv.expire(key, ATTEMPT_WINDOW_SECONDS);
|
|
26105
|
+
return n > MAX_ATTEMPTS;
|
|
26106
|
+
};
|
|
26107
|
+
var linkPromptAllowed = async (kv, channelId, identity) => {
|
|
26108
|
+
const key = `channel-link:prompt:${channelId}:${identity}`;
|
|
26109
|
+
return await kv.set(key, "1", { EX: PROMPT_WINDOW_SECONDS, NX: true }) !== null;
|
|
26110
|
+
};
|
|
26111
|
+
|
|
26112
|
+
// src/exulu/channels/decide.ts
|
|
26113
|
+
var isUserActive = (user) => user !== void 0;
|
|
26114
|
+
var NEW_SESSION_COMMANDS = /* @__PURE__ */ new Set(["/neu", "/new"]);
|
|
26115
|
+
var LOGOUT_COMMANDS = /* @__PURE__ */ new Set(["/abmelden", "/logout"]);
|
|
26116
|
+
var reply = (key, vars) => vars ? { kind: "reply", key, vars } : { kind: "reply", key };
|
|
26117
|
+
var notLinked = async (msg, deps) => await deps.linkPromptAllowed(msg.identity) ? reply("linkRequired", { linkUrl: deps.linkUrl() }) : { kind: "silent" };
|
|
26118
|
+
var tryCode = async (code, msg, deps) => {
|
|
26119
|
+
if (await deps.codeAttemptsExceeded(msg.identity)) {
|
|
26120
|
+
deps.audit({ type: "code_lockout", identity: msg.identity });
|
|
26121
|
+
return { lockedOut: true };
|
|
26122
|
+
}
|
|
26123
|
+
const consumed = await deps.consumeCode(code);
|
|
26124
|
+
if (!consumed || consumed.channelId !== msg.channelId) return { lockedOut: false };
|
|
26125
|
+
const access = await deps.access(consumed.userId);
|
|
26126
|
+
if (access === "unavailable") return { decision: { kind: "silent" }, lockedOut: false };
|
|
26127
|
+
if (access !== "allowed") return { lockedOut: false };
|
|
26128
|
+
const link = await deps.links.upsert({
|
|
26129
|
+
channelId: msg.channelId,
|
|
26130
|
+
identity: msg.identity,
|
|
26131
|
+
userId: consumed.userId,
|
|
26132
|
+
linkTtlDays: deps.config.linkTtlDays,
|
|
26133
|
+
now: deps.now()
|
|
26134
|
+
});
|
|
26135
|
+
deps.audit({ type: "linked", identity: msg.identity, userId: consumed.userId });
|
|
26136
|
+
return { decision: reply("linked", { expiresAt: link.expires_at }), lockedOut: false };
|
|
26137
|
+
};
|
|
26138
|
+
var decideInbound = async (msg, deps) => {
|
|
26139
|
+
const text = msg.text.trim();
|
|
26140
|
+
if (msg.hasAttachments || text === "") return reply("textOnly");
|
|
26141
|
+
const code = normalizeCode(text);
|
|
26142
|
+
let codeLockedOut = false;
|
|
26143
|
+
if (code !== null) {
|
|
26144
|
+
const tried = await tryCode(code, msg, deps);
|
|
26145
|
+
if (tried.decision) return tried.decision;
|
|
26146
|
+
codeLockedOut = tried.lockedOut;
|
|
26147
|
+
}
|
|
26148
|
+
const now = deps.now();
|
|
26149
|
+
const found = await deps.links.find(msg.channelId, msg.identity);
|
|
26150
|
+
const state = linkState(found, now);
|
|
26151
|
+
if (code !== null && state.state !== "valid") {
|
|
26152
|
+
return codeLockedOut ? { kind: "silent" } : reply("codeInvalid");
|
|
26153
|
+
}
|
|
26154
|
+
const command = text.toLowerCase();
|
|
26155
|
+
if (NEW_SESSION_COMMANDS.has(command) && state.state === "valid") {
|
|
26156
|
+
await deps.markNewSession(msg.identity);
|
|
26157
|
+
return reply("newSession");
|
|
26158
|
+
}
|
|
26159
|
+
if (LOGOUT_COMMANDS.has(command) && found && (state.state === "valid" || state.state === "expired")) {
|
|
26160
|
+
await deps.links.revoke(found.id, now);
|
|
26161
|
+
deps.audit({ type: "unlinked", identity: msg.identity, userId: found.user });
|
|
26162
|
+
return reply("unlinked");
|
|
26163
|
+
}
|
|
26164
|
+
if (state.state !== "valid") return notLinked(msg, deps);
|
|
26165
|
+
const link = state.link;
|
|
26166
|
+
const access = await deps.access(link.user);
|
|
26167
|
+
if (access === "unavailable") return { kind: "silent" };
|
|
26168
|
+
if (access !== "allowed") {
|
|
26169
|
+
await deps.links.revoke(link.id, now);
|
|
26170
|
+
deps.audit({ type: "access_rejected", identity: msg.identity, userId: link.user });
|
|
26171
|
+
return notLinked(msg, deps);
|
|
26172
|
+
}
|
|
26173
|
+
if (deps.rateLimited(link.user)) return reply("rateLimited");
|
|
26174
|
+
if (await deps.runInFlight(msg.identity)) return reply("stillWorking");
|
|
26175
|
+
await deps.links.touch(link.id, now);
|
|
26176
|
+
return { kind: "run", userId: link.user, newSession: await deps.takeNewSession(msg.identity) };
|
|
26177
|
+
};
|
|
26178
|
+
|
|
26179
|
+
// src/exulu/channels/access.ts
|
|
26180
|
+
var channelAccessCheck = async (p) => {
|
|
26181
|
+
try {
|
|
26182
|
+
const user = await p.db("users").where({ id: p.userId }).first();
|
|
26183
|
+
if (!isUserActive(user)) return "denied";
|
|
26184
|
+
if (!checkApiKeyScope(user, p.agentId).allowed) return "denied";
|
|
26185
|
+
const agent = await p.loadAgent(p.agentId);
|
|
26186
|
+
if (!agent) return "denied";
|
|
26187
|
+
if (!canEnableChannel(agent).ok) return "denied";
|
|
26188
|
+
const gate = await evaluateGuestChatAccess(agent, user.id, void 0);
|
|
26189
|
+
return gate.allowed ? "allowed" : "denied";
|
|
26190
|
+
} catch (error) {
|
|
26191
|
+
console.error(`[EXULU-CHANNEL] access check failed on channel ${p.channelId}`, safeError(error));
|
|
26192
|
+
return "unavailable";
|
|
26193
|
+
}
|
|
26194
|
+
};
|
|
26195
|
+
var channelAccessAllowed = async (p) => await channelAccessCheck(p) === "allowed";
|
|
26196
|
+
|
|
26197
|
+
// src/exulu/channels/audit.ts
|
|
26198
|
+
init_cjs_shims();
|
|
26199
|
+
init_logger();
|
|
26200
|
+
var CODE_LOCKOUT_AUDIT_WINDOW_SECONDS = 3600;
|
|
26201
|
+
var lockoutKey = (channelId, identity) => `channel-audit:code_lockout:${channelId}:${identity}`;
|
|
26202
|
+
var defaultLogger = () => getAuditLogger({});
|
|
26203
|
+
var buildAuditEvent = (channelId, agentId, event) => ({
|
|
26204
|
+
v: 1,
|
|
26205
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
26206
|
+
type: `channel.${event.type}`,
|
|
26207
|
+
actor: event.userId != null ? { kind: "user", userId: String(event.userId) } : { kind: "system" },
|
|
26208
|
+
...agentId ? { context: { agentId } } : {},
|
|
26209
|
+
target: { kind: "channel", id: channelId },
|
|
26210
|
+
status: event.type === "access_rejected" || event.type === "code_lockout" ? "denied" : "ok",
|
|
26211
|
+
data: { identity: maskIdentity(event.identity) }
|
|
26212
|
+
});
|
|
26213
|
+
var createChannelAuditor = (deps) => async (event) => {
|
|
26214
|
+
try {
|
|
26215
|
+
if (event.type === "code_lockout") {
|
|
26216
|
+
const first = await deps.kv.set(lockoutKey(deps.channelId, event.identity), "1", {
|
|
26217
|
+
EX: CODE_LOCKOUT_AUDIT_WINDOW_SECONDS,
|
|
26218
|
+
NX: true
|
|
26219
|
+
});
|
|
26220
|
+
if (first === null) return;
|
|
26221
|
+
}
|
|
26222
|
+
console.info(
|
|
26223
|
+
"[EXULU-CHANNEL] audit",
|
|
26224
|
+
JSON.stringify({
|
|
26225
|
+
event: event.type,
|
|
26226
|
+
channel: deps.channelId,
|
|
26227
|
+
identity: maskIdentity(event.identity),
|
|
26228
|
+
user: event.userId ?? null
|
|
26229
|
+
})
|
|
26230
|
+
);
|
|
26231
|
+
} catch (error) {
|
|
26232
|
+
console.error(`[EXULU-CHANNEL] audit ${event.type} on channel ${deps.channelId} failed`, safeError(error));
|
|
26233
|
+
return;
|
|
26234
|
+
}
|
|
26235
|
+
try {
|
|
26236
|
+
const logger = (deps.logger ?? defaultLogger)();
|
|
26237
|
+
if (logger.enabled) logger.record(buildAuditEvent(deps.channelId, deps.agentId, event));
|
|
26238
|
+
} catch (error) {
|
|
26239
|
+
console.error(`[EXULU-CHANNEL] audit forward of ${event.type} on channel ${deps.channelId} failed`, safeError(error));
|
|
26240
|
+
}
|
|
26241
|
+
};
|
|
26242
|
+
|
|
26243
|
+
// src/exulu/channels/api.ts
|
|
26244
|
+
var GRAPH_HOST = "https://graph.facebook.com";
|
|
26245
|
+
var GRAPH_VERSION = "v25.0";
|
|
26246
|
+
var TEST_TIMEOUT_MS = 1e4;
|
|
26247
|
+
var CODE_ISSUE_LIMIT = 5;
|
|
26248
|
+
var CODE_ISSUE_WINDOW_SECONDS = 600;
|
|
26249
|
+
var TYPE = "whatsapp";
|
|
26250
|
+
var TABLE4 = "agent_channels";
|
|
26251
|
+
var LOG2 = "[EXULU-CHANNEL]";
|
|
26252
|
+
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
26253
|
+
var PHONE_NUMBER_ID_RE = /^\d{1,32}$/;
|
|
26254
|
+
var PUT_KEYS = /* @__PURE__ */ new Set(["enabled", "config", "secrets"]);
|
|
26255
|
+
var SECRET_KEYS = ["accessToken", "appSecret"];
|
|
26256
|
+
var NOT_FOUND = { detail: "Not found." };
|
|
26257
|
+
var EMPTY_CONFIG = {
|
|
26258
|
+
phoneNumberId: "",
|
|
26259
|
+
displayNumber: "",
|
|
26260
|
+
linkTtlDays: 7,
|
|
26261
|
+
sessionIdleHours: 8,
|
|
26262
|
+
locale: "de",
|
|
26263
|
+
texts: {}
|
|
26264
|
+
};
|
|
26265
|
+
var apiChannelView = (row) => {
|
|
26266
|
+
try {
|
|
26267
|
+
return { ...channelView(row), configInvalid: false };
|
|
26268
|
+
} catch (error) {
|
|
26269
|
+
if (!(error instanceof ChannelConfigError)) throw error;
|
|
26270
|
+
return {
|
|
26271
|
+
id: row.id,
|
|
26272
|
+
agent: row.agent,
|
|
26273
|
+
type: row.type,
|
|
26274
|
+
enabled: row.enabled,
|
|
26275
|
+
config: { ...EMPTY_CONFIG, texts: {} },
|
|
26276
|
+
hasSecrets: !!row.secrets,
|
|
26277
|
+
needsCredentials: readSecrets(row) === null,
|
|
26278
|
+
configInvalid: true
|
|
26279
|
+
};
|
|
26280
|
+
}
|
|
26281
|
+
};
|
|
26282
|
+
var tryParseConfig = (raw) => {
|
|
26283
|
+
try {
|
|
26284
|
+
return parseChannelConfig(raw);
|
|
26285
|
+
} catch {
|
|
26286
|
+
return null;
|
|
26287
|
+
}
|
|
26288
|
+
};
|
|
26289
|
+
var isPlainObject4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
26290
|
+
var buildWaUrl = (displayNumber, code) => {
|
|
26291
|
+
const digits = displayNumber.replace(/\D/g, "");
|
|
26292
|
+
return digits ? `https://wa.me/${digits}?text=${encodeURIComponent(code)}` : null;
|
|
26293
|
+
};
|
|
26294
|
+
var loadChannel = async (db2, agentId) => db2(TABLE4).where({ agent: agentId, type: TYPE }).first();
|
|
26295
|
+
var NO_DEDUP = { set: async () => "OK" };
|
|
26296
|
+
var auditFor = (channelId, agentId) => createChannelAuditor({ channelId, agentId, kv: NO_DEDUP });
|
|
26297
|
+
var codeIssueLimitExceeded = async (kv, userId) => {
|
|
26298
|
+
const key = `channel-link:issued:${userId}`;
|
|
26299
|
+
await kv.set(key, "0", { EX: CODE_ISSUE_WINDOW_SECONDS, NX: true });
|
|
26300
|
+
const n = await kv.incr(key);
|
|
26301
|
+
if (await kv.ttl(key) === -1) await kv.expire(key, CODE_ISSUE_WINDOW_SECONDS);
|
|
26302
|
+
return n > CODE_ISSUE_LIMIT;
|
|
26303
|
+
};
|
|
26304
|
+
var disableChannelsForAgent = async (db2, agentId, now = /* @__PURE__ */ new Date()) => {
|
|
26305
|
+
if (!channelsLicensed()) return;
|
|
26306
|
+
await db2(TABLE4).where({ agent: agentId, enabled: true }).update({ enabled: false, updatedAt: now });
|
|
26307
|
+
};
|
|
26308
|
+
var syncChannelsWithGuestAccess = async (db2, agent) => {
|
|
26309
|
+
if (!channelsLicensed() || !agent?.id) return;
|
|
26310
|
+
if (!canEnableChannel(agent).ok) await disableChannelsForAgent(db2, agent.id);
|
|
26311
|
+
};
|
|
26312
|
+
var deleteChannelsForAgent = async (db2, agentId) => {
|
|
26313
|
+
if (!channelsLicensed()) return;
|
|
26314
|
+
const rows = await db2(TABLE4).where({ agent: agentId }).select("id");
|
|
26315
|
+
const ids = rows.map((r) => r.id);
|
|
26316
|
+
if (ids.length > 0) await db2("channel_links").whereIn("channel", ids).del();
|
|
26317
|
+
await db2(TABLE4).where({ agent: agentId }).del();
|
|
26318
|
+
};
|
|
26319
|
+
var touchesGuestFields = (input) => isPlainObject4(input) && ("guest_access" in input || "guest_auth_mode" in input);
|
|
26320
|
+
var afterAgentWrite = async (db2, agent, changedFields) => {
|
|
26321
|
+
if (!touchesGuestFields(changedFields) || !isPlainObject4(agent) || typeof agent.id !== "string") return;
|
|
26322
|
+
if (!channelsLicensed()) return;
|
|
26323
|
+
try {
|
|
26324
|
+
await syncChannelsWithGuestAccess(db2, agent);
|
|
26325
|
+
} catch (error) {
|
|
26326
|
+
console.error(`${LOG2} disabling the channels of agent ${agent.id} failed`, safeError(error));
|
|
26327
|
+
}
|
|
26328
|
+
};
|
|
26329
|
+
var afterAgentDelete = async (db2, agentId) => {
|
|
26330
|
+
if (typeof agentId !== "string" || agentId === "") return;
|
|
26331
|
+
if (!channelsLicensed()) return;
|
|
26332
|
+
try {
|
|
26333
|
+
await deleteChannelsForAgent(db2, agentId);
|
|
26334
|
+
} catch (error) {
|
|
26335
|
+
console.error(`${LOG2} removing the channels of agent ${agentId} failed`, safeError(error));
|
|
26336
|
+
}
|
|
26337
|
+
};
|
|
26338
|
+
var registerChannelApi = (app, deps) => {
|
|
26339
|
+
const now = () => deps.now ? deps.now() : /* @__PURE__ */ new Date();
|
|
26340
|
+
const doFetch = (...args) => (deps.fetch ?? fetch)(...args);
|
|
26341
|
+
const route = (name, fn) => async (req, res) => {
|
|
26342
|
+
res.setHeader("Cache-Control", "no-store");
|
|
26343
|
+
try {
|
|
26344
|
+
await fn(req, res);
|
|
26345
|
+
} catch (error) {
|
|
26346
|
+
console.error(`${LOG2} api ${name} failed`, safeError(error));
|
|
26347
|
+
if (!res.headersSent) res.status(500).json({ detail: "Internal error." });
|
|
26348
|
+
}
|
|
26349
|
+
};
|
|
26350
|
+
const loadAgent = async (id) => {
|
|
26351
|
+
if (!UUID_RE2.test(id)) return void 0;
|
|
26352
|
+
try {
|
|
26353
|
+
return await deps.loadAgent(id) ?? void 0;
|
|
26354
|
+
} catch {
|
|
26355
|
+
return void 0;
|
|
26356
|
+
}
|
|
26357
|
+
};
|
|
26358
|
+
const signedIn = async (req, res) => {
|
|
26359
|
+
const auth = await deps.authenticate(req);
|
|
26360
|
+
if (!auth.user?.id) {
|
|
26361
|
+
res.status(auth.code || 401).json({ detail: auth.message || "Authentication required." });
|
|
26362
|
+
return null;
|
|
26363
|
+
}
|
|
26364
|
+
return auth.user;
|
|
26365
|
+
};
|
|
26366
|
+
const adminAgent = async (req, res) => {
|
|
26367
|
+
const user = await signedIn(req, res);
|
|
26368
|
+
if (!user) return null;
|
|
26369
|
+
const agent = await loadAgent(String(req.params.agentId ?? ""));
|
|
26370
|
+
if (!agent) {
|
|
26371
|
+
res.status(404).json({ detail: "Agent not found." });
|
|
26372
|
+
return null;
|
|
26373
|
+
}
|
|
26374
|
+
const roleAllows = user.super_admin === true || user.role?.agents === "write";
|
|
26375
|
+
if (!roleAllows || !await deps.checkRecordAccess(agent, "write", user)) {
|
|
26376
|
+
res.status(403).json({ detail: "You don't have write access to this agent." });
|
|
26377
|
+
return null;
|
|
26378
|
+
}
|
|
26379
|
+
return { user, agent };
|
|
26380
|
+
};
|
|
26381
|
+
const webhookUrl = (row) => {
|
|
26382
|
+
const base2 = (deps.backendUrl ? deps.backendUrl() : process.env.BACKEND)?.trim().replace(/\/+$/, "");
|
|
26383
|
+
return row && base2 ? `${base2}/webhooks/whatsapp/${encodeURIComponent(row.id)}` : null;
|
|
26384
|
+
};
|
|
26385
|
+
const base = "/agents/:agentId/channels/whatsapp";
|
|
26386
|
+
app.get(
|
|
26387
|
+
base,
|
|
26388
|
+
route("get channel", async (req, res) => {
|
|
26389
|
+
const gate = await adminAgent(req, res);
|
|
26390
|
+
if (!gate) return;
|
|
26391
|
+
const row = await loadChannel(await deps.getDb(), gate.agent.id);
|
|
26392
|
+
res.json({
|
|
26393
|
+
channel: row ? apiChannelView(row) : null,
|
|
26394
|
+
webhookUrl: webhookUrl(row),
|
|
26395
|
+
canEnable: canEnableChannel(gate.agent)
|
|
26396
|
+
});
|
|
26397
|
+
})
|
|
26398
|
+
);
|
|
26399
|
+
app.put(
|
|
26400
|
+
base,
|
|
26401
|
+
route("put channel", async (req, res) => {
|
|
26402
|
+
const gate = await adminAgent(req, res);
|
|
26403
|
+
if (!gate) return;
|
|
26404
|
+
const { agent } = gate;
|
|
26405
|
+
const body = req.body;
|
|
26406
|
+
const bad = (field, detail) => res.status(400).json({ detail, field });
|
|
26407
|
+
if (!isPlainObject4(body)) return void bad("body", "The body must be a JSON object.");
|
|
26408
|
+
for (const key of Object.keys(body)) {
|
|
26409
|
+
if (!PUT_KEYS.has(key)) return void bad(key, `Unknown field "${key}".`);
|
|
26410
|
+
}
|
|
26411
|
+
if (body.enabled !== void 0 && typeof body.enabled !== "boolean") {
|
|
26412
|
+
return void bad("enabled", "enabled must be a boolean.");
|
|
26413
|
+
}
|
|
26414
|
+
let config;
|
|
26415
|
+
if (body.config !== void 0) {
|
|
26416
|
+
try {
|
|
26417
|
+
config = parseChannelConfig(body.config);
|
|
26418
|
+
} catch (error) {
|
|
26419
|
+
if (error instanceof ChannelConfigError) return void bad(error.field, error.message);
|
|
26420
|
+
throw error;
|
|
26421
|
+
}
|
|
26422
|
+
}
|
|
26423
|
+
const incoming = {};
|
|
26424
|
+
if (body.secrets !== void 0) {
|
|
26425
|
+
if (!isPlainObject4(body.secrets)) return void bad("secrets", "secrets must be an object.");
|
|
26426
|
+
for (const key of Object.keys(body.secrets)) {
|
|
26427
|
+
if (!SECRET_KEYS.includes(key)) return void bad("secrets", "Unknown secret field.");
|
|
26428
|
+
}
|
|
26429
|
+
for (const key of SECRET_KEYS) {
|
|
26430
|
+
const value = body.secrets[key];
|
|
26431
|
+
if (value === void 0) continue;
|
|
26432
|
+
if (typeof value !== "string") return void bad(`secrets.${key}`, `${key} must be a string.`);
|
|
26433
|
+
if (value !== "") incoming[key] = value;
|
|
26434
|
+
}
|
|
26435
|
+
}
|
|
26436
|
+
const db2 = await deps.getDb();
|
|
26437
|
+
const existing = await loadChannel(db2, agent.id);
|
|
26438
|
+
let sealed;
|
|
26439
|
+
if (incoming.accessToken !== void 0 || incoming.appSecret !== void 0) {
|
|
26440
|
+
const stored = existing ? readSecrets(existing) : null;
|
|
26441
|
+
const merged = {
|
|
26442
|
+
accessToken: incoming.accessToken ?? stored?.accessToken ?? "",
|
|
26443
|
+
appSecret: incoming.appSecret ?? stored?.appSecret ?? ""
|
|
26444
|
+
};
|
|
26445
|
+
for (const key of SECRET_KEYS) {
|
|
26446
|
+
if (merged[key] === "") return void bad(`secrets.${key}`, `${key} is required.`);
|
|
26447
|
+
}
|
|
26448
|
+
sealed = sealSecrets(merged);
|
|
26449
|
+
}
|
|
26450
|
+
if (body.enabled === true) {
|
|
26451
|
+
const refuse = (reason, detail) => res.status(409).json({ detail, reason });
|
|
26452
|
+
if (!deps.entitled()) return void refuse("not_entitled", "The channels and queues entitlements are required.");
|
|
26453
|
+
const can = canEnableChannel(agent);
|
|
26454
|
+
if (!can.ok) {
|
|
26455
|
+
return void refuse(
|
|
26456
|
+
can.reason,
|
|
26457
|
+
can.reason === "guest_access_off" ? "Guest access must be on for this agent." : 'Guest access must be in "regular" (sign-in) mode.'
|
|
26458
|
+
);
|
|
26459
|
+
}
|
|
26460
|
+
const hasSecrets = sealed !== void 0 || (existing ? readSecrets(existing) !== null : false);
|
|
26461
|
+
if (!hasSecrets) return void refuse("needs_credentials", "An access token and an app secret are required.");
|
|
26462
|
+
const effective = config ?? (existing ? tryParseConfig(existing.config) : null);
|
|
26463
|
+
if (!effective || effective.phoneNumberId.trim() === "") {
|
|
26464
|
+
return void refuse("invalid_config", "A valid configuration with a phone number ID is required.");
|
|
26465
|
+
}
|
|
26466
|
+
try {
|
|
26467
|
+
linkPageUrl(agent.id);
|
|
26468
|
+
} catch {
|
|
26469
|
+
return void refuse(
|
|
26470
|
+
"link_url_not_configured",
|
|
26471
|
+
"Set FRONTEND (or CHANNEL_LINK_BASE_URL, where customers use a web address of their own) on the server; NEXTAUTH_URL is not set here either."
|
|
26472
|
+
);
|
|
26473
|
+
}
|
|
26474
|
+
}
|
|
26475
|
+
const changes = { updatedAt: now() };
|
|
26476
|
+
if (body.enabled !== void 0) changes.enabled = body.enabled;
|
|
26477
|
+
if (config) changes.config = JSON.stringify(config);
|
|
26478
|
+
if (sealed) changes.secrets = sealed;
|
|
26479
|
+
const verifyToken = (0, import_crypto7.randomBytes)(24).toString("base64url");
|
|
26480
|
+
const [row] = await db2(TABLE4).insert({
|
|
26481
|
+
agent: agent.id,
|
|
26482
|
+
type: TYPE,
|
|
26483
|
+
enabled: false,
|
|
26484
|
+
config: null,
|
|
26485
|
+
secrets: null,
|
|
26486
|
+
...changes,
|
|
26487
|
+
verify_token: verifyToken
|
|
26488
|
+
}).onConflict(["agent", "type"]).merge(changes).returning("*");
|
|
26489
|
+
const created = row.verify_token === verifyToken;
|
|
26490
|
+
res.json(created ? { channel: apiChannelView(row), verifyToken } : { channel: apiChannelView(row) });
|
|
26491
|
+
})
|
|
26492
|
+
);
|
|
26493
|
+
app.post(
|
|
26494
|
+
`${base}/test`,
|
|
26495
|
+
route("test channel", async (req, res) => {
|
|
26496
|
+
const gate = await adminAgent(req, res);
|
|
26497
|
+
if (!gate) return;
|
|
26498
|
+
const row = await loadChannel(await deps.getDb(), gate.agent.id);
|
|
26499
|
+
if (!row) return void res.status(404).json({ detail: "Channel not found." });
|
|
26500
|
+
const result = (ok, detail) => res.json({ ok, detail });
|
|
26501
|
+
const secrets = readSecrets(row);
|
|
26502
|
+
if (!secrets) return void result(false, "No access token and app secret are stored.");
|
|
26503
|
+
const config = tryParseConfig(row.config);
|
|
26504
|
+
if (!config) return void result(false, "The channel configuration is incomplete.");
|
|
26505
|
+
if (!PHONE_NUMBER_ID_RE.test(config.phoneNumberId)) {
|
|
26506
|
+
return void result(false, "The phone number ID must contain digits only.");
|
|
26507
|
+
}
|
|
26508
|
+
const url = `${GRAPH_HOST}/${GRAPH_VERSION}/${config.phoneNumberId}?fields=display_phone_number,verified_name`;
|
|
26509
|
+
let response;
|
|
26510
|
+
try {
|
|
26511
|
+
response = await doFetch(url, {
|
|
26512
|
+
method: "GET",
|
|
26513
|
+
headers: { Authorization: `Bearer ${secrets.accessToken}`, Accept: "application/json" },
|
|
26514
|
+
redirect: "manual",
|
|
26515
|
+
signal: AbortSignal.timeout(TEST_TIMEOUT_MS)
|
|
26516
|
+
});
|
|
26517
|
+
} catch (error) {
|
|
26518
|
+
console.warn(`${LOG2} connection test on channel ${row.id} failed`, safeError(error));
|
|
26519
|
+
const name = error?.name;
|
|
26520
|
+
return void result(
|
|
26521
|
+
false,
|
|
26522
|
+
name === "TimeoutError" || name === "AbortError" ? `Meta did not answer within ${TEST_TIMEOUT_MS / 1e3} seconds.` : "Meta could not be reached."
|
|
26523
|
+
);
|
|
26524
|
+
}
|
|
26525
|
+
if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
|
|
26526
|
+
return void result(false, "Meta answered with an unexpected redirect.");
|
|
26527
|
+
}
|
|
26528
|
+
let json = null;
|
|
26529
|
+
try {
|
|
26530
|
+
json = await response.json();
|
|
26531
|
+
} catch {
|
|
26532
|
+
json = null;
|
|
26533
|
+
}
|
|
26534
|
+
const clean = (v) => {
|
|
26535
|
+
if (typeof v !== "string" || v.trim() === "") return null;
|
|
26536
|
+
if (v.includes(secrets.accessToken) || v.includes(secrets.appSecret)) return null;
|
|
26537
|
+
return v.slice(0, 300);
|
|
26538
|
+
};
|
|
26539
|
+
if (response.ok) {
|
|
26540
|
+
const name = clean(json?.verified_name);
|
|
26541
|
+
const number = clean(json?.display_phone_number);
|
|
26542
|
+
if (!name || !number) return void result(false, "Meta answered, but not with the expected phone number details.");
|
|
26543
|
+
return void result(true, `Connected: ${name}, ${number}`);
|
|
26544
|
+
}
|
|
26545
|
+
result(false, clean(json?.error?.message) ?? `Meta answered with HTTP ${response.status}.`);
|
|
26546
|
+
})
|
|
26547
|
+
);
|
|
26548
|
+
app.get(
|
|
26549
|
+
`${base}/links`,
|
|
26550
|
+
route("list links", async (req, res) => {
|
|
26551
|
+
const gate = await adminAgent(req, res);
|
|
26552
|
+
if (!gate) return;
|
|
26553
|
+
const db2 = await deps.getDb();
|
|
26554
|
+
const row = await loadChannel(db2, gate.agent.id);
|
|
26555
|
+
if (!row) return void res.json({ links: [] });
|
|
26556
|
+
const at = now();
|
|
26557
|
+
const links = await createLinkStore(db2).listForChannel(row.id);
|
|
26558
|
+
res.json({
|
|
26559
|
+
links: links.map((l) => ({
|
|
26560
|
+
id: l.id,
|
|
26561
|
+
identityMasked: maskIdentity(l.identity),
|
|
26562
|
+
userId: l.user,
|
|
26563
|
+
linked_at: l.linked_at,
|
|
26564
|
+
expires_at: l.expires_at,
|
|
26565
|
+
last_seen_at: l.last_seen_at,
|
|
26566
|
+
state: linkState(l, at).state
|
|
26567
|
+
}))
|
|
26568
|
+
});
|
|
26569
|
+
})
|
|
26570
|
+
);
|
|
26571
|
+
app.delete(
|
|
26572
|
+
`${base}/links/:linkId`,
|
|
26573
|
+
route("revoke link", async (req, res) => {
|
|
26574
|
+
const gate = await adminAgent(req, res);
|
|
26575
|
+
if (!gate) return;
|
|
26576
|
+
const notFound = () => res.status(404).json({ detail: "Link not found." });
|
|
26577
|
+
const linkId = String(req.params.linkId ?? "");
|
|
26578
|
+
if (!UUID_RE2.test(linkId)) return void notFound();
|
|
26579
|
+
const db2 = await deps.getDb();
|
|
26580
|
+
const row = await loadChannel(db2, gate.agent.id);
|
|
26581
|
+
if (!row) return void notFound();
|
|
26582
|
+
const link = await db2("channel_links").where({ id: linkId, channel: row.id }).first();
|
|
26583
|
+
if (!link) return void notFound();
|
|
26584
|
+
if (!link.revoked_at) {
|
|
26585
|
+
await createLinkStore(db2).revoke(link.id, now());
|
|
26586
|
+
await auditFor(row.id, row.agent)({ type: "revoked", identity: link.identity, userId: link.user });
|
|
26587
|
+
}
|
|
26588
|
+
res.status(204).end();
|
|
26589
|
+
})
|
|
26590
|
+
);
|
|
26591
|
+
const customerChannel = async (req, opts) => {
|
|
26592
|
+
const agent = await loadAgent(String(req.params.id ?? ""));
|
|
26593
|
+
if (!agent) return null;
|
|
26594
|
+
const db2 = await deps.getDb();
|
|
26595
|
+
const row = await loadChannel(db2, agent.id);
|
|
26596
|
+
if (!row) return null;
|
|
26597
|
+
if (opts.requireEnabled && !row.enabled) return null;
|
|
26598
|
+
return { db: db2, agent, row };
|
|
26599
|
+
};
|
|
26600
|
+
app.post(
|
|
26601
|
+
"/public-agents/:id/channels/whatsapp/link-code",
|
|
26602
|
+
route("issue link code", async (req, res) => {
|
|
26603
|
+
const user = await signedIn(req, res);
|
|
26604
|
+
if (!user) return;
|
|
26605
|
+
if (!deps.entitled()) return void res.status(404).json(NOT_FOUND);
|
|
26606
|
+
const found = await customerChannel(req, { requireEnabled: true });
|
|
26607
|
+
const config = found ? tryParseConfig(found.row.config) : null;
|
|
26608
|
+
if (!found || !config || !canEnableChannel(found.agent).ok) return void res.status(404).json(NOT_FOUND);
|
|
26609
|
+
const { db: db2, agent, row } = found;
|
|
26610
|
+
const allowed = await channelAccessAllowed({
|
|
26611
|
+
db: db2,
|
|
26612
|
+
loadAgent: (id) => loadAgent(id),
|
|
26613
|
+
agentId: agent.id,
|
|
26614
|
+
channelId: row.id,
|
|
26615
|
+
userId: user.id
|
|
26616
|
+
});
|
|
26617
|
+
if (!allowed) return void res.status(403).json({ detail: "You don't have access to this agent." });
|
|
26618
|
+
let store = null;
|
|
26619
|
+
try {
|
|
26620
|
+
store = await deps.getStore();
|
|
26621
|
+
} catch (error) {
|
|
26622
|
+
console.error(`${LOG2} link code store unavailable on channel ${row.id}`, safeError(error));
|
|
26623
|
+
}
|
|
26624
|
+
const unavailable = () => res.status(503).json({ detail: "Linking is temporarily unavailable." });
|
|
26625
|
+
if (!store) return void unavailable();
|
|
26626
|
+
let code;
|
|
26627
|
+
try {
|
|
26628
|
+
if (await codeIssueLimitExceeded(store, user.id)) {
|
|
26629
|
+
return void res.status(429).json({ detail: "Too many requests. Try again later." });
|
|
26630
|
+
}
|
|
26631
|
+
code = await issueCode(store, { channelId: row.id, userId: user.id });
|
|
26632
|
+
} catch (error) {
|
|
26633
|
+
console.error(`${LOG2} issuing a link code on channel ${row.id} failed`, safeError(error));
|
|
26634
|
+
return void unavailable();
|
|
26635
|
+
}
|
|
26636
|
+
const links = await createLinkStore(db2).listForUser(row.id, user.id);
|
|
26637
|
+
res.json({
|
|
26638
|
+
code,
|
|
26639
|
+
expiresInSeconds: CODE_TTL_SECONDS,
|
|
26640
|
+
waUrl: buildWaUrl(config.displayNumber, code),
|
|
26641
|
+
// the caller's own links on this channel; unlinked (revoked) ones are gone for them
|
|
26642
|
+
links: links.filter((l) => !l.revoked_at).map((l) => ({ id: l.id, identityMasked: maskIdentity(l.identity), expires_at: l.expires_at }))
|
|
26643
|
+
});
|
|
26644
|
+
})
|
|
26645
|
+
);
|
|
26646
|
+
app.delete(
|
|
26647
|
+
"/public-agents/:id/channels/whatsapp/links/:linkId",
|
|
26648
|
+
route("unlink", async (req, res) => {
|
|
26649
|
+
const user = await signedIn(req, res);
|
|
26650
|
+
if (!user) return;
|
|
26651
|
+
const linkId = String(req.params.linkId ?? "");
|
|
26652
|
+
if (!UUID_RE2.test(linkId)) return void res.status(404).json(NOT_FOUND);
|
|
26653
|
+
const found = await customerChannel(req, { requireEnabled: false });
|
|
26654
|
+
if (!found) return void res.status(404).json(NOT_FOUND);
|
|
26655
|
+
const { db: db2, row } = found;
|
|
26656
|
+
const link = await db2("channel_links").where({ id: linkId, channel: row.id, user: user.id }).first();
|
|
26657
|
+
if (!link) return void res.status(404).json(NOT_FOUND);
|
|
26658
|
+
if (!link.revoked_at) {
|
|
26659
|
+
await createLinkStore(db2).revoke(link.id, now());
|
|
26660
|
+
await auditFor(row.id, row.agent)({ type: "unlinked", identity: link.identity, userId: link.user });
|
|
26661
|
+
}
|
|
26662
|
+
res.status(204).end();
|
|
26663
|
+
})
|
|
26664
|
+
);
|
|
26665
|
+
};
|
|
26666
|
+
|
|
25647
26667
|
// src/graphql/mutations/should-generate-embeddings.ts
|
|
25648
26668
|
init_cjs_shims();
|
|
25649
26669
|
var shouldGenerateEmbeddings = ({
|
|
@@ -26400,6 +27420,9 @@ function createMutations(table, contexts, tools, config) {
|
|
|
26400
27420
|
insert.onConflict().merge();
|
|
26401
27421
|
}
|
|
26402
27422
|
let results = await insert;
|
|
27423
|
+
if (tableNamePlural === "agents" && args.upsert) {
|
|
27424
|
+
await afterAgentWrite(db2, results[0], args.input);
|
|
27425
|
+
}
|
|
26403
27426
|
if (table.RBAC && rbacData && results[0]) {
|
|
26404
27427
|
await handleRBACUpdate(db2, table.name.singular, results[0].id, rbacData, []);
|
|
26405
27428
|
}
|
|
@@ -26483,6 +27506,9 @@ function createMutations(table, contexts, tools, config) {
|
|
|
26483
27506
|
if (!result?.id) {
|
|
26484
27507
|
throw new Error("Something went wrong with the update, no id returned.");
|
|
26485
27508
|
}
|
|
27509
|
+
if (tableNamePlural === "agents") {
|
|
27510
|
+
await afterAgentWrite(db2, result, args.input);
|
|
27511
|
+
}
|
|
26486
27512
|
if (table.RBAC && rbacData && result.id) {
|
|
26487
27513
|
const existingRbacRecords = await db2.from("rbac").where({
|
|
26488
27514
|
entity: table.name.singular,
|
|
@@ -26567,6 +27593,9 @@ function createMutations(table, contexts, tools, config) {
|
|
|
26567
27593
|
const requestedFields = getRequestedFields(info);
|
|
26568
27594
|
const columns = await db2(tableNamePlural).columnInfo();
|
|
26569
27595
|
const result = await db2.from(tableNamePlural).select(Object.keys(columns)).where({ id }).first();
|
|
27596
|
+
if (tableNamePlural === "agents") {
|
|
27597
|
+
await afterAgentWrite(db2, result, args.input);
|
|
27598
|
+
}
|
|
26570
27599
|
const { job } = await postprocessUpdate({
|
|
26571
27600
|
table,
|
|
26572
27601
|
requestedFields,
|
|
@@ -26626,6 +27655,12 @@ function createMutations(table, contexts, tools, config) {
|
|
|
26626
27655
|
tools,
|
|
26627
27656
|
result
|
|
26628
27657
|
});
|
|
27658
|
+
if (tableNamePlural === "agents") {
|
|
27659
|
+
await afterAgentDelete(db2, id);
|
|
27660
|
+
}
|
|
27661
|
+
if (tableNamePlural === "users") {
|
|
27662
|
+
await afterUserDeleteBestEffort(db2, id);
|
|
27663
|
+
}
|
|
26629
27664
|
return finalizeRequestedFields({
|
|
26630
27665
|
args,
|
|
26631
27666
|
table,
|
|
@@ -26666,6 +27701,12 @@ function createMutations(table, contexts, tools, config) {
|
|
|
26666
27701
|
tools,
|
|
26667
27702
|
result
|
|
26668
27703
|
});
|
|
27704
|
+
if (tableNamePlural === "agents") {
|
|
27705
|
+
await afterAgentDelete(db2, result.id);
|
|
27706
|
+
}
|
|
27707
|
+
if (tableNamePlural === "users") {
|
|
27708
|
+
await afterUserDeleteBestEffort(db2, result.id);
|
|
27709
|
+
}
|
|
26669
27710
|
return finalizeRequestedFields({
|
|
26670
27711
|
args,
|
|
26671
27712
|
table,
|
|
@@ -27234,12 +28275,12 @@ var bullmq = {
|
|
|
27234
28275
|
if (!data.inputs) {
|
|
27235
28276
|
throw new Error(`Missing property "inputs" in data for job ${id}.`);
|
|
27236
28277
|
}
|
|
27237
|
-
if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source" && data.type !== "email_intake" && data.type !== "import") {
|
|
28278
|
+
if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source" && data.type !== "email_intake" && data.type !== "channel_message" && data.type !== "import") {
|
|
27238
28279
|
throw new Error(
|
|
27239
|
-
`Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function", "source", "email_intake" or "import".`
|
|
28280
|
+
`Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function", "source", "email_intake", "channel_message" or "import".`
|
|
27240
28281
|
);
|
|
27241
28282
|
}
|
|
27242
|
-
if (data.type !== "email_intake" && data.type !== "import" && !data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
|
|
28283
|
+
if (data.type !== "email_intake" && data.type !== "channel_message" && data.type !== "import" && !data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
|
|
27243
28284
|
throw new Error(
|
|
27244
28285
|
`Either a workflow, embedder, processor, eval_run, eval_functions or source must be set for job ${id}.`
|
|
27245
28286
|
);
|
|
@@ -28198,12 +29239,12 @@ var generateSync = async ({
|
|
|
28198
29239
|
);
|
|
28199
29240
|
const turnBudget = resolveTurnStepBudget(maxStepCount, agent);
|
|
28200
29241
|
const includesContextSearchTool = currentTools?.some(
|
|
28201
|
-
(
|
|
29242
|
+
(tool5) => tool5.name.toLowerCase().includes("context_search") || tool5.id.includes("context_search") || tool5.type === "context"
|
|
28202
29243
|
);
|
|
28203
29244
|
const includesWebSearchTool = currentTools?.some(
|
|
28204
|
-
(
|
|
29245
|
+
(tool5) => tool5.name.toLowerCase().includes("web_search") || tool5.id.includes("web_search") || tool5.type === "web_search"
|
|
28205
29246
|
);
|
|
28206
|
-
console.log("[EXULU] Current tools: " + currentTools?.map((
|
|
29247
|
+
console.log("[EXULU] Current tools: " + currentTools?.map((tool5) => tool5.name).join("\n"));
|
|
28207
29248
|
console.log("[EXULU] Includes context search tool: " + includesContextSearchTool);
|
|
28208
29249
|
if (includesContextSearchTool && shouldShowSourcesToUser(toolConfigs, user)) {
|
|
28209
29250
|
system += `
|
|
@@ -28657,12 +29698,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
28657
29698
|
);
|
|
28658
29699
|
console.log("[EXULU] Converted tools", Object.keys(tools));
|
|
28659
29700
|
const includesContextSearchTool = currentTools?.some(
|
|
28660
|
-
(
|
|
29701
|
+
(tool5) => tool5.name.toLowerCase().includes("context_search") || tool5.id.includes("context_search") || tool5.type === "context"
|
|
28661
29702
|
);
|
|
28662
29703
|
const includesWebSearchTool = currentTools?.some(
|
|
28663
|
-
(
|
|
29704
|
+
(tool5) => tool5.name.toLowerCase().includes("web_search") || tool5.id.includes("web_search") || tool5.type === "web_search"
|
|
28664
29705
|
);
|
|
28665
|
-
console.log("[EXULU] Current tools: " + currentTools?.map((
|
|
29706
|
+
console.log("[EXULU] Current tools: " + currentTools?.map((tool5) => tool5.name).join("\n"));
|
|
28666
29707
|
console.log("[EXULU] Includes context search tool: " + includesContextSearchTool);
|
|
28667
29708
|
console.log("[EXULU] Includes web search tool: " + includesWebSearchTool);
|
|
28668
29709
|
if (includesContextSearchTool && shouldShowSourcesToUser(toolConfigs, user)) {
|
|
@@ -28922,7 +29963,7 @@ var getEnabledTools = async (agent, allExuluTools, allContexts, disabledTools =
|
|
|
28922
29963
|
}
|
|
28923
29964
|
console.log("[EXULU] available tools", enabledTools?.length);
|
|
28924
29965
|
console.log("[EXULU] disabled tools", disabledTools?.length);
|
|
28925
|
-
enabledTools = enabledTools.filter((
|
|
29966
|
+
enabledTools = enabledTools.filter((tool5) => !disabledTools.includes(tool5.id));
|
|
28926
29967
|
return enabledTools;
|
|
28927
29968
|
};
|
|
28928
29969
|
|
|
@@ -28973,9 +30014,9 @@ var resolveContextWindow = async ({
|
|
|
28973
30014
|
// ee/workers.ts
|
|
28974
30015
|
init_client();
|
|
28975
30016
|
init_prune_job_results();
|
|
28976
|
-
var
|
|
30017
|
+
var import_api2 = require("@opentelemetry/api");
|
|
28977
30018
|
var import_uuid3 = require("uuid");
|
|
28978
|
-
var
|
|
30019
|
+
var import_ai9 = require("ai");
|
|
28979
30020
|
var import_crypto_js6 = require("crypto-js");
|
|
28980
30021
|
init_statistics();
|
|
28981
30022
|
init_jobs();
|
|
@@ -29526,6 +30567,927 @@ async function handleEmailIntake(payload, deps) {
|
|
|
29526
30567
|
return fireRun({ db: db2, deps, trigger, email, s3Key: payload.s3Key, jobResultId });
|
|
29527
30568
|
}
|
|
29528
30569
|
|
|
30570
|
+
// src/exulu/channels/worker.ts
|
|
30571
|
+
init_cjs_shims();
|
|
30572
|
+
init_client();
|
|
30573
|
+
init_singleton();
|
|
30574
|
+
|
|
30575
|
+
// src/exulu/channels/act.ts
|
|
30576
|
+
init_cjs_shims();
|
|
30577
|
+
var import_crypto8 = require("crypto");
|
|
30578
|
+
|
|
30579
|
+
// src/exulu/channels/texts.ts
|
|
30580
|
+
init_cjs_shims();
|
|
30581
|
+
var DEFAULTS2 = {
|
|
30582
|
+
de: {
|
|
30583
|
+
linkRequired: "Hallo! Bevor ich dir antworten kann, musst du deine Nummer verkn\xFCpfen. \xD6ffne diesen Link, melde dich an und sende mir den Code, den du dort bekommst:\n{linkUrl}",
|
|
30584
|
+
linked: "Deine Nummer ist verkn\xFCpft, und zwar bis zum {expiresAt}. Du kannst mir jetzt deine Frage stellen.",
|
|
30585
|
+
codeInvalid: "Dieser Code ist falsch oder abgelaufen. \xD6ffne den Link erneut, um einen neuen Code zu bekommen, und sende ihn mir.",
|
|
30586
|
+
textOnly: "Ich kann im Moment nur Textnachrichten verarbeiten. Bitte schreib mir deine Frage als Text.",
|
|
30587
|
+
rateLimited: "Du hast gerade sehr viele Anfragen gestellt. Bitte versuche es sp\xE4ter noch einmal.",
|
|
30588
|
+
stillWorking: "Ich bin noch mit deiner vorherigen Frage besch\xE4ftigt. Bitte warte einen Moment, bis ich geantwortet habe.",
|
|
30589
|
+
runFailed: "Leider ist etwas schiefgelaufen. Bitte versuche es noch einmal.",
|
|
30590
|
+
newSession: "Alles klar, wir starten ein neues Gespr\xE4ch. Was m\xF6chtest du wissen?",
|
|
30591
|
+
unlinked: "Deine Nummer wurde getrennt. Wenn du mir wieder schreibst, bekommst du einen neuen Link zum Verkn\xFCpfen."
|
|
30592
|
+
},
|
|
30593
|
+
en: {
|
|
30594
|
+
linkRequired: "Hello! Before I can answer, you need to link your number. Open this link, sign in and send me the code you get there:\n{linkUrl}",
|
|
30595
|
+
linked: "Your number is linked until {expiresAt}. You can ask your question now.",
|
|
30596
|
+
codeInvalid: "That code is wrong or has expired. Open the link again to get a new code and send it to me.",
|
|
30597
|
+
textOnly: "I can only handle text messages at the moment. Please write your question as text.",
|
|
30598
|
+
rateLimited: "You have sent a lot of requests just now. Please try again later.",
|
|
30599
|
+
stillWorking: "I am still answering your previous question. Please wait a moment until I have replied.",
|
|
30600
|
+
runFailed: "Sorry, something went wrong. Please try again.",
|
|
30601
|
+
newSession: "Okay, we are starting a new conversation. What would you like to know?",
|
|
30602
|
+
unlinked: "Your number has been disconnected. When you write to me again, you will get a new link to connect it."
|
|
30603
|
+
}
|
|
30604
|
+
};
|
|
30605
|
+
var pad2 = (n) => String(n).padStart(2, "0");
|
|
30606
|
+
var formatDate = (date, locale) => {
|
|
30607
|
+
const d = pad2(date.getUTCDate());
|
|
30608
|
+
const m = pad2(date.getUTCMonth() + 1);
|
|
30609
|
+
const y = String(date.getUTCFullYear());
|
|
30610
|
+
return locale === "de" ? `${d}.${m}.${y}` : `${y}-${m}-${d}`;
|
|
30611
|
+
};
|
|
30612
|
+
var replyText = (key, config, vars = {}) => {
|
|
30613
|
+
const override = config.texts?.[key];
|
|
30614
|
+
const template = override ? override : DEFAULTS2[config.locale][key];
|
|
30615
|
+
const values = {
|
|
30616
|
+
linkUrl: vars.linkUrl,
|
|
30617
|
+
expiresAt: vars.expiresAt ? formatDate(vars.expiresAt, config.locale) : void 0
|
|
30618
|
+
};
|
|
30619
|
+
return template.replace(/\{(\w+)\}/g, (whole, name) => values[name] ?? whole);
|
|
30620
|
+
};
|
|
30621
|
+
|
|
30622
|
+
// src/exulu/channels/act.ts
|
|
30623
|
+
var CHANNEL_JOB_NAME = "channel_message";
|
|
30624
|
+
var CHANNEL_JOB_TIMEOUT_SECONDS = 600;
|
|
30625
|
+
var SEEN_TTL_SECONDS = 24 * 60 * 60;
|
|
30626
|
+
var ANSWERED_TTL_SECONDS = 24 * 60 * 60;
|
|
30627
|
+
var hashMessageId = (messageId) => (0, import_crypto8.createHash)("sha256").update(messageId).digest("hex");
|
|
30628
|
+
var seenKey = (channelId, messageId) => `channel-seen:${channelId}:${hashMessageId(messageId)}`;
|
|
30629
|
+
var answeredKey = (channelId, messageId) => `channel-answered:${channelId}:${hashMessageId(messageId)}`;
|
|
30630
|
+
var channelJobOptions = (messageId) => ({
|
|
30631
|
+
jobId: `wa:${hashMessageId(messageId).slice(0, 32)}`,
|
|
30632
|
+
attempts: 1,
|
|
30633
|
+
removeOnComplete: true,
|
|
30634
|
+
removeOnFail: true
|
|
30635
|
+
});
|
|
30636
|
+
var enqueueChannelMessage = async (queue, job) => {
|
|
30637
|
+
await queue.add(
|
|
30638
|
+
CHANNEL_JOB_NAME,
|
|
30639
|
+
{
|
|
30640
|
+
label: "WhatsApp message",
|
|
30641
|
+
type: CHANNEL_JOB_NAME,
|
|
30642
|
+
trigger: "api",
|
|
30643
|
+
timeoutInSeconds: CHANNEL_JOB_TIMEOUT_SECONDS,
|
|
30644
|
+
inputs: job
|
|
30645
|
+
},
|
|
30646
|
+
channelJobOptions(job.messageId)
|
|
30647
|
+
);
|
|
30648
|
+
};
|
|
30649
|
+
var actOnDecision = async (msg, decision, deps) => {
|
|
30650
|
+
if (decision.kind === "silent") return;
|
|
30651
|
+
if (decision.kind === "reply") {
|
|
30652
|
+
await deps.transport.post(msg.threadId, replyText(decision.key, deps.config, decision.vars));
|
|
30653
|
+
return;
|
|
30654
|
+
}
|
|
30655
|
+
const seen = seenKey(msg.channelId, msg.messageId);
|
|
30656
|
+
if (await deps.store.set(seen, "1", { EX: SEEN_TTL_SECONDS, NX: true }) === null) {
|
|
30657
|
+
return;
|
|
30658
|
+
}
|
|
30659
|
+
try {
|
|
30660
|
+
await deps.enqueue({
|
|
30661
|
+
channelId: msg.channelId,
|
|
30662
|
+
threadId: msg.threadId,
|
|
30663
|
+
identity: msg.identity,
|
|
30664
|
+
userId: decision.userId,
|
|
30665
|
+
messageId: msg.messageId,
|
|
30666
|
+
text: msg.text,
|
|
30667
|
+
newSession: decision.newSession
|
|
30668
|
+
});
|
|
30669
|
+
} catch (error) {
|
|
30670
|
+
console.error(`[EXULU-CHANNEL] enqueue failed on channel ${msg.channelId}`, safeError(error));
|
|
30671
|
+
await deps.store.del(seen).catch((e) => console.error(`[EXULU-CHANNEL] could not free the seen key on channel ${msg.channelId}`, safeError(e)));
|
|
30672
|
+
await deps.transport.post(msg.threadId, replyText("runFailed", deps.config)).catch((e) => console.error(`[EXULU-CHANNEL] could not post runFailed on channel ${msg.channelId}`, safeError(e)));
|
|
30673
|
+
return;
|
|
30674
|
+
}
|
|
30675
|
+
const cosmetic = async (what, effect) => {
|
|
30676
|
+
try {
|
|
30677
|
+
await effect();
|
|
30678
|
+
} catch (error) {
|
|
30679
|
+
console.warn(`[EXULU-CHANNEL] ${what} failed on channel ${msg.channelId}`, safeError(error));
|
|
30680
|
+
}
|
|
30681
|
+
};
|
|
30682
|
+
await cosmetic("mark read", () => deps.transport.markRead(msg.threadId, msg.messageId));
|
|
30683
|
+
await cosmetic("typing indicator", () => deps.transport.typing(msg.threadId));
|
|
30684
|
+
};
|
|
30685
|
+
|
|
30686
|
+
// src/exulu/channels/agent-turn.ts
|
|
30687
|
+
init_cjs_shims();
|
|
30688
|
+
var import_ai8 = require("ai");
|
|
30689
|
+
init_resolve_model();
|
|
30690
|
+
init_public_surface();
|
|
30691
|
+
|
|
30692
|
+
// src/exulu/channels/plain-text.ts
|
|
30693
|
+
init_cjs_shims();
|
|
30694
|
+
var MARK = "\0";
|
|
30695
|
+
var CITATION_KEYS = ["item_name", "item_id", "context", "chunk_id", "chunk_index", "url", "title", "snippet"];
|
|
30696
|
+
var hasKey = (inner, key) => new RegExp(`(?:^|[\\s,])${key}\\s*:`).test(inner);
|
|
30697
|
+
var isCitation = (inner) => {
|
|
30698
|
+
const first = /^\s*([a-z_]+)\s*:/i.exec(inner);
|
|
30699
|
+
if (!first?.[1] || !CITATION_KEYS.includes(first[1].toLowerCase())) return false;
|
|
30700
|
+
if (hasKey(inner, "item_name") && (hasKey(inner, "item_id") || hasKey(inner, "context") || hasKey(inner, "chunk_id"))) {
|
|
30701
|
+
return true;
|
|
30702
|
+
}
|
|
30703
|
+
return hasKey(inner, "url") && hasKey(inner, "title") && hasKey(inner, "snippet");
|
|
30704
|
+
};
|
|
30705
|
+
var OPENS_QUOTE = /(?:^|[{,])\s*[a-z_]+\s*:\s*$/i;
|
|
30706
|
+
var CLOSES_QUOTE = /^[ \t]*(?:[,}]|\n|$)/;
|
|
30707
|
+
var closingBrace = (text, start) => {
|
|
30708
|
+
let depth = 0;
|
|
30709
|
+
let quoted = false;
|
|
30710
|
+
for (let i = start; i < text.length; i++) {
|
|
30711
|
+
const c = text[i];
|
|
30712
|
+
if (c === "\n") return -1;
|
|
30713
|
+
if (quoted) {
|
|
30714
|
+
if (c === '"' && CLOSES_QUOTE.test(text.slice(i + 1, i + 33))) quoted = false;
|
|
30715
|
+
continue;
|
|
30716
|
+
}
|
|
30717
|
+
if (c === '"' && OPENS_QUOTE.test(text.slice(start, i))) quoted = true;
|
|
30718
|
+
else if (c === "{") depth++;
|
|
30719
|
+
else if (c === "}" && --depth === 0) return i;
|
|
30720
|
+
}
|
|
30721
|
+
return -1;
|
|
30722
|
+
};
|
|
30723
|
+
var stripCitations = (text) => {
|
|
30724
|
+
let out = "";
|
|
30725
|
+
let found = false;
|
|
30726
|
+
for (let i = 0; i < text.length; ) {
|
|
30727
|
+
if (text[i] === "{") {
|
|
30728
|
+
const end = closingBrace(text, i);
|
|
30729
|
+
if (end !== -1 && isCitation(text.slice(i + 1, end))) {
|
|
30730
|
+
out += MARK;
|
|
30731
|
+
found = true;
|
|
30732
|
+
i = end + 1;
|
|
30733
|
+
continue;
|
|
30734
|
+
}
|
|
30735
|
+
}
|
|
30736
|
+
out += text[i];
|
|
30737
|
+
i++;
|
|
30738
|
+
}
|
|
30739
|
+
if (!found) return text;
|
|
30740
|
+
if (text.includes(MARK)) return out.split(MARK).join("").trim();
|
|
30741
|
+
return out.replace(/[ \t]*\u0000(?:[ \t]*\u0000)*/g, MARK).replace(/[ \t]*(?:\(\s*\u0000\s*\)|\[\s*\u0000\s*\])/g, MARK).replace(/\u0000(?=[.,;:!?)\]])/g, "").replace(/\u0000[ \t]*(?=\n|$)/g, "").replace(/(^|\n)\u0000[ \t]*/g, "$1").replace(/\u0000(?=\S)/g, " ").replace(/\u0000/g, "").replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "").trimEnd();
|
|
30742
|
+
};
|
|
30743
|
+
|
|
30744
|
+
// src/exulu/channels/agent-turn.ts
|
|
30745
|
+
var GUEST_TURN_REQUEST = { headers: { [PUBLIC_SURFACE_HEADER]: "1" } };
|
|
30746
|
+
var newMessageId = (0, import_ai8.createIdGenerator)({ prefix: "msg_", size: 16 });
|
|
30747
|
+
var loadTurnUser = async (db2, userId) => {
|
|
30748
|
+
const user = await db2("users").where({ id: userId }).first();
|
|
30749
|
+
if (!user) return void 0;
|
|
30750
|
+
if (user.role) {
|
|
30751
|
+
const role = await db2("roles").where({ id: user.role }).first();
|
|
30752
|
+
if (role) user.role = role;
|
|
30753
|
+
}
|
|
30754
|
+
if (user.team) {
|
|
30755
|
+
const team = await db2("teams").where({ id: user.team }).first();
|
|
30756
|
+
if (team) user.team = team;
|
|
30757
|
+
}
|
|
30758
|
+
if (user.project) {
|
|
30759
|
+
const project = await db2("projects").where({ id: user.project }).first();
|
|
30760
|
+
if (project) user.project = project;
|
|
30761
|
+
}
|
|
30762
|
+
return user;
|
|
30763
|
+
};
|
|
30764
|
+
var runChannelAgentTurn = async (p, ctx) => {
|
|
30765
|
+
const db2 = await ctx.getDb();
|
|
30766
|
+
const agent = await ctx.loadAgent(p.agentId);
|
|
30767
|
+
if (!agent) throw new Error(`Agent ${p.agentId} not found.`);
|
|
30768
|
+
const user = await loadTurnUser(db2, p.userId);
|
|
30769
|
+
if (!user) throw new Error(`User ${p.userId} not found.`);
|
|
30770
|
+
const enabledSkills = await getEnabledSkills(agent, []);
|
|
30771
|
+
const enabledTools = await getEnabledTools(agent, ctx.tools, ctx.contexts, [], user);
|
|
30772
|
+
if (!agent.model) throw new Error(`Agent ${agent.name} (${agent.id}) has no model configured.`);
|
|
30773
|
+
const resolved = await resolveModel({ modelId: agent.model, user, agent });
|
|
30774
|
+
const contextWindow = await resolveContextWindow({ modelId: resolved.model.id });
|
|
30775
|
+
const instructions = withGlossary(agent.instructions, agent.tools);
|
|
30776
|
+
const question = { id: newMessageId(), role: "user", parts: [{ type: "text", text: p.text }] };
|
|
30777
|
+
await markSessionGenerating(db2, p.sessionId);
|
|
30778
|
+
let answer;
|
|
30779
|
+
try {
|
|
30780
|
+
answer = await generateSync({
|
|
30781
|
+
contexts: ctx.contexts,
|
|
30782
|
+
agent,
|
|
30783
|
+
user,
|
|
30784
|
+
req: GUEST_TURN_REQUEST,
|
|
30785
|
+
instructions,
|
|
30786
|
+
session: p.sessionId,
|
|
30787
|
+
inputMessages: [question],
|
|
30788
|
+
currentTools: enabledTools,
|
|
30789
|
+
currentSkills: enabledSkills,
|
|
30790
|
+
allExuluTools: ctx.tools,
|
|
30791
|
+
languageModel: resolved.languageModel,
|
|
30792
|
+
exuluConfig: ctx.config,
|
|
30793
|
+
toolConfigs: agent.tools,
|
|
30794
|
+
contextWindow,
|
|
30795
|
+
disabledTools: [],
|
|
30796
|
+
statistics: { label: agent.name, trigger: "agent" }
|
|
30797
|
+
});
|
|
30798
|
+
} catch (error) {
|
|
30799
|
+
await markSessionIdle(db2, p.sessionId);
|
|
30800
|
+
throw error;
|
|
30801
|
+
}
|
|
30802
|
+
const text = typeof answer === "string" ? answer : "";
|
|
30803
|
+
if (text.trim() === "") {
|
|
30804
|
+
await markSessionIdle(db2, p.sessionId);
|
|
30805
|
+
return text;
|
|
30806
|
+
}
|
|
30807
|
+
await saveChat({
|
|
30808
|
+
session: p.sessionId,
|
|
30809
|
+
user: user.id,
|
|
30810
|
+
messages: [question, { id: newMessageId(), role: "assistant", parts: [{ type: "text", text }] }],
|
|
30811
|
+
model: resolved.model.id
|
|
30812
|
+
});
|
|
30813
|
+
await markSessionAnswered(db2, p.sessionId);
|
|
30814
|
+
const plain = stripCitations(text);
|
|
30815
|
+
return plain.trim() === "" ? "" : plain;
|
|
30816
|
+
};
|
|
30817
|
+
|
|
30818
|
+
// src/exulu/channels/chat-instance.ts
|
|
30819
|
+
init_cjs_shims();
|
|
30820
|
+
|
|
30821
|
+
// src/exulu/channels/state-tables.ts
|
|
30822
|
+
init_cjs_shims();
|
|
30823
|
+
var import_pg = require("pg");
|
|
30824
|
+
var CHAT_STATE_KEY_PREFIX = "exulu-channel";
|
|
30825
|
+
var loadStateModule = () => import("@chat-adapter/state-pg");
|
|
30826
|
+
async function ensureChatStateTables(pool3, load2 = loadStateModule) {
|
|
30827
|
+
const { createPostgresState } = await load2();
|
|
30828
|
+
const state = createPostgresState({
|
|
30829
|
+
client: pool3,
|
|
30830
|
+
keyPrefix: CHAT_STATE_KEY_PREFIX,
|
|
30831
|
+
autoCreateSchema: true
|
|
30832
|
+
});
|
|
30833
|
+
try {
|
|
30834
|
+
await state.connect();
|
|
30835
|
+
} finally {
|
|
30836
|
+
await state.disconnect();
|
|
30837
|
+
}
|
|
30838
|
+
}
|
|
30839
|
+
var EXPIRING_TABLES = ["chat_state_locks", "chat_state_cache", "chat_state_lists", "chat_state_queues"];
|
|
30840
|
+
async function purgeExpiredChatState(pool3) {
|
|
30841
|
+
if (!channelsLicensed()) return;
|
|
30842
|
+
try {
|
|
30843
|
+
const present = await pool3.query(
|
|
30844
|
+
`SELECT name FROM unnest($1::text[]) AS t(name) WHERE to_regclass(name) IS NOT NULL`,
|
|
30845
|
+
[[...EXPIRING_TABLES]]
|
|
30846
|
+
);
|
|
30847
|
+
const existing = new Set(present.rows.map((r) => r.name));
|
|
30848
|
+
for (const table of EXPIRING_TABLES) {
|
|
30849
|
+
if (!existing.has(table)) continue;
|
|
30850
|
+
await pool3.query(
|
|
30851
|
+
`DELETE FROM ${table} WHERE key_prefix = $1 AND expires_at IS NOT NULL AND expires_at <= now()`,
|
|
30852
|
+
[CHAT_STATE_KEY_PREFIX]
|
|
30853
|
+
);
|
|
30854
|
+
}
|
|
30855
|
+
} catch (error) {
|
|
30856
|
+
console.error("[EXULU-CHANNEL] purging expired chat state failed", safeError(error));
|
|
30857
|
+
}
|
|
30858
|
+
}
|
|
30859
|
+
var initdbPool = () => new import_pg.Pool({
|
|
30860
|
+
host: process.env.POSTGRES_DB_HOST,
|
|
30861
|
+
port: parseInt(process.env.POSTGRES_DB_PORT || "5432"),
|
|
30862
|
+
user: process.env.POSTGRES_DB_USER,
|
|
30863
|
+
database: process.env.POSTGRES_DB_NAME || "exulu",
|
|
30864
|
+
password: process.env.POSTGRES_DB_PASSWORD,
|
|
30865
|
+
ssl: process.env.POSTGRES_DB_SSL === "true" ? { rejectUnauthorized: false } : false,
|
|
30866
|
+
max: 2
|
|
30867
|
+
});
|
|
30868
|
+
async function initChatStateTables(opts = {}) {
|
|
30869
|
+
let pool3;
|
|
30870
|
+
try {
|
|
30871
|
+
pool3 = (opts.createPool ?? initdbPool)();
|
|
30872
|
+
await ensureChatStateTables(pool3, opts.load ?? loadStateModule);
|
|
30873
|
+
await purgeExpiredChatState(pool3);
|
|
30874
|
+
} catch (error) {
|
|
30875
|
+
console.error(
|
|
30876
|
+
"[EXULU-CHANNEL] chat state tables not created; WhatsApp channels will not work until this succeeds",
|
|
30877
|
+
safeError(error)
|
|
30878
|
+
);
|
|
30879
|
+
} finally {
|
|
30880
|
+
await pool3?.end().catch(() => void 0);
|
|
30881
|
+
}
|
|
30882
|
+
}
|
|
30883
|
+
var CHAT_STATE_PURGE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
30884
|
+
var lastPurgeStartedAt = null;
|
|
30885
|
+
var purgeChatStateThrottled = (pool3, now = Date.now(), purge = purgeExpiredChatState) => {
|
|
30886
|
+
if (lastPurgeStartedAt !== null && now - lastPurgeStartedAt < CHAT_STATE_PURGE_INTERVAL_MS) return false;
|
|
30887
|
+
lastPurgeStartedAt = now;
|
|
30888
|
+
void (async () => purge(pool3))().catch((error) => console.error("[EXULU-CHANNEL] purging expired chat state failed", safeError(error)));
|
|
30889
|
+
return true;
|
|
30890
|
+
};
|
|
30891
|
+
|
|
30892
|
+
// src/exulu/channels/chat-instance.ts
|
|
30893
|
+
var USER_NAME = "exulu-agent";
|
|
30894
|
+
var KEY_PREFIX = CHAT_STATE_KEY_PREFIX;
|
|
30895
|
+
var CHAT_HISTORY = { thread: { maxMessages: 1, ttlMs: 60 * 60 * 1e3 } };
|
|
30896
|
+
var LOG_PREFIX = "[EXULU-CHANNEL]";
|
|
30897
|
+
var loadSdk = async () => {
|
|
30898
|
+
const [chat, whatsapp, statePg] = await Promise.all([
|
|
30899
|
+
import("chat"),
|
|
30900
|
+
import("@chat-adapter/whatsapp"),
|
|
30901
|
+
import("@chat-adapter/state-pg")
|
|
30902
|
+
]);
|
|
30903
|
+
return {
|
|
30904
|
+
Chat: chat.Chat,
|
|
30905
|
+
createWhatsAppAdapter: whatsapp.createWhatsAppAdapter,
|
|
30906
|
+
createPostgresState: statePg.createPostgresState
|
|
30907
|
+
};
|
|
30908
|
+
};
|
|
30909
|
+
var REDACTED_KEYS = /* @__PURE__ */ new Set([
|
|
30910
|
+
"body",
|
|
30911
|
+
"bodyPreview",
|
|
30912
|
+
"text",
|
|
30913
|
+
"emoji",
|
|
30914
|
+
"messageId",
|
|
30915
|
+
"droppedId",
|
|
30916
|
+
"activityId",
|
|
30917
|
+
"mediaId",
|
|
30918
|
+
"threadId",
|
|
30919
|
+
"lockKey",
|
|
30920
|
+
"userId",
|
|
30921
|
+
"authorUserId",
|
|
30922
|
+
"conversationId",
|
|
30923
|
+
"channelId",
|
|
30924
|
+
"token"
|
|
30925
|
+
]);
|
|
30926
|
+
var redact2 = (arg) => {
|
|
30927
|
+
if (arg instanceof Error) return safeError(arg);
|
|
30928
|
+
if (arg === null || typeof arg !== "object" || Array.isArray(arg)) {
|
|
30929
|
+
return arg;
|
|
30930
|
+
}
|
|
30931
|
+
return Object.fromEntries(
|
|
30932
|
+
Object.entries(arg).map(([k, v]) => [
|
|
30933
|
+
k,
|
|
30934
|
+
REDACTED_KEYS.has(k) ? "[redacted]" : v instanceof Error ? safeError(v) : v
|
|
30935
|
+
])
|
|
30936
|
+
);
|
|
30937
|
+
};
|
|
30938
|
+
var sdkLogger = (prefix) => ({
|
|
30939
|
+
child: (p) => sdkLogger(`${prefix}:${p}`),
|
|
30940
|
+
debug: () => {
|
|
30941
|
+
},
|
|
30942
|
+
info: (m, ...args) => console.info(`${LOG_PREFIX} ${prefix}`, m, ...args.map(redact2)),
|
|
30943
|
+
warn: (m, ...args) => console.warn(`${LOG_PREFIX} ${prefix}`, m, ...args.map(redact2)),
|
|
30944
|
+
error: (m, ...args) => console.error(`${LOG_PREFIX} ${prefix}`, m, ...args.map(redact2))
|
|
30945
|
+
});
|
|
30946
|
+
var toInboundMessage = (channelId, threadId, message) => ({
|
|
30947
|
+
channelId,
|
|
30948
|
+
threadId,
|
|
30949
|
+
// whatsapp:<phoneNumberId>:<identity>; the identity is opaque
|
|
30950
|
+
identity: threadId.split(":").slice(2).join(":"),
|
|
30951
|
+
messageId: message.id,
|
|
30952
|
+
text: message.text,
|
|
30953
|
+
hasAttachments: message.attachments.length > 0
|
|
30954
|
+
});
|
|
30955
|
+
var cache2 = /* @__PURE__ */ new Map();
|
|
30956
|
+
var pending = /* @__PURE__ */ new Map();
|
|
30957
|
+
var cacheKey = (channelId, deps) => `${channelId}:${deps.onMessage ? "inbound" : "post-only"}`;
|
|
30958
|
+
var timeOf2 = (value) => new Date(value).getTime();
|
|
30959
|
+
var isNewer = (incoming, cached) => !Number.isNaN(incoming) && (Number.isNaN(cached) || incoming > cached);
|
|
30960
|
+
var shutDown = (channelId, entry) => {
|
|
30961
|
+
entry.promise.then((built) => built.shutdown()).catch(
|
|
30962
|
+
(error) => console.error(`${LOG_PREFIX} shutting down the chat instance of channel ${channelId} failed`, safeError(error))
|
|
30963
|
+
);
|
|
30964
|
+
};
|
|
30965
|
+
var settingsOf = (row) => {
|
|
30966
|
+
const secrets = readSecrets(row);
|
|
30967
|
+
if (!secrets || !row.verify_token) {
|
|
30968
|
+
return null;
|
|
30969
|
+
}
|
|
30970
|
+
let phoneNumberId;
|
|
30971
|
+
try {
|
|
30972
|
+
phoneNumberId = parseChannelConfig(row.config).phoneNumberId;
|
|
30973
|
+
} catch {
|
|
30974
|
+
return null;
|
|
30975
|
+
}
|
|
30976
|
+
return { phoneNumberId, ...secrets, verifyToken: row.verify_token };
|
|
30977
|
+
};
|
|
30978
|
+
var build2 = async (channelId, settings, deps) => {
|
|
30979
|
+
const sdk = await (deps.load ?? loadSdk)();
|
|
30980
|
+
const logger = sdkLogger(`channel ${channelId}`);
|
|
30981
|
+
const adapter = sdk.createWhatsAppAdapter({
|
|
30982
|
+
accessToken: settings.accessToken,
|
|
30983
|
+
appSecret: settings.appSecret,
|
|
30984
|
+
phoneNumberId: settings.phoneNumberId,
|
|
30985
|
+
verifyToken: settings.verifyToken,
|
|
30986
|
+
userName: USER_NAME,
|
|
30987
|
+
logger: logger.child("whatsapp")
|
|
30988
|
+
});
|
|
30989
|
+
const state = sdk.createPostgresState({
|
|
30990
|
+
client: deps.pgPool,
|
|
30991
|
+
keyPrefix: KEY_PREFIX,
|
|
30992
|
+
autoCreateSchema: false,
|
|
30993
|
+
logger: logger.child("state")
|
|
30994
|
+
});
|
|
30995
|
+
const chat = new sdk.Chat({
|
|
30996
|
+
userName: USER_NAME,
|
|
30997
|
+
adapters: { whatsapp: adapter },
|
|
30998
|
+
state,
|
|
30999
|
+
// our own run lock decides; the SDK must not hold or drop messages
|
|
31000
|
+
concurrency: "concurrent",
|
|
31001
|
+
history: { thread: { ...CHAT_HISTORY.thread } },
|
|
31002
|
+
logger
|
|
31003
|
+
});
|
|
31004
|
+
const ownThreadPrefix = `whatsapp:${settings.phoneNumberId}:`;
|
|
31005
|
+
const onMessage = deps.onMessage;
|
|
31006
|
+
if (onMessage) chat.onDirectMessage(async (thread, message) => {
|
|
31007
|
+
if (message.author?.isMe) {
|
|
31008
|
+
return;
|
|
31009
|
+
}
|
|
31010
|
+
if (!thread.id.startsWith(ownThreadPrefix)) {
|
|
31011
|
+
console.warn(`${LOG_PREFIX} channel ${channelId} ignored a message for another phone number`);
|
|
31012
|
+
return;
|
|
31013
|
+
}
|
|
31014
|
+
try {
|
|
31015
|
+
await onMessage(toInboundMessage(channelId, thread.id, message));
|
|
31016
|
+
} catch (error) {
|
|
31017
|
+
console.error(`${LOG_PREFIX} handling a message on channel ${channelId} failed`, safeError(error));
|
|
31018
|
+
}
|
|
31019
|
+
});
|
|
31020
|
+
const ready = () => chat.initialize();
|
|
31021
|
+
const transport = {
|
|
31022
|
+
handleWebhook: async (request3, options) => {
|
|
31023
|
+
if (!onMessage) {
|
|
31024
|
+
throw new Error("post-only channel transport cannot handle webhooks");
|
|
31025
|
+
}
|
|
31026
|
+
return chat.webhooks.whatsapp(request3, options);
|
|
31027
|
+
},
|
|
31028
|
+
post: async (threadId, markdown) => {
|
|
31029
|
+
if (markdown.trim() === "") {
|
|
31030
|
+
throw new Error("refusing to post an empty message");
|
|
31031
|
+
}
|
|
31032
|
+
await ready();
|
|
31033
|
+
await adapter.postMessage(threadId, { markdown });
|
|
31034
|
+
},
|
|
31035
|
+
typing: async (threadId) => {
|
|
31036
|
+
await ready();
|
|
31037
|
+
await adapter.startTyping(threadId);
|
|
31038
|
+
},
|
|
31039
|
+
markRead: async (threadId, messageId) => {
|
|
31040
|
+
await ready();
|
|
31041
|
+
await adapter.markAsRead(threadId, messageId);
|
|
31042
|
+
}
|
|
31043
|
+
};
|
|
31044
|
+
return { transport, shutdown: () => chat.shutdown() };
|
|
31045
|
+
};
|
|
31046
|
+
var startBuild = (key, channelId, updatedAt, settings, deps) => {
|
|
31047
|
+
const entry = { updatedAt, promise: build2(channelId, settings, deps) };
|
|
31048
|
+
pending.set(key, entry);
|
|
31049
|
+
entry.promise.then(
|
|
31050
|
+
() => {
|
|
31051
|
+
if (pending.get(key) === entry) {
|
|
31052
|
+
pending.delete(key);
|
|
31053
|
+
}
|
|
31054
|
+
const current = cache2.get(key);
|
|
31055
|
+
if (current && !isNewer(updatedAt, current.updatedAt)) {
|
|
31056
|
+
shutDown(channelId, entry);
|
|
31057
|
+
return;
|
|
31058
|
+
}
|
|
31059
|
+
cache2.set(key, entry);
|
|
31060
|
+
if (current) {
|
|
31061
|
+
shutDown(channelId, current);
|
|
31062
|
+
}
|
|
31063
|
+
},
|
|
31064
|
+
() => {
|
|
31065
|
+
if (pending.get(key) === entry) {
|
|
31066
|
+
pending.delete(key);
|
|
31067
|
+
}
|
|
31068
|
+
}
|
|
31069
|
+
);
|
|
31070
|
+
return entry;
|
|
31071
|
+
};
|
|
31072
|
+
var getTransport = async (row, deps) => {
|
|
31073
|
+
const settings = settingsOf(row);
|
|
31074
|
+
const updatedAt = timeOf2(row.updatedAt);
|
|
31075
|
+
const key = cacheKey(row.id, deps);
|
|
31076
|
+
const current = cache2.get(key);
|
|
31077
|
+
if (!settings) {
|
|
31078
|
+
if (current && isNewer(updatedAt, current.updatedAt)) {
|
|
31079
|
+
cache2.delete(key);
|
|
31080
|
+
shutDown(row.id, current);
|
|
31081
|
+
}
|
|
31082
|
+
return null;
|
|
31083
|
+
}
|
|
31084
|
+
if (current && !isNewer(updatedAt, current.updatedAt)) {
|
|
31085
|
+
return (await current.promise).transport;
|
|
31086
|
+
}
|
|
31087
|
+
const inFlight3 = pending.get(key);
|
|
31088
|
+
const entry = inFlight3 && !isNewer(updatedAt, inFlight3.updatedAt) ? inFlight3 : startBuild(key, row.id, updatedAt, settings, deps);
|
|
31089
|
+
const built = await entry.promise;
|
|
31090
|
+
const installed = cache2.get(key);
|
|
31091
|
+
return installed && installed !== entry && !isNewer(entry.updatedAt, installed.updatedAt) ? (await installed.promise).transport : built.transport;
|
|
31092
|
+
};
|
|
31093
|
+
|
|
31094
|
+
// src/exulu/channels/pg-pool.ts
|
|
31095
|
+
init_cjs_shims();
|
|
31096
|
+
var import_pg2 = require("pg");
|
|
31097
|
+
var pool;
|
|
31098
|
+
var getChannelPgPool = () => {
|
|
31099
|
+
if (!pool) {
|
|
31100
|
+
pool = new import_pg2.Pool({
|
|
31101
|
+
host: process.env.POSTGRES_DB_HOST,
|
|
31102
|
+
port: parseInt(process.env.POSTGRES_DB_PORT || "5432"),
|
|
31103
|
+
user: process.env.POSTGRES_DB_USER,
|
|
31104
|
+
database: process.env.POSTGRES_DB_NAME || "exulu",
|
|
31105
|
+
password: process.env.POSTGRES_DB_PASSWORD,
|
|
31106
|
+
ssl: process.env.POSTGRES_DB_SSL === "true" ? { rejectUnauthorized: false } : false,
|
|
31107
|
+
max: 5
|
|
31108
|
+
});
|
|
31109
|
+
pool.on("error", (error) => {
|
|
31110
|
+
console.error("[EXULU-CHANNEL] chat state database connection error", safeError(error));
|
|
31111
|
+
});
|
|
31112
|
+
}
|
|
31113
|
+
return pool;
|
|
31114
|
+
};
|
|
31115
|
+
|
|
31116
|
+
// src/exulu/channels/run.ts
|
|
31117
|
+
init_cjs_shims();
|
|
31118
|
+
var RUN_LOCK_TTL_SECONDS = 90;
|
|
31119
|
+
var RUN_LOCK_RENEW_MS = 2e4;
|
|
31120
|
+
var runLockKey = (channelId, identity) => `channel-run:${channelId}:${identity}`;
|
|
31121
|
+
var handleChannelMessage = async (job, deps) => {
|
|
31122
|
+
const who = `${job.channelId} ${maskIdentity(job.identity)}`;
|
|
31123
|
+
const loaded = await deps.loadChannel(job.channelId);
|
|
31124
|
+
if (!loaded || !loaded.row.enabled) return { sessionId: null, posted: "skipped" };
|
|
31125
|
+
const { row, config } = loaded;
|
|
31126
|
+
let allowed = false;
|
|
31127
|
+
try {
|
|
31128
|
+
allowed = await deps.stillAllowed(job, row);
|
|
31129
|
+
} catch (error) {
|
|
31130
|
+
console.error(`[EXULU-CHANNEL] run-time access check failed on channel ${job.channelId}`, safeError(error));
|
|
31131
|
+
}
|
|
31132
|
+
if (!allowed) {
|
|
31133
|
+
console.warn(`[EXULU-CHANNEL] message on channel ${job.channelId} skipped: link or access no longer valid`);
|
|
31134
|
+
return { sessionId: null, posted: "skipped" };
|
|
31135
|
+
}
|
|
31136
|
+
const key = runLockKey(job.channelId, job.identity);
|
|
31137
|
+
const token = await deps.lock.acquire(key, RUN_LOCK_TTL_SECONDS);
|
|
31138
|
+
if (token === null) {
|
|
31139
|
+
await deps.transport.post(job.threadId, replyText("stillWorking", config)).catch(
|
|
31140
|
+
(e) => console.error(`[EXULU-CHANNEL] could not post stillWorking for ${who}`, safeError(e))
|
|
31141
|
+
);
|
|
31142
|
+
return { sessionId: null, posted: "skipped" };
|
|
31143
|
+
}
|
|
31144
|
+
try {
|
|
31145
|
+
let sessionId;
|
|
31146
|
+
try {
|
|
31147
|
+
const recent = job.newSession ? null : await deps.sessions.findRecent({
|
|
31148
|
+
agentId: row.agent,
|
|
31149
|
+
userId: job.userId,
|
|
31150
|
+
channelId: job.channelId,
|
|
31151
|
+
idleHours: config.sessionIdleHours,
|
|
31152
|
+
now: deps.now()
|
|
31153
|
+
});
|
|
31154
|
+
sessionId = recent ?? await deps.sessions.create({
|
|
31155
|
+
agentId: row.agent,
|
|
31156
|
+
userId: job.userId,
|
|
31157
|
+
title: job.text.slice(0, 50),
|
|
31158
|
+
channel: { type: "whatsapp", id: job.channelId, identity: job.identity }
|
|
31159
|
+
});
|
|
31160
|
+
} catch (error) {
|
|
31161
|
+
console.error(`[EXULU-CHANNEL] session lookup/creation failed for ${who}`, safeError(error));
|
|
31162
|
+
await deps.transport.post(job.threadId, replyText("runFailed", config)).catch(
|
|
31163
|
+
(e) => console.error(`[EXULU-CHANNEL] could not post failure notice for ${who}`, safeError(e))
|
|
31164
|
+
);
|
|
31165
|
+
throw error;
|
|
31166
|
+
}
|
|
31167
|
+
const typing = () => {
|
|
31168
|
+
void (async () => deps.transport.typing(job.threadId))().catch(
|
|
31169
|
+
(e) => console.warn(`[EXULU-CHANNEL] typing indicator failed for ${who}`, safeError(e))
|
|
31170
|
+
);
|
|
31171
|
+
};
|
|
31172
|
+
const extendLock = () => {
|
|
31173
|
+
void (async () => deps.lock.extend(key, token, RUN_LOCK_TTL_SECONDS))().then(
|
|
31174
|
+
(extended) => {
|
|
31175
|
+
if (!extended) console.warn(`[EXULU-CHANNEL] run lock could not be extended on channel ${job.channelId}`);
|
|
31176
|
+
},
|
|
31177
|
+
(e) => console.error(`[EXULU-CHANNEL] run lock extension failed on channel ${job.channelId}`, safeError(e))
|
|
31178
|
+
);
|
|
31179
|
+
};
|
|
31180
|
+
typing();
|
|
31181
|
+
const timer3 = setInterval(() => {
|
|
31182
|
+
typing();
|
|
31183
|
+
extendLock();
|
|
31184
|
+
}, RUN_LOCK_RENEW_MS);
|
|
31185
|
+
let answer = null;
|
|
31186
|
+
try {
|
|
31187
|
+
answer = await deps.runAgentTurn({
|
|
31188
|
+
agentId: row.agent,
|
|
31189
|
+
userId: job.userId,
|
|
31190
|
+
sessionId,
|
|
31191
|
+
text: job.text
|
|
31192
|
+
});
|
|
31193
|
+
} catch (error) {
|
|
31194
|
+
console.error(`[EXULU-CHANNEL] agent run failed for ${who}`, safeError(error));
|
|
31195
|
+
} finally {
|
|
31196
|
+
clearInterval(timer3);
|
|
31197
|
+
}
|
|
31198
|
+
const ok = typeof answer === "string" && answer.trim() !== "";
|
|
31199
|
+
let first = true;
|
|
31200
|
+
try {
|
|
31201
|
+
first = await deps.markAnswered(job);
|
|
31202
|
+
} catch (error) {
|
|
31203
|
+
console.error(`[EXULU-CHANNEL] could not mark the message answered on channel ${job.channelId}`, safeError(error));
|
|
31204
|
+
}
|
|
31205
|
+
if (!first) {
|
|
31206
|
+
console.warn(`[EXULU-CHANNEL] message on channel ${job.channelId} already answered; nothing posted`);
|
|
31207
|
+
return { sessionId, posted: "skipped" };
|
|
31208
|
+
}
|
|
31209
|
+
try {
|
|
31210
|
+
await deps.transport.post(job.threadId, ok ? answer : replyText("runFailed", config));
|
|
31211
|
+
} catch (error) {
|
|
31212
|
+
console.error(`[EXULU-CHANNEL] posting to WhatsApp failed for ${who}`, safeError(error));
|
|
31213
|
+
throw error;
|
|
31214
|
+
}
|
|
31215
|
+
return { sessionId, posted: ok ? "answer" : "runFailed" };
|
|
31216
|
+
} finally {
|
|
31217
|
+
await deps.lock.release(key, token).catch((e) => console.error(`[EXULU-CHANNEL] lock release failed for ${who}`, safeError(e)));
|
|
31218
|
+
}
|
|
31219
|
+
};
|
|
31220
|
+
|
|
31221
|
+
// src/exulu/channels/run-lock.ts
|
|
31222
|
+
init_cjs_shims();
|
|
31223
|
+
var import_crypto9 = require("crypto");
|
|
31224
|
+
var RELEASE_SCRIPT = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
|
|
31225
|
+
var EXTEND_SCRIPT = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return 0 end';
|
|
31226
|
+
var createRunLock = (redis) => ({
|
|
31227
|
+
async acquire(key, ttlSeconds) {
|
|
31228
|
+
const token = (0, import_crypto9.randomBytes)(16).toString("hex");
|
|
31229
|
+
const result = await redis.set(key, token, { NX: true, EX: ttlSeconds });
|
|
31230
|
+
return result === null ? null : token;
|
|
31231
|
+
},
|
|
31232
|
+
async release(key, token) {
|
|
31233
|
+
await redis.eval(RELEASE_SCRIPT, { keys: [key], arguments: [token] });
|
|
31234
|
+
},
|
|
31235
|
+
async extend(key, token, ttlSeconds) {
|
|
31236
|
+
const result = await redis.eval(EXTEND_SCRIPT, { keys: [key], arguments: [token, String(ttlSeconds)] });
|
|
31237
|
+
return Number(result) === 1;
|
|
31238
|
+
},
|
|
31239
|
+
async held(key) {
|
|
31240
|
+
return await redis.exists(key) > 0;
|
|
31241
|
+
}
|
|
31242
|
+
});
|
|
31243
|
+
|
|
31244
|
+
// src/exulu/channels/wiring.ts
|
|
31245
|
+
init_cjs_shims();
|
|
31246
|
+
|
|
31247
|
+
// src/exulu/external-rate-limit.ts
|
|
31248
|
+
init_cjs_shims();
|
|
31249
|
+
var MINUTE_MS = 6e4;
|
|
31250
|
+
var HOUR_MS2 = 36e5;
|
|
31251
|
+
var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
|
|
31252
|
+
var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
|
|
31253
|
+
var windows = /* @__PURE__ */ new Map();
|
|
31254
|
+
var externalRateLimitExceeded = (userId, now = Date.now()) => {
|
|
31255
|
+
const state = windows.get(userId) ?? {
|
|
31256
|
+
minuteStart: now,
|
|
31257
|
+
minuteCount: 0,
|
|
31258
|
+
hourStart: now,
|
|
31259
|
+
hourCount: 0,
|
|
31260
|
+
lastSeen: now
|
|
31261
|
+
};
|
|
31262
|
+
if (now - state.minuteStart >= MINUTE_MS) {
|
|
31263
|
+
state.minuteStart = now;
|
|
31264
|
+
state.minuteCount = 0;
|
|
31265
|
+
}
|
|
31266
|
+
if (now - state.hourStart >= HOUR_MS2) {
|
|
31267
|
+
state.hourStart = now;
|
|
31268
|
+
state.hourCount = 0;
|
|
31269
|
+
}
|
|
31270
|
+
state.minuteCount += 1;
|
|
31271
|
+
state.hourCount += 1;
|
|
31272
|
+
state.lastSeen = now;
|
|
31273
|
+
windows.set(userId, state);
|
|
31274
|
+
if (windows.size > 1e4) {
|
|
31275
|
+
for (const [key, value] of windows) {
|
|
31276
|
+
if (now - value.lastSeen >= HOUR_MS2) windows.delete(key);
|
|
31277
|
+
}
|
|
31278
|
+
if (windows.size > 1e4) {
|
|
31279
|
+
const sorted = [...windows.entries()].sort(
|
|
31280
|
+
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
31281
|
+
);
|
|
31282
|
+
for (const [key] of sorted) {
|
|
31283
|
+
if (windows.size <= 1e4) break;
|
|
31284
|
+
windows.delete(key);
|
|
31285
|
+
}
|
|
31286
|
+
}
|
|
31287
|
+
}
|
|
31288
|
+
const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
|
|
31289
|
+
const hourLimitExceeded = state.hourCount > perHourLimit();
|
|
31290
|
+
const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
|
|
31291
|
+
if (limitExceeded) {
|
|
31292
|
+
const limits = {
|
|
31293
|
+
perMinute: perMinuteLimit(),
|
|
31294
|
+
perHour: perHourLimit()
|
|
31295
|
+
};
|
|
31296
|
+
const current = {
|
|
31297
|
+
minute: state.minuteCount,
|
|
31298
|
+
hour: state.hourCount
|
|
31299
|
+
};
|
|
31300
|
+
console.warn(
|
|
31301
|
+
`[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
|
|
31302
|
+
);
|
|
31303
|
+
}
|
|
31304
|
+
return limitExceeded;
|
|
31305
|
+
};
|
|
31306
|
+
var isExternalUser = (user) => {
|
|
31307
|
+
return user?.role?.name === "external";
|
|
31308
|
+
};
|
|
31309
|
+
|
|
31310
|
+
// src/exulu/channels/wiring.ts
|
|
31311
|
+
var channelStoreFromRedis = (client2) => ({
|
|
31312
|
+
set: (key, value, opts) => client2.set(key, value, opts.NX ? { EX: opts.EX, NX: true } : { EX: opts.EX }),
|
|
31313
|
+
getDel: (key) => client2.getDel(key),
|
|
31314
|
+
del: (key) => client2.del(key),
|
|
31315
|
+
incr: (key) => client2.incr(key),
|
|
31316
|
+
expire: (key, seconds) => client2.expire(key, seconds),
|
|
31317
|
+
get: (key) => client2.get(key),
|
|
31318
|
+
ttl: (key) => client2.ttl(key),
|
|
31319
|
+
eval: (script, options) => client2.eval(script, options),
|
|
31320
|
+
exists: (key) => client2.exists(key)
|
|
31321
|
+
});
|
|
31322
|
+
var newSessionKey = (channelId, identity) => `channel-new-session:${channelId}:${identity}`;
|
|
31323
|
+
var createDecideDeps = (p) => {
|
|
31324
|
+
const { row, config, db: db2, store, env } = p;
|
|
31325
|
+
const lock = createRunLock(store);
|
|
31326
|
+
const userRateLimited = env.userRateLimited ?? ((userId) => externalRateLimitExceeded(String(userId)));
|
|
31327
|
+
return {
|
|
31328
|
+
now: env.now ?? (() => /* @__PURE__ */ new Date()),
|
|
31329
|
+
config,
|
|
31330
|
+
// lazily: a missing URL variable must only affect the link reply, never linked users
|
|
31331
|
+
linkUrl: () => linkPageUrl(row.agent),
|
|
31332
|
+
links: createLinkStore(db2),
|
|
31333
|
+
consumeCode: (code) => consumeCode(store, code),
|
|
31334
|
+
codeAttemptsExceeded: (identity) => codeAttemptsExceeded(store, row.id, identity),
|
|
31335
|
+
linkPromptAllowed: (identity) => linkPromptAllowed(store, row.id, identity),
|
|
31336
|
+
access: (userId) => channelAccessCheck({ db: db2, loadAgent: env.loadAgent, agentId: row.agent, channelId: row.id, userId }),
|
|
31337
|
+
rateLimited: (userId) => userRateLimited(userId),
|
|
31338
|
+
runInFlight: (identity) => lock.held(runLockKey(row.id, identity)),
|
|
31339
|
+
// a marker older than the idle window is moot: the next run starts a new session anyway
|
|
31340
|
+
markNewSession: async (identity) => {
|
|
31341
|
+
await store.set(newSessionKey(row.id, identity), "1", { EX: config.sessionIdleHours * 3600 });
|
|
31342
|
+
},
|
|
31343
|
+
takeNewSession: async (identity) => await store.getDel(newSessionKey(row.id, identity)) !== null,
|
|
31344
|
+
audit: createChannelAuditor({ channelId: row.id, agentId: row.agent, kv: store })
|
|
31345
|
+
};
|
|
31346
|
+
};
|
|
31347
|
+
var readyClient = async (env) => {
|
|
31348
|
+
const client2 = await env.getRedis();
|
|
31349
|
+
return client2 && client2.isReady ? client2 : null;
|
|
31350
|
+
};
|
|
31351
|
+
var handleInbound = async (row, msg, env, transportDeps) => {
|
|
31352
|
+
const client2 = await readyClient(env);
|
|
31353
|
+
if (!client2) throw new ChannelSetupError("redis unavailable");
|
|
31354
|
+
const store = (env.storeFor ?? channelStoreFromRedis)(client2);
|
|
31355
|
+
const config = parseChannelConfig(row.config);
|
|
31356
|
+
const db2 = await env.getDb();
|
|
31357
|
+
const decision = await decideInbound(msg, createDecideDeps({ row, config, db: db2, store, env }));
|
|
31358
|
+
const transport = await (env.getTransport ?? getTransport)(row, transportDeps);
|
|
31359
|
+
if (!transport) throw new ChannelSetupError("channel transport unavailable");
|
|
31360
|
+
await actOnDecision(msg, decision, { config, transport, enqueue: env.enqueue, store });
|
|
31361
|
+
};
|
|
31362
|
+
var createChannelWebhookDeps = (env) => ({
|
|
31363
|
+
entitled: () => env.entitled(),
|
|
31364
|
+
rateLimitExceeded: () => env.rateLimitExceeded(),
|
|
31365
|
+
redisAvailable: async () => await readyClient(env) !== null,
|
|
31366
|
+
loadChannel: async (id) => (await env.getDb())("agent_channels").where({ id }).first(),
|
|
31367
|
+
transportFor: (row) => {
|
|
31368
|
+
const transportDeps = {
|
|
31369
|
+
pgPool: getChannelPgPool(),
|
|
31370
|
+
onMessage: (msg) => handleInbound(row, msg, env, transportDeps)
|
|
31371
|
+
};
|
|
31372
|
+
return (env.getTransport ?? getTransport)(row, transportDeps);
|
|
31373
|
+
},
|
|
31374
|
+
// at most once per hour per process, not awaited
|
|
31375
|
+
purgeChatState: () => {
|
|
31376
|
+
purgeChatStateThrottled(getChannelPgPool());
|
|
31377
|
+
}
|
|
31378
|
+
});
|
|
31379
|
+
|
|
31380
|
+
// src/exulu/channels/worker.ts
|
|
31381
|
+
var LOG_PREFIX2 = "[EXULU-CHANNEL]";
|
|
31382
|
+
var parseChannelMessageJob = (inputs) => {
|
|
31383
|
+
const bad = (field) => new Error(`Invalid channel_message job: ${field}`);
|
|
31384
|
+
if (inputs === null || typeof inputs !== "object") throw bad("inputs");
|
|
31385
|
+
const j = inputs;
|
|
31386
|
+
for (const field of ["channelId", "threadId", "identity", "messageId", "text"]) {
|
|
31387
|
+
if (typeof j[field] !== "string" || field !== "text" && j[field] === "") throw bad(field);
|
|
31388
|
+
}
|
|
31389
|
+
if (typeof j.userId !== "number" || !Number.isInteger(j.userId)) throw bad("userId");
|
|
31390
|
+
if (typeof j.newSession !== "boolean") throw bad("newSession");
|
|
31391
|
+
return {
|
|
31392
|
+
channelId: j.channelId,
|
|
31393
|
+
threadId: j.threadId,
|
|
31394
|
+
identity: j.identity,
|
|
31395
|
+
userId: j.userId,
|
|
31396
|
+
messageId: j.messageId,
|
|
31397
|
+
text: j.text,
|
|
31398
|
+
newSession: j.newSession
|
|
31399
|
+
};
|
|
31400
|
+
};
|
|
31401
|
+
var LAST_ACTIVITY = 'COALESCE(last_answer_at, "createdAt")';
|
|
31402
|
+
var findRecentSessionQuery = (db2, p) => db2("agent_sessions").where({ agent: p.agentId, user: p.userId }).whereNull("run").whereRaw("metadata -> 'channel' ->> 'id' = ?", [p.channelId]).whereRaw(`${LAST_ACTIVITY} >= ?`, [new Date(p.now.getTime() - p.idleHours * 3600 * 1e3)]).orderByRaw(`${LAST_ACTIVITY} DESC`).first("id");
|
|
31403
|
+
var createChannelSessions = (db2) => ({
|
|
31404
|
+
async findRecent(p) {
|
|
31405
|
+
const found = await findRecentSessionQuery(db2, p);
|
|
31406
|
+
return found?.id ?? null;
|
|
31407
|
+
},
|
|
31408
|
+
async create(p) {
|
|
31409
|
+
const [inserted] = await db2("agent_sessions").insert({
|
|
31410
|
+
agent: p.agentId,
|
|
31411
|
+
user: p.userId,
|
|
31412
|
+
created_by: p.userId,
|
|
31413
|
+
title: p.title,
|
|
31414
|
+
rights_mode: "private",
|
|
31415
|
+
metadata: { channel: p.channel }
|
|
31416
|
+
}).returning("id");
|
|
31417
|
+
return typeof inserted === "object" ? inserted.id : inserted;
|
|
31418
|
+
}
|
|
31419
|
+
});
|
|
31420
|
+
var createRunDeps = async (env) => {
|
|
31421
|
+
const db2 = await env.getDb();
|
|
31422
|
+
const client2 = await env.getRedis();
|
|
31423
|
+
if (!client2) throw new ChannelSetupError("redis unavailable");
|
|
31424
|
+
const store = channelStoreFromRedis(client2);
|
|
31425
|
+
let loadedRow = null;
|
|
31426
|
+
const transportDeps = { pgPool: getChannelPgPool() };
|
|
31427
|
+
const now = env.now ?? (() => /* @__PURE__ */ new Date());
|
|
31428
|
+
const transport = async () => {
|
|
31429
|
+
if (!loadedRow) throw new ChannelSetupError("no channel loaded for this job");
|
|
31430
|
+
const t = await (env.getTransport ?? getTransport)(loadedRow, transportDeps);
|
|
31431
|
+
if (!t) throw new ChannelSetupError(`channel ${loadedRow.id} has no usable credentials`);
|
|
31432
|
+
return t;
|
|
31433
|
+
};
|
|
31434
|
+
return {
|
|
31435
|
+
now,
|
|
31436
|
+
async loadChannel(id) {
|
|
31437
|
+
const row = await db2("agent_channels").where({ id }).first();
|
|
31438
|
+
if (!row) return null;
|
|
31439
|
+
try {
|
|
31440
|
+
const config = parseChannelConfig(row.config);
|
|
31441
|
+
loadedRow = row;
|
|
31442
|
+
return { row, config };
|
|
31443
|
+
} catch {
|
|
31444
|
+
console.error(`${LOG_PREFIX2} channel ${id} has an invalid config; message skipped`);
|
|
31445
|
+
return null;
|
|
31446
|
+
}
|
|
31447
|
+
},
|
|
31448
|
+
async stillAllowed(job, row) {
|
|
31449
|
+
const state = linkState(await createLinkStore(db2).find(job.channelId, job.identity), now());
|
|
31450
|
+
if (state.state !== "valid" || state.link.user !== job.userId) return false;
|
|
31451
|
+
return channelAccessAllowed({
|
|
31452
|
+
db: db2,
|
|
31453
|
+
loadAgent: env.loadAgent,
|
|
31454
|
+
agentId: row.agent,
|
|
31455
|
+
channelId: row.id,
|
|
31456
|
+
userId: job.userId
|
|
31457
|
+
});
|
|
31458
|
+
},
|
|
31459
|
+
lock: createRunLock(store),
|
|
31460
|
+
async markAnswered(job) {
|
|
31461
|
+
const set = await store.set(answeredKey(job.channelId, job.messageId), "1", { EX: ANSWERED_TTL_SECONDS, NX: true });
|
|
31462
|
+
return set !== null;
|
|
31463
|
+
},
|
|
31464
|
+
sessions: createChannelSessions(db2),
|
|
31465
|
+
runAgentTurn: env.runAgentTurn,
|
|
31466
|
+
transport: {
|
|
31467
|
+
post: async (threadId, markdown) => (await transport()).post(threadId, markdown),
|
|
31468
|
+
typing: async (threadId) => (await transport()).typing(threadId)
|
|
31469
|
+
}
|
|
31470
|
+
};
|
|
31471
|
+
};
|
|
31472
|
+
var runChannelMessageJob = async (inputs, env) => {
|
|
31473
|
+
const job = parseChannelMessageJob(inputs);
|
|
31474
|
+
try {
|
|
31475
|
+
return await handleChannelMessage(job, await createRunDeps(env));
|
|
31476
|
+
} catch (error) {
|
|
31477
|
+
throw sanitizedError(`channel_message job failed on channel ${job.channelId}`, error);
|
|
31478
|
+
}
|
|
31479
|
+
};
|
|
31480
|
+
var createChannelWorkerEnv = (ctx) => {
|
|
31481
|
+
const getDb = async () => (await postgresClient()).db;
|
|
31482
|
+
const loadAgent = (id) => exuluApp.get().agent(id);
|
|
31483
|
+
return {
|
|
31484
|
+
getDb,
|
|
31485
|
+
getRedis: async () => (await redisClient()).client,
|
|
31486
|
+
loadAgent,
|
|
31487
|
+
runAgentTurn: (p) => runChannelAgentTurn(p, { ...ctx, getDb, loadAgent })
|
|
31488
|
+
};
|
|
31489
|
+
};
|
|
31490
|
+
|
|
29529
31491
|
// src/exulu/routines/flow-steps.ts
|
|
29530
31492
|
init_cjs_shims();
|
|
29531
31493
|
var EMAIL_RUN_VARIABLES = /* @__PURE__ */ new Set([
|
|
@@ -30015,18 +31977,18 @@ var startPoolMonitoring = () => {
|
|
|
30015
31977
|
if (poolStats) {
|
|
30016
31978
|
const used = poolStats.numUsed?.() || 0;
|
|
30017
31979
|
const free = poolStats.numFree?.() || 0;
|
|
30018
|
-
const
|
|
31980
|
+
const pending2 = poolStats.numPendingAcquires?.() || 0;
|
|
30019
31981
|
const total = used + free;
|
|
30020
31982
|
console.log("[EXULU] Connection pool health check:", {
|
|
30021
31983
|
used,
|
|
30022
31984
|
free,
|
|
30023
|
-
pending,
|
|
31985
|
+
pending: pending2,
|
|
30024
31986
|
total,
|
|
30025
31987
|
utilization: total > 0 ? `${Math.round(used / total * 100)}%` : "0%"
|
|
30026
31988
|
});
|
|
30027
|
-
if (
|
|
31989
|
+
if (pending2 > 10) {
|
|
30028
31990
|
console.warn(
|
|
30029
|
-
`[EXULU] WARNING: ${
|
|
31991
|
+
`[EXULU] WARNING: ${pending2} jobs waiting for database connections. Consider increasing pool size or reducing worker concurrency.`
|
|
30030
31992
|
);
|
|
30031
31993
|
}
|
|
30032
31994
|
}
|
|
@@ -30865,6 +32827,13 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
30865
32827
|
);
|
|
30866
32828
|
return { result, metadata: {} };
|
|
30867
32829
|
}
|
|
32830
|
+
if (data.type === "channel_message") {
|
|
32831
|
+
const result = await runChannelMessageJob(
|
|
32832
|
+
data.inputs,
|
|
32833
|
+
createChannelWorkerEnv({ tools, contexts, config })
|
|
32834
|
+
);
|
|
32835
|
+
return { result, metadata: {} };
|
|
32836
|
+
}
|
|
30868
32837
|
throw new Error(`Invalid job type: ${data.type} for job ${bullmqJob.name}.`);
|
|
30869
32838
|
} catch (error) {
|
|
30870
32839
|
console.error(
|
|
@@ -31247,7 +33216,7 @@ var processUiMessagesFlow = async ({
|
|
|
31247
33216
|
user,
|
|
31248
33217
|
// Legacy blanket pre-approval unless this run respects
|
|
31249
33218
|
// approvals (spec §5.2 — auto_approve_tools = false routines).
|
|
31250
|
-
approvedTools: respectToolApprovals ? void 0 : tools.map((
|
|
33219
|
+
approvedTools: respectToolApprovals ? void 0 : tools.map((tool5) => "tool-" + sanitizeToolName(tool5.name)),
|
|
31251
33220
|
instructions: agent.instructions,
|
|
31252
33221
|
session: sessionId,
|
|
31253
33222
|
previousMessages: messageHistory.messages,
|
|
@@ -31285,7 +33254,7 @@ var processUiMessagesFlow = async ({
|
|
|
31285
33254
|
// message onto one frozen-createdAt row — which sorts the tool
|
|
31286
33255
|
// approval to the top of the transcript and leaves it out of the
|
|
31287
33256
|
// last-message slot the approval handler acts on (buttons inert).
|
|
31288
|
-
generateMessageId: (0,
|
|
33257
|
+
generateMessageId: (0, import_ai9.createIdGenerator)({
|
|
31289
33258
|
prefix: "msg_",
|
|
31290
33259
|
size: 16
|
|
31291
33260
|
}),
|
|
@@ -31480,7 +33449,7 @@ var applyRoutineRunFilters = (query, args, allowedWorkflowIds, doneKeys) => {
|
|
|
31480
33449
|
}
|
|
31481
33450
|
return q;
|
|
31482
33451
|
};
|
|
31483
|
-
var
|
|
33452
|
+
var parseMaybeJson2 = (value) => {
|
|
31484
33453
|
if (value == null) {
|
|
31485
33454
|
return null;
|
|
31486
33455
|
}
|
|
@@ -31495,18 +33464,18 @@ var parseMaybeJson = (value) => {
|
|
|
31495
33464
|
};
|
|
31496
33465
|
var mapRoutineRunRow = (row, routineById) => {
|
|
31497
33466
|
const routine = row.workflow ? routineById.get(row.workflow) : void 0;
|
|
31498
|
-
const tokens =
|
|
33467
|
+
const tokens = parseMaybeJson2(row.metadata)?.tokens;
|
|
31499
33468
|
return {
|
|
31500
33469
|
id: row.id,
|
|
31501
33470
|
job_id: row.job_id ?? null,
|
|
31502
33471
|
state: row.state,
|
|
31503
33472
|
trigger: row.trigger ?? null,
|
|
31504
|
-
trigger_metadata:
|
|
33473
|
+
trigger_metadata: parseMaybeJson2(row.trigger_metadata),
|
|
31505
33474
|
session: row.session ?? null,
|
|
31506
33475
|
workflow: row.workflow,
|
|
31507
33476
|
workflowName: routine?.name ?? null,
|
|
31508
33477
|
agent: routine?.agent ?? null,
|
|
31509
|
-
error:
|
|
33478
|
+
error: parseMaybeJson2(row.error),
|
|
31510
33479
|
tries: row.tries ?? null,
|
|
31511
33480
|
createdAt: row.createdAt,
|
|
31512
33481
|
updatedAt: row.updatedAt,
|
|
@@ -31515,7 +33484,7 @@ var mapRoutineRunRow = (row, routineById) => {
|
|
|
31515
33484
|
costUsd: tokens?.costUsd ?? null,
|
|
31516
33485
|
work_status: row.work_status ?? null,
|
|
31517
33486
|
work_status_updated_at: row.work_status_updated_at ?? null,
|
|
31518
|
-
work_status_updated_by:
|
|
33487
|
+
work_status_updated_by: parseMaybeJson2(row.work_status_updated_by)
|
|
31519
33488
|
};
|
|
31520
33489
|
};
|
|
31521
33490
|
|
|
@@ -31533,7 +33502,7 @@ init_rbac_update();
|
|
|
31533
33502
|
|
|
31534
33503
|
// src/exulu/recall/service.ts
|
|
31535
33504
|
init_cjs_shims();
|
|
31536
|
-
var
|
|
33505
|
+
var import_ai10 = require("ai");
|
|
31537
33506
|
init_singleton();
|
|
31538
33507
|
init_client();
|
|
31539
33508
|
init_resolve_model();
|
|
@@ -31815,7 +33784,7 @@ function resolveBotIdentity(request3, workspace) {
|
|
|
31815
33784
|
}
|
|
31816
33785
|
|
|
31817
33786
|
// src/exulu/recall/service.ts
|
|
31818
|
-
var
|
|
33787
|
+
var TABLE5 = "transcription_jobs";
|
|
31819
33788
|
var RECONCILE_STALE_MS = 10 * 60 * 1e3;
|
|
31820
33789
|
var RECONCILE_PROBE_QUIET_MS = 60 * 60 * 1e3;
|
|
31821
33790
|
var RECONCILE_GIVE_UP_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -31853,7 +33822,7 @@ var recallService = {
|
|
|
31853
33822
|
const startOfMonth = new Date(
|
|
31854
33823
|
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)
|
|
31855
33824
|
);
|
|
31856
|
-
const [row] = await db2(
|
|
33825
|
+
const [row] = await db2(TABLE5).where({ source: "recall" }).andWhere("createdAt", ">=", startOfMonth).whereNotNull("duration_seconds").sum({ total: "duration_seconds" });
|
|
31857
33826
|
return Number(row?.total ?? 0);
|
|
31858
33827
|
},
|
|
31859
33828
|
/**
|
|
@@ -31898,7 +33867,7 @@ var recallService = {
|
|
|
31898
33867
|
const { db: db2 } = await postgresClient();
|
|
31899
33868
|
const now = /* @__PURE__ */ new Date();
|
|
31900
33869
|
const joinAt = input.join_at ? new Date(input.join_at) : now;
|
|
31901
|
-
const [inserted] = await db2(
|
|
33870
|
+
const [inserted] = await db2(TABLE5).insert({
|
|
31902
33871
|
source: "recall",
|
|
31903
33872
|
status: "queued",
|
|
31904
33873
|
title: input.title ?? null,
|
|
@@ -31931,10 +33900,10 @@ var recallService = {
|
|
|
31931
33900
|
notifyChat: notifyChat ? { message: "This meeting is being recorded and transcribed." } : void 0,
|
|
31932
33901
|
retentionHours: settings.videoRetentionHours.value
|
|
31933
33902
|
});
|
|
31934
|
-
const [updated] = await db2(
|
|
33903
|
+
const [updated] = await db2(TABLE5).where({ id: inserted.id }).update({ recall_bot_id: bot.id, updatedAt: /* @__PURE__ */ new Date() }).returning("*");
|
|
31935
33904
|
return this._row(updated);
|
|
31936
33905
|
} catch (err4) {
|
|
31937
|
-
const [failed] = await db2(
|
|
33906
|
+
const [failed] = await db2(TABLE5).where({ id: inserted.id }).update({
|
|
31938
33907
|
status: "failed",
|
|
31939
33908
|
error: err4.message,
|
|
31940
33909
|
updatedAt: /* @__PURE__ */ new Date()
|
|
@@ -31987,7 +33956,7 @@ var recallService = {
|
|
|
31987
33956
|
return;
|
|
31988
33957
|
}
|
|
31989
33958
|
const { db: db2 } = await postgresClient();
|
|
31990
|
-
const claimed = await db2(
|
|
33959
|
+
const claimed = await db2(TABLE5).where({ id: jobId }).whereNotIn("status", [
|
|
31991
33960
|
"transcribing",
|
|
31992
33961
|
"awaiting_review",
|
|
31993
33962
|
"reviewed",
|
|
@@ -32004,7 +33973,7 @@ var recallService = {
|
|
|
32004
33973
|
return;
|
|
32005
33974
|
}
|
|
32006
33975
|
try {
|
|
32007
|
-
const row = await db2(
|
|
33976
|
+
const row = await db2(TABLE5).where({ id: jobId }).first();
|
|
32008
33977
|
const transcript = await recallClient.createAsyncTranscript(
|
|
32009
33978
|
recordingId,
|
|
32010
33979
|
row?.language || "auto"
|
|
@@ -32016,7 +33985,7 @@ var recallService = {
|
|
|
32016
33985
|
},
|
|
32017
33986
|
async _onTranscriptDone(jobId, transcriptId, recordingId) {
|
|
32018
33987
|
const { db: db2 } = await postgresClient();
|
|
32019
|
-
const dbRow = await db2(
|
|
33988
|
+
const dbRow = await db2(TABLE5).where({ id: jobId }).first();
|
|
32020
33989
|
if (!dbRow) return;
|
|
32021
33990
|
const job = this._row(dbRow);
|
|
32022
33991
|
if ((job.status === "awaiting_review" || job.status === "reviewed" || job.status === "saved") && job.raw_segments && job.raw_segments.length > 0) {
|
|
@@ -32109,7 +34078,7 @@ var recallService = {
|
|
|
32109
34078
|
*/
|
|
32110
34079
|
async runPostProcessing(jobId) {
|
|
32111
34080
|
const { db: db2 } = await postgresClient();
|
|
32112
|
-
const dbRow = await db2(
|
|
34081
|
+
const dbRow = await db2(TABLE5).where({ id: jobId }).first();
|
|
32113
34082
|
if (!dbRow) return [];
|
|
32114
34083
|
const job = this._row(dbRow);
|
|
32115
34084
|
const prompts = job.post_processing_prompts ?? [];
|
|
@@ -32122,7 +34091,7 @@ var recallService = {
|
|
|
32122
34091
|
log3(`post-processing for job ${jobId} skipped: no transcript.`);
|
|
32123
34092
|
return [];
|
|
32124
34093
|
}
|
|
32125
|
-
const claimed = await db2(
|
|
34094
|
+
const claimed = await db2(TABLE5).where({ id: jobId }).whereRaw(
|
|
32126
34095
|
`(post_processing_outputs IS NULL OR (post_processing_outputs::text = '[]' AND "updatedAt" < ?))`,
|
|
32127
34096
|
[new Date(Date.now() - POST_PROCESSING_REDO_STALE_MS)]
|
|
32128
34097
|
).update({ post_processing_outputs: "[]", updatedAt: /* @__PURE__ */ new Date() });
|
|
@@ -32145,7 +34114,7 @@ var recallService = {
|
|
|
32145
34114
|
async _mergeOutputs(jobId, entries) {
|
|
32146
34115
|
const { db: db2 } = await postgresClient();
|
|
32147
34116
|
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
32148
|
-
const row = await db2(
|
|
34117
|
+
const row = await db2(TABLE5).where({ id: jobId }).first();
|
|
32149
34118
|
if (!row) return entries;
|
|
32150
34119
|
const raw = row.post_processing_outputs ?? null;
|
|
32151
34120
|
const snapshot = raw == null ? null : typeof raw === "string" ? raw : JSON.stringify(raw);
|
|
@@ -32158,7 +34127,7 @@ var recallService = {
|
|
|
32158
34127
|
),
|
|
32159
34128
|
...entries
|
|
32160
34129
|
];
|
|
32161
|
-
const updated = await db2(
|
|
34130
|
+
const updated = await db2(TABLE5).where({ id: jobId }).whereRaw(
|
|
32162
34131
|
"post_processing_outputs::jsonb IS NOT DISTINCT FROM ?::jsonb",
|
|
32163
34132
|
[snapshot]
|
|
32164
34133
|
).update({
|
|
@@ -32178,7 +34147,7 @@ var recallService = {
|
|
|
32178
34147
|
*/
|
|
32179
34148
|
async runOnePostProcessing(jobId, promptId, agentId) {
|
|
32180
34149
|
const { db: db2 } = await postgresClient();
|
|
32181
|
-
const dbRow = await db2(
|
|
34150
|
+
const dbRow = await db2(TABLE5).where({ id: jobId }).first();
|
|
32182
34151
|
if (!dbRow) throw new Error(`transcription_job ${jobId} not found`);
|
|
32183
34152
|
const job = this._row(dbRow);
|
|
32184
34153
|
const claimInFlight = dbRow.post_processing_outputs != null && (job.post_processing_outputs?.length ?? 0) === 0 && Date.now() - new Date(job.updatedAt).getTime() < POST_PROCESSING_REDO_STALE_MS;
|
|
@@ -32213,7 +34182,7 @@ var recallService = {
|
|
|
32213
34182
|
job.speakers ?? {},
|
|
32214
34183
|
{ timestamps: true }
|
|
32215
34184
|
);
|
|
32216
|
-
const { text } = await (0,
|
|
34185
|
+
const { text } = await (0, import_ai10.generateText)({
|
|
32217
34186
|
model: resolved.languageModel,
|
|
32218
34187
|
system: withGlossary(agent.instructions, agent.tools) || void 0,
|
|
32219
34188
|
prompt: `${prompt.content}
|
|
@@ -32261,10 +34230,10 @@ ${transcriptText}`,
|
|
|
32261
34230
|
if (!recallEnabled()) return 0;
|
|
32262
34231
|
const { db: db2 } = await postgresClient();
|
|
32263
34232
|
const now = Date.now();
|
|
32264
|
-
const stuck = await db2(
|
|
34233
|
+
const stuck = await db2(TABLE5).where({ source: "recall" }).whereIn("status", ["queued", "transcribing"]).whereRaw(`("join_at" IS NULL OR "join_at" < ?)`, [
|
|
32265
34234
|
new Date(now - RECONCILE_STALE_MS)
|
|
32266
34235
|
]).where("updatedAt", "<", new Date(now - RECONCILE_STALE_MS)).orderBy("updatedAt", "asc").limit(limit);
|
|
32267
|
-
const redo = await db2(
|
|
34236
|
+
const redo = await db2(TABLE5).where({ source: "recall", status: "awaiting_review" }).whereNotNull("post_processing_prompts").whereRaw("post_processing_prompts::text <> '[]'").whereRaw("(raw_segments IS NOT NULL AND raw_segments::text <> '[]')").whereRaw(
|
|
32268
34237
|
"(post_processing_outputs IS NULL OR post_processing_outputs::text = '[]')"
|
|
32269
34238
|
).where("updatedAt", "<", new Date(now - POST_PROCESSING_REDO_STALE_MS)).orderBy("updatedAt", "asc").limit(limit);
|
|
32270
34239
|
let acted = 0;
|
|
@@ -32400,7 +34369,7 @@ ${transcriptText}`,
|
|
|
32400
34369
|
});
|
|
32401
34370
|
} else {
|
|
32402
34371
|
const { db: db2 } = await postgresClient();
|
|
32403
|
-
const claimed = await db2(
|
|
34372
|
+
const claimed = await db2(TABLE5).where({ id: job.id, status: "transcribing" }).whereNull("recall_transcript_id").where("updatedAt", "<", new Date(Date.now() - RECONCILE_STALE_MS)).update({ recall_recording_id: recordingId, updatedAt: /* @__PURE__ */ new Date() });
|
|
32404
34373
|
if (!claimed) return false;
|
|
32405
34374
|
log3(
|
|
32406
34375
|
`reconcile: re-requesting transcript for job ${job.id} (lost before createAsyncTranscript)`
|
|
@@ -32450,16 +34419,16 @@ ${transcriptText}`,
|
|
|
32450
34419
|
async _findJob(botId, recordingId, transcriptId) {
|
|
32451
34420
|
const { db: db2 } = await postgresClient();
|
|
32452
34421
|
let dbRow;
|
|
32453
|
-
if (botId) dbRow = await db2(
|
|
34422
|
+
if (botId) dbRow = await db2(TABLE5).where({ recall_bot_id: botId }).first();
|
|
32454
34423
|
if (!dbRow && recordingId)
|
|
32455
|
-
dbRow = await db2(
|
|
34424
|
+
dbRow = await db2(TABLE5).where({ recall_recording_id: recordingId }).first();
|
|
32456
34425
|
if (!dbRow && transcriptId)
|
|
32457
|
-
dbRow = await db2(
|
|
34426
|
+
dbRow = await db2(TABLE5).where({ recall_transcript_id: transcriptId }).first();
|
|
32458
34427
|
return dbRow ? this._row(dbRow) : null;
|
|
32459
34428
|
},
|
|
32460
34429
|
async _update(id, patch) {
|
|
32461
34430
|
const { db: db2 } = await postgresClient();
|
|
32462
|
-
await db2(
|
|
34431
|
+
await db2(TABLE5).where({ id }).update({ ...patch, updatedAt: /* @__PURE__ */ new Date() });
|
|
32463
34432
|
},
|
|
32464
34433
|
async _fail(id, error) {
|
|
32465
34434
|
await this._update(id, { status: "failed", error });
|
|
@@ -32592,7 +34561,7 @@ async function assertOwnsTranscriptionJob(db2, user, id) {
|
|
|
32592
34561
|
}
|
|
32593
34562
|
|
|
32594
34563
|
// src/exulu/transcription/service.ts
|
|
32595
|
-
var
|
|
34564
|
+
var TABLE6 = "transcription_jobs";
|
|
32596
34565
|
var log4 = (msg) => console.log(`[EXULU-TRANSCRIPTION] ${msg}`);
|
|
32597
34566
|
var parseJsonField = (v) => {
|
|
32598
34567
|
if (v == null) return null;
|
|
@@ -32631,7 +34600,7 @@ var transcriptionService = {
|
|
|
32631
34600
|
}
|
|
32632
34601
|
const { db: db2 } = await postgresClient();
|
|
32633
34602
|
const now = /* @__PURE__ */ new Date();
|
|
32634
|
-
const [inserted] = await db2(
|
|
34603
|
+
const [inserted] = await db2(TABLE6).insert({
|
|
32635
34604
|
audio_s3key: input.s3Key,
|
|
32636
34605
|
title: input.title ?? input.filename,
|
|
32637
34606
|
status: "queued",
|
|
@@ -32654,14 +34623,14 @@ var transcriptionService = {
|
|
|
32654
34623
|
num_speakers: input.num_speakers ?? void 0,
|
|
32655
34624
|
hotwords: input.hotwords
|
|
32656
34625
|
});
|
|
32657
|
-
const [updated] = await db2(
|
|
34626
|
+
const [updated] = await db2(TABLE6).where({ id: row.id }).update({
|
|
32658
34627
|
whisper_job_id: submitted.job_id,
|
|
32659
34628
|
status: "transcribing",
|
|
32660
34629
|
updatedAt: /* @__PURE__ */ new Date()
|
|
32661
34630
|
}).returning("*");
|
|
32662
34631
|
return this._rowFromDb(updated);
|
|
32663
34632
|
} catch (err4) {
|
|
32664
|
-
const [failed] = await db2(
|
|
34633
|
+
const [failed] = await db2(TABLE6).where({ id: row.id }).update({
|
|
32665
34634
|
status: "failed",
|
|
32666
34635
|
error: err4.message,
|
|
32667
34636
|
updatedAt: /* @__PURE__ */ new Date()
|
|
@@ -32678,7 +34647,7 @@ var transcriptionService = {
|
|
|
32678
34647
|
async pollOnce(maxPerTick = 50) {
|
|
32679
34648
|
if (!transcriptionClient.isConfigured()) return;
|
|
32680
34649
|
const { db: db2 } = await postgresClient();
|
|
32681
|
-
const rows = await db2(
|
|
34650
|
+
const rows = await db2(TABLE6).where({ status: "transcribing" }).whereNotNull("whisper_job_id").limit(maxPerTick);
|
|
32682
34651
|
for (const dbRow of rows) {
|
|
32683
34652
|
const row = this._rowFromDb(dbRow);
|
|
32684
34653
|
if (!row.whisper_job_id) continue;
|
|
@@ -32688,7 +34657,7 @@ var transcriptionService = {
|
|
|
32688
34657
|
} catch (err4) {
|
|
32689
34658
|
const code = err4.code;
|
|
32690
34659
|
if (code === "JOB_NOT_FOUND") {
|
|
32691
|
-
await db2(
|
|
34660
|
+
await db2(TABLE6).where({ id: row.id }).update({
|
|
32692
34661
|
status: "failed",
|
|
32693
34662
|
error: "lost on server restart",
|
|
32694
34663
|
updatedAt: /* @__PURE__ */ new Date()
|
|
@@ -32704,14 +34673,14 @@ var transcriptionService = {
|
|
|
32704
34673
|
async _applyJobUpdate(row, job) {
|
|
32705
34674
|
const { db: db2 } = await postgresClient();
|
|
32706
34675
|
if ((job.status === "queued" || job.status === "running") && job.duration_seconds != null && row.duration_seconds !== job.duration_seconds) {
|
|
32707
|
-
await db2(
|
|
34676
|
+
await db2(TABLE6).where({ id: row.id }).update({
|
|
32708
34677
|
duration_seconds: job.duration_seconds,
|
|
32709
34678
|
updatedAt: /* @__PURE__ */ new Date()
|
|
32710
34679
|
});
|
|
32711
34680
|
}
|
|
32712
34681
|
if (job.status === "running" || job.status === "queued") return;
|
|
32713
34682
|
if (job.status === "completed") {
|
|
32714
|
-
await db2(
|
|
34683
|
+
await db2(TABLE6).where({ id: row.id }).update({
|
|
32715
34684
|
status: "awaiting_review",
|
|
32716
34685
|
raw_segments: JSON.stringify(job.segments ?? []),
|
|
32717
34686
|
language: job.language ?? null,
|
|
@@ -32730,7 +34699,7 @@ var transcriptionService = {
|
|
|
32730
34699
|
return;
|
|
32731
34700
|
}
|
|
32732
34701
|
if (job.status === "failed") {
|
|
32733
|
-
await db2(
|
|
34702
|
+
await db2(TABLE6).where({ id: row.id }).update({
|
|
32734
34703
|
status: "failed",
|
|
32735
34704
|
error: job.error ?? "transcription failed",
|
|
32736
34705
|
updatedAt: /* @__PURE__ */ new Date()
|
|
@@ -32738,7 +34707,7 @@ var transcriptionService = {
|
|
|
32738
34707
|
return;
|
|
32739
34708
|
}
|
|
32740
34709
|
if (job.status === "cancelled") {
|
|
32741
|
-
await db2(
|
|
34710
|
+
await db2(TABLE6).where({ id: row.id }).update({
|
|
32742
34711
|
status: "cancelled",
|
|
32743
34712
|
updatedAt: /* @__PURE__ */ new Date()
|
|
32744
34713
|
});
|
|
@@ -32746,7 +34715,7 @@ var transcriptionService = {
|
|
|
32746
34715
|
},
|
|
32747
34716
|
async cancelJob(id) {
|
|
32748
34717
|
const { db: db2 } = await postgresClient();
|
|
32749
|
-
const dbRow = await db2(
|
|
34718
|
+
const dbRow = await db2(TABLE6).where({ id }).first();
|
|
32750
34719
|
if (!dbRow) throw new Error(`transcription_job ${id} not found`);
|
|
32751
34720
|
const row = this._rowFromDb(dbRow);
|
|
32752
34721
|
if (row.whisper_job_id && transcriptionClient.isConfigured()) {
|
|
@@ -32759,7 +34728,7 @@ var transcriptionService = {
|
|
|
32759
34728
|
}
|
|
32760
34729
|
}
|
|
32761
34730
|
}
|
|
32762
|
-
const [updated] = await db2(
|
|
34731
|
+
const [updated] = await db2(TABLE6).where({ id }).update({ status: "cancelled", updatedAt: /* @__PURE__ */ new Date() }).returning("*");
|
|
32763
34732
|
return this._rowFromDb(updated);
|
|
32764
34733
|
},
|
|
32765
34734
|
/**
|
|
@@ -32782,7 +34751,7 @@ var transcriptionService = {
|
|
|
32782
34751
|
*/
|
|
32783
34752
|
async markReviewed(id, input) {
|
|
32784
34753
|
const { db: db2 } = await postgresClient();
|
|
32785
|
-
const dbRow = await db2(
|
|
34754
|
+
const dbRow = await db2(TABLE6).where({ id }).first();
|
|
32786
34755
|
if (!dbRow) throw new Error(`transcription_job ${id} not found`);
|
|
32787
34756
|
const row = this._rowFromDb(dbRow);
|
|
32788
34757
|
if (row.status !== "awaiting_review" && row.status !== "reviewed") {
|
|
@@ -32794,7 +34763,7 @@ var transcriptionService = {
|
|
|
32794
34763
|
throw new Error(`transcription_job ${id} has no raw_segments to review`);
|
|
32795
34764
|
}
|
|
32796
34765
|
const resolvedCorrected = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments ?? null;
|
|
32797
|
-
const [updated] = await db2(
|
|
34766
|
+
const [updated] = await db2(TABLE6).where({ id }).update({
|
|
32798
34767
|
status: "reviewed",
|
|
32799
34768
|
reviewed_at: row.reviewed_at ?? /* @__PURE__ */ new Date(),
|
|
32800
34769
|
title: input.title ?? row.title,
|
|
@@ -32821,7 +34790,7 @@ var transcriptionService = {
|
|
|
32821
34790
|
*/
|
|
32822
34791
|
async finalize(id, input) {
|
|
32823
34792
|
const { db: db2 } = await postgresClient();
|
|
32824
|
-
const dbRow = await db2(
|
|
34793
|
+
const dbRow = await db2(TABLE6).where({ id }).first();
|
|
32825
34794
|
if (!dbRow) throw new Error(`transcription_job ${id} not found`);
|
|
32826
34795
|
const row = this._rowFromDb(dbRow);
|
|
32827
34796
|
if (row.status !== "awaiting_review" && row.status !== "reviewed" && row.status !== "saved") {
|
|
@@ -32866,7 +34835,7 @@ var transcriptionService = {
|
|
|
32866
34835
|
);
|
|
32867
34836
|
item = result.item;
|
|
32868
34837
|
} catch (err4) {
|
|
32869
|
-
await db2(
|
|
34838
|
+
await db2(TABLE6).where({ id }).update({
|
|
32870
34839
|
speakers: JSON.stringify(input.speakers),
|
|
32871
34840
|
error: `Failed to save: ${err4.message}`,
|
|
32872
34841
|
updatedAt: /* @__PURE__ */ new Date()
|
|
@@ -32912,7 +34881,7 @@ var transcriptionService = {
|
|
|
32912
34881
|
}
|
|
32913
34882
|
}
|
|
32914
34883
|
const nextCorrectedSegments = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments;
|
|
32915
|
-
const [updated] = await db2(
|
|
34884
|
+
const [updated] = await db2(TABLE6).where({ id }).update({
|
|
32916
34885
|
status: "saved",
|
|
32917
34886
|
reviewed_at: row.reviewed_at ?? /* @__PURE__ */ new Date(),
|
|
32918
34887
|
saved_item_id: itemId,
|
|
@@ -32953,7 +34922,7 @@ var transcriptionService = {
|
|
|
32953
34922
|
if (err4 instanceof TranscriptionJobAccessError) return void 0;
|
|
32954
34923
|
throw err4;
|
|
32955
34924
|
}
|
|
32956
|
-
const dbRow = await db2(
|
|
34925
|
+
const dbRow = await db2(TABLE6).where({ id: jobId }).first();
|
|
32957
34926
|
if (!dbRow) return void 0;
|
|
32958
34927
|
const row = this._rowFromDb(dbRow);
|
|
32959
34928
|
return {
|
|
@@ -32993,7 +34962,7 @@ var transcriptionService = {
|
|
|
32993
34962
|
init_cjs_shims();
|
|
32994
34963
|
init_client();
|
|
32995
34964
|
init_supervisor();
|
|
32996
|
-
var
|
|
34965
|
+
var TABLE7 = "transcription_jobs";
|
|
32997
34966
|
var log5 = (msg) => console.log(`[EXULU-LIVE-RECORDING] ${msg}`);
|
|
32998
34967
|
var LIVE_RECORDING_DISABLED_MESSAGE = "Speech-to-text is not enabled on this deployment. Set EXULU_USE_LITELLM=true and TRANSCRIPTION_MODEL in the environment.";
|
|
32999
34968
|
function liveRecordingEnabled() {
|
|
@@ -33019,7 +34988,7 @@ var liveRecordingService = {
|
|
|
33019
34988
|
async start(input) {
|
|
33020
34989
|
const { db: db2 } = await postgresClient();
|
|
33021
34990
|
const now = /* @__PURE__ */ new Date();
|
|
33022
|
-
const [inserted] = await db2(
|
|
34991
|
+
const [inserted] = await db2(TABLE7).insert({
|
|
33023
34992
|
source: "live",
|
|
33024
34993
|
status: "recording",
|
|
33025
34994
|
chunk_count: 0,
|
|
@@ -33049,7 +35018,7 @@ var liveRecordingService = {
|
|
|
33049
35018
|
text: input.text,
|
|
33050
35019
|
speaker: "unknown"
|
|
33051
35020
|
};
|
|
33052
|
-
const affected = await db2(
|
|
35021
|
+
const affected = await db2(TABLE7).where({ id: input.id, status: "recording", chunk_count: input.seq }).update({
|
|
33053
35022
|
raw_segments: db2.raw("COALESCE(raw_segments, '[]'::jsonb) || ?::jsonb", [
|
|
33054
35023
|
JSON.stringify([segment])
|
|
33055
35024
|
]),
|
|
@@ -33059,7 +35028,7 @@ var liveRecordingService = {
|
|
|
33059
35028
|
updatedAt: /* @__PURE__ */ new Date()
|
|
33060
35029
|
});
|
|
33061
35030
|
if (affected === 1) return { kind: "appended", chunkCount: input.seq + 1 };
|
|
33062
|
-
const row = await db2(
|
|
35031
|
+
const row = await db2(TABLE7).select(["status", "chunk_count", "raw_segments"]).where({ id: input.id }).first();
|
|
33063
35032
|
if (!row) throw new Error(`transcription_job ${input.id} not found`);
|
|
33064
35033
|
if (row.status !== "recording") return { kind: "not_recording", status: row.status };
|
|
33065
35034
|
const chunkCount = Number(row.chunk_count ?? 0);
|
|
@@ -33076,9 +35045,9 @@ var liveRecordingService = {
|
|
|
33076
35045
|
if (typeof input.duration_seconds === "number" && input.duration_seconds > 0) {
|
|
33077
35046
|
patch.duration_seconds = input.duration_seconds;
|
|
33078
35047
|
}
|
|
33079
|
-
const [updated] = await db2(
|
|
35048
|
+
const [updated] = await db2(TABLE7).where({ id, status: "recording" }).update(patch).returning("*");
|
|
33080
35049
|
if (!updated) {
|
|
33081
|
-
const row = await db2(
|
|
35050
|
+
const row = await db2(TABLE7).where({ id }).first();
|
|
33082
35051
|
if (!row) throw new Error(`transcription_job ${id} not found`);
|
|
33083
35052
|
throw new Error(
|
|
33084
35053
|
`transcription_job ${id} is in status '${row.status}'; can only stop from 'recording'`
|
|
@@ -34132,7 +36101,7 @@ function groupDuplicates(pairs, cap) {
|
|
|
34132
36101
|
// src/exulu/memory/conflicts/scan.ts
|
|
34133
36102
|
var INSERT_CHUNK = 500;
|
|
34134
36103
|
var num5 = (v) => typeof v === "number" ? v : Number(v ?? 0) || 0;
|
|
34135
|
-
var
|
|
36104
|
+
var pool2 = async (items, limit, worker) => {
|
|
34136
36105
|
let next = 0;
|
|
34137
36106
|
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
34138
36107
|
while (next < items.length) {
|
|
@@ -34196,7 +36165,7 @@ async function runScan({ db: db2, context, user, judge, now = /* @__PURE__ */ ne
|
|
|
34196
36165
|
const toJudge = needJudgement.slice(0, JUDGE_CALLS_PER_SCAN);
|
|
34197
36166
|
unjudged += needJudgement.length - toJudge.length;
|
|
34198
36167
|
const fresh = /* @__PURE__ */ new Map();
|
|
34199
|
-
await
|
|
36168
|
+
await pool2(toJudge, JUDGE_CONCURRENCY, async (pair) => {
|
|
34200
36169
|
const key = pairKey(context.id, pair.a, pair.b);
|
|
34201
36170
|
try {
|
|
34202
36171
|
const verdict = await judge(wordings.get(pair.a) ?? "", wordings.get(pair.b) ?? "", AbortSignal.timeout(JUDGE_TIMEOUT_MS));
|
|
@@ -34264,7 +36233,7 @@ async function runScan({ db: db2, context, user, judge, now = /* @__PURE__ */ ne
|
|
|
34264
36233
|
|
|
34265
36234
|
// src/exulu/memory/conflicts/judge.ts
|
|
34266
36235
|
init_cjs_shims();
|
|
34267
|
-
var
|
|
36236
|
+
var import_ai11 = require("ai");
|
|
34268
36237
|
var import_zod26 = require("zod");
|
|
34269
36238
|
init_resolve_model();
|
|
34270
36239
|
var schema = import_zod26.z.object({
|
|
@@ -34279,7 +36248,7 @@ Answer with JSON: verdict = "same" when both state the same fact or instruction
|
|
|
34279
36248
|
async function makeModelJudge({ modelId, agent, user }) {
|
|
34280
36249
|
const { languageModel } = await resolveModel({ modelId, agent, user, rbacBypass: true });
|
|
34281
36250
|
return async (a, b, signal) => {
|
|
34282
|
-
const { output } = await (0,
|
|
36251
|
+
const { output } = await (0, import_ai11.generateText)({
|
|
34283
36252
|
temperature: 0,
|
|
34284
36253
|
model: languageModel,
|
|
34285
36254
|
system: SYSTEM,
|
|
@@ -34290,7 +36259,7 @@ Memory B:
|
|
|
34290
36259
|
${b}`,
|
|
34291
36260
|
maxRetries: 1,
|
|
34292
36261
|
...signal ? { abortSignal: signal } : {},
|
|
34293
|
-
output:
|
|
36262
|
+
output: import_ai11.Output.object({ schema })
|
|
34294
36263
|
});
|
|
34295
36264
|
return { verdict: output.verdict, reason: output.reason.slice(0, 160) };
|
|
34296
36265
|
};
|
|
@@ -34298,14 +36267,14 @@ ${b}`,
|
|
|
34298
36267
|
async function makeMergeSuggester({ modelId, agent, user }) {
|
|
34299
36268
|
const { languageModel } = await resolveModel({ modelId, agent, user, rbacBypass: true });
|
|
34300
36269
|
return async (members) => {
|
|
34301
|
-
const { output } = await (0,
|
|
36270
|
+
const { output } = await (0, import_ai11.generateText)({
|
|
34302
36271
|
temperature: 0,
|
|
34303
36272
|
model: languageModel,
|
|
34304
36273
|
system: "You merge near-duplicate memories into one. Keep every fact, drop repetition, keep the memories' language and tone, \u2264 400 characters. Answer with JSON { information }.",
|
|
34305
36274
|
prompt: members.map((m, i) => `Memory ${i + 1}:
|
|
34306
36275
|
${m.information}`).join("\n\n"),
|
|
34307
36276
|
maxRetries: 1,
|
|
34308
|
-
output:
|
|
36277
|
+
output: import_ai11.Output.object({ schema: import_zod26.z.object({ information: import_zod26.z.string().min(1).max(400) }) })
|
|
34309
36278
|
});
|
|
34310
36279
|
const types = members.map((m) => m.type).filter((t) => !!t);
|
|
34311
36280
|
const type = types.length ? [...types].sort((x, y) => types.filter((t) => t === y).length - types.filter((t) => t === x).length)[0] ?? null : null;
|
|
@@ -35588,12 +37557,12 @@ type EmbeddingModelOption {
|
|
|
35588
37557
|
contextQueueNames: async () => {
|
|
35589
37558
|
const names = /* @__PURE__ */ new Set();
|
|
35590
37559
|
for (const ctx of contexts ?? []) {
|
|
35591
|
-
const
|
|
37560
|
+
const pending2 = [
|
|
35592
37561
|
ctx.processor?.config?.queue,
|
|
35593
37562
|
ctx.embedder?.queue,
|
|
35594
37563
|
...(ctx.sources ?? []).map((source) => source.config?.queue)
|
|
35595
37564
|
];
|
|
35596
|
-
for (const queue of
|
|
37565
|
+
for (const queue of pending2) {
|
|
35597
37566
|
const config2 = await Promise.resolve(queue).catch(() => void 0);
|
|
35598
37567
|
if (config2?.queue?.name) names.add(config2.queue.name);
|
|
35599
37568
|
}
|
|
@@ -36871,7 +38840,7 @@ type EmbeddingModelOption {
|
|
|
36871
38840
|
})
|
|
36872
38841
|
);
|
|
36873
38842
|
let agenticRetrievalTool = void 0;
|
|
36874
|
-
const filtered = agentTools.filter((
|
|
38843
|
+
const filtered = agentTools.filter((tool5) => tool5 !== null);
|
|
36875
38844
|
let allTools = [...filtered, ...tools];
|
|
36876
38845
|
if (contexts?.length) {
|
|
36877
38846
|
agenticRetrievalTool = createAgenticRetrievalTool({
|
|
@@ -36891,21 +38860,21 @@ type EmbeddingModelOption {
|
|
|
36891
38860
|
if (search && search.trim()) {
|
|
36892
38861
|
const searchTerm = search.toLowerCase().trim();
|
|
36893
38862
|
allTools = allTools.filter(
|
|
36894
|
-
(
|
|
38863
|
+
(tool5) => tool5.name?.toLowerCase().includes(searchTerm) || tool5.description?.toLowerCase().includes(searchTerm)
|
|
36895
38864
|
);
|
|
36896
38865
|
}
|
|
36897
38866
|
if (category && category.trim()) {
|
|
36898
|
-
allTools = allTools.filter((
|
|
38867
|
+
allTools = allTools.filter((tool5) => tool5.category === category);
|
|
36899
38868
|
}
|
|
36900
38869
|
const total = allTools.length;
|
|
36901
38870
|
const start = page * limit;
|
|
36902
38871
|
const end = start + limit;
|
|
36903
38872
|
const paginatedTools = allTools.slice(start, end);
|
|
36904
38873
|
return {
|
|
36905
|
-
items: paginatedTools.map((
|
|
38874
|
+
items: paginatedTools.map((tool5) => {
|
|
36906
38875
|
const object = {};
|
|
36907
38876
|
requestedFields.forEach((field) => {
|
|
36908
|
-
object[field] =
|
|
38877
|
+
object[field] = tool5[field];
|
|
36909
38878
|
});
|
|
36910
38879
|
return object;
|
|
36911
38880
|
}),
|
|
@@ -36915,7 +38884,7 @@ type EmbeddingModelOption {
|
|
|
36915
38884
|
};
|
|
36916
38885
|
};
|
|
36917
38886
|
resolvers2.Query["toolCategories"] = async () => {
|
|
36918
|
-
const array = tools.map((
|
|
38887
|
+
const array = tools.map((tool5) => tool5.category).filter((category) => category && typeof category === "string");
|
|
36919
38888
|
array.push("contexts");
|
|
36920
38889
|
array.push("agents");
|
|
36921
38890
|
return [...new Set(array)].sort();
|
|
@@ -37208,7 +39177,7 @@ var import_crypto_js7 = require("crypto-js");
|
|
|
37208
39177
|
var import_openai = require("openai");
|
|
37209
39178
|
var import_fs5 = __toESM(require("fs"), 1);
|
|
37210
39179
|
var import_node_crypto24 = require("crypto");
|
|
37211
|
-
var
|
|
39180
|
+
var import_api3 = require("@opentelemetry/api");
|
|
37212
39181
|
init_check_record_access();
|
|
37213
39182
|
var import_jszip4 = __toESM(require("jszip"), 1);
|
|
37214
39183
|
|
|
@@ -37323,7 +39292,7 @@ async function seedBundledSkills({
|
|
|
37323
39292
|
}
|
|
37324
39293
|
|
|
37325
39294
|
// src/exulu/routes.ts
|
|
37326
|
-
var
|
|
39295
|
+
var import_ai17 = require("ai");
|
|
37327
39296
|
var import_cookie_parser = __toESM(require("cookie-parser"), 1);
|
|
37328
39297
|
init_convert_context_to_table_definition();
|
|
37329
39298
|
init_context();
|
|
@@ -37331,10 +39300,10 @@ init_statistics2();
|
|
|
37331
39300
|
|
|
37332
39301
|
// src/exulu/suggestions.ts
|
|
37333
39302
|
init_cjs_shims();
|
|
37334
|
-
var
|
|
39303
|
+
var import_ai12 = require("ai");
|
|
37335
39304
|
var import_zod27 = require("zod");
|
|
37336
39305
|
var SUGGESTIONS_SYSTEM_PROMPT = "You generate short follow-up message suggestions for the user. You are NOT continuing the conversation as the assistant \u2014 you are predicting what the user might want to say next. Suggest up to 3 short follow-up questions or messages the user might want to send next. Each suggestion must be written from the user's perspective (first person) and be 12 words or fewer. You MUST submit your answer by calling the `submit_suggestions` tool exactly once. Do not emit any plain text \u2014 only the tool call.";
|
|
37337
|
-
var submitSuggestionsTool = (0,
|
|
39306
|
+
var submitSuggestionsTool = (0, import_ai12.tool)({
|
|
37338
39307
|
description: "Submit the final list of follow-up message suggestions for the user. Must be called exactly once. Each suggestion is written from the user's perspective (first person) and is 12 words or fewer.",
|
|
37339
39308
|
inputSchema: import_zod27.z.object({
|
|
37340
39309
|
suggestions: import_zod27.z.array(import_zod27.z.string()).max(3)
|
|
@@ -37373,12 +39342,12 @@ var generateSuggestions = async ({
|
|
|
37373
39342
|
|
|
37374
39343
|
${SUGGESTIONS_SYSTEM_PROMPT}` : SUGGESTIONS_SYSTEM_PROMPT;
|
|
37375
39344
|
const trimmed = trimMessagesForSuggestions(messages);
|
|
37376
|
-
const { toolCalls, totalUsage } = await (0,
|
|
39345
|
+
const { toolCalls, totalUsage } = await (0, import_ai12.generateText)({
|
|
37377
39346
|
temperature: 0,
|
|
37378
39347
|
model: languageModel,
|
|
37379
39348
|
system,
|
|
37380
39349
|
// ignoreIncompleteToolCalls keeps persisted preliminary tool parts (e.g. a read aborted mid-way) out of model messages.
|
|
37381
|
-
messages: await (0,
|
|
39350
|
+
messages: await (0, import_ai12.convertToModelMessages)(trimmed, {
|
|
37382
39351
|
ignoreIncompleteToolCalls: true
|
|
37383
39352
|
}),
|
|
37384
39353
|
tools: { submit_suggestions: submitSuggestionsTool },
|
|
@@ -37404,17 +39373,17 @@ init_context_budget();
|
|
|
37404
39373
|
|
|
37405
39374
|
// src/exulu/stream-persistence.ts
|
|
37406
39375
|
init_cjs_shims();
|
|
37407
|
-
var
|
|
39376
|
+
var import_ai13 = require("ai");
|
|
37408
39377
|
var persistThroughDisconnect = () => ({
|
|
37409
39378
|
consumeSseStream: ({ stream }) => {
|
|
37410
|
-
void (0,
|
|
39379
|
+
void (0, import_ai13.consumeStream)({ stream });
|
|
37411
39380
|
}
|
|
37412
39381
|
});
|
|
37413
39382
|
|
|
37414
39383
|
// src/exulu/compact-session.ts
|
|
37415
39384
|
init_cjs_shims();
|
|
37416
39385
|
var import_node_crypto22 = require("crypto");
|
|
37417
|
-
var
|
|
39386
|
+
var import_ai14 = require("ai");
|
|
37418
39387
|
init_truncate_tool_output();
|
|
37419
39388
|
init_context_budget();
|
|
37420
39389
|
var CompactionInsufficientError = class extends Error {
|
|
@@ -37474,7 +39443,7 @@ var compactSession = async ({
|
|
|
37474
39443
|
}) => {
|
|
37475
39444
|
const budget = deriveContextBudget(contextWindow);
|
|
37476
39445
|
const rows = await getAgentMessages({ session: sessionID, user: user.id });
|
|
37477
|
-
const all = await (0,
|
|
39446
|
+
const all = await (0, import_ai14.validateUIMessages)({
|
|
37478
39447
|
messages: dropEmptyMessages(rows.map((r) => JSON.parse(r.content)))
|
|
37479
39448
|
});
|
|
37480
39449
|
const history = sliceHistoryAtCheckpoint(all);
|
|
@@ -37491,7 +39460,7 @@ var compactSession = async ({
|
|
|
37491
39460
|
|
|
37492
39461
|
Focus especially on: ${steer.trim()}` : SUMMARY_SYSTEM;
|
|
37493
39462
|
const doSummarize = summarize ?? (async ({ system: sys, prompt, maxOutputTokens }) => {
|
|
37494
|
-
const { text } = await (0,
|
|
39463
|
+
const { text } = await (0, import_ai14.generateText)({
|
|
37495
39464
|
model: languageModel,
|
|
37496
39465
|
system: sys,
|
|
37497
39466
|
prompt,
|
|
@@ -37532,13 +39501,13 @@ ${summary}` }],
|
|
|
37532
39501
|
|
|
37533
39502
|
// src/exulu/request-error.ts
|
|
37534
39503
|
init_cjs_shims();
|
|
37535
|
-
var
|
|
39504
|
+
var import_ai15 = require("ai");
|
|
37536
39505
|
init_context_budget();
|
|
37537
39506
|
function describeRequestError(err4) {
|
|
37538
39507
|
if (err4 instanceof ContextCompactionRequiredError) {
|
|
37539
39508
|
return { status: 413, body: err4.message };
|
|
37540
39509
|
}
|
|
37541
|
-
if (
|
|
39510
|
+
if (import_ai15.TypeValidationError.isInstance(err4)) {
|
|
37542
39511
|
const cause = err4.cause;
|
|
37543
39512
|
const detail = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
|
|
37544
39513
|
return {
|
|
@@ -37549,6 +39518,174 @@ function describeRequestError(err4) {
|
|
|
37549
39518
|
return { status: 500, body: err4 instanceof Error ? err4.message : String(err4) };
|
|
37550
39519
|
}
|
|
37551
39520
|
|
|
39521
|
+
// src/exulu/output-schema.ts
|
|
39522
|
+
init_cjs_shims();
|
|
39523
|
+
var import_ai16 = require("ai");
|
|
39524
|
+
var import_ajv = __toESM(require("ajv"), 1);
|
|
39525
|
+
var import__ = __toESM(require("ajv/dist/2020"), 1);
|
|
39526
|
+
var import_ajv_formats = __toESM(require("ajv-formats"), 1);
|
|
39527
|
+
var OUTPUT_SCHEMA_MAX_BYTES = 32 * 1024;
|
|
39528
|
+
var SUBMIT_TOOL = "submit_output";
|
|
39529
|
+
var MAX_ISSUES = 20;
|
|
39530
|
+
var OutputSchemaInvalidError = class extends Error {
|
|
39531
|
+
constructor(message) {
|
|
39532
|
+
super(message);
|
|
39533
|
+
this.name = "OutputSchemaInvalidError";
|
|
39534
|
+
}
|
|
39535
|
+
};
|
|
39536
|
+
var OutputSchemaMismatchError = class extends Error {
|
|
39537
|
+
constructor(issues, text, usage) {
|
|
39538
|
+
super("The agent's output did not match the output schema.");
|
|
39539
|
+
this.issues = issues;
|
|
39540
|
+
this.text = text;
|
|
39541
|
+
this.usage = usage;
|
|
39542
|
+
this.name = "OutputSchemaMismatchError";
|
|
39543
|
+
}
|
|
39544
|
+
};
|
|
39545
|
+
var toIssues = (errors) => (errors ?? []).slice(0, MAX_ISSUES).map((e) => ({
|
|
39546
|
+
path: e.instancePath || "/",
|
|
39547
|
+
message: e.message ?? e.keyword
|
|
39548
|
+
}));
|
|
39549
|
+
var parseOutputSchema = (raw) => {
|
|
39550
|
+
let schema7 = raw;
|
|
39551
|
+
if (typeof schema7 === "string") {
|
|
39552
|
+
try {
|
|
39553
|
+
schema7 = JSON.parse(schema7);
|
|
39554
|
+
} catch {
|
|
39555
|
+
throw new OutputSchemaInvalidError("outputSchema is not valid JSON.");
|
|
39556
|
+
}
|
|
39557
|
+
}
|
|
39558
|
+
if (!schema7 || typeof schema7 !== "object" || Array.isArray(schema7)) {
|
|
39559
|
+
throw new OutputSchemaInvalidError("outputSchema must be a JSON Schema object.");
|
|
39560
|
+
}
|
|
39561
|
+
const jsonSchemaObject = schema7;
|
|
39562
|
+
if (Buffer.byteLength(JSON.stringify(jsonSchemaObject), "utf8") > OUTPUT_SCHEMA_MAX_BYTES) {
|
|
39563
|
+
throw new OutputSchemaInvalidError(`outputSchema is too large (limit ${OUTPUT_SCHEMA_MAX_BYTES / 1024} KB).`);
|
|
39564
|
+
}
|
|
39565
|
+
if (jsonSchemaObject.type !== "object") {
|
|
39566
|
+
throw new OutputSchemaInvalidError('outputSchema must have "type": "object" at its root.');
|
|
39567
|
+
}
|
|
39568
|
+
const draft07 = typeof jsonSchemaObject.$schema === "string" && jsonSchemaObject.$schema.includes("draft-07");
|
|
39569
|
+
const ajv = new (draft07 ? import_ajv.default : import__.default)({ allErrors: true, strict: false });
|
|
39570
|
+
(0, import_ajv_formats.default)(ajv);
|
|
39571
|
+
let compiled;
|
|
39572
|
+
try {
|
|
39573
|
+
compiled = ajv.compile(jsonSchemaObject);
|
|
39574
|
+
} catch (e) {
|
|
39575
|
+
throw new OutputSchemaInvalidError(
|
|
39576
|
+
`outputSchema is not a usable JSON Schema: ${(e instanceof Error ? e.message : String(e)).slice(0, 300)}`
|
|
39577
|
+
);
|
|
39578
|
+
}
|
|
39579
|
+
return {
|
|
39580
|
+
jsonSchema: jsonSchemaObject,
|
|
39581
|
+
validate: (value) => compiled(value) ? [] : toIssues(compiled.errors)
|
|
39582
|
+
};
|
|
39583
|
+
};
|
|
39584
|
+
var outputSchemaInstructions = (schema7) => `## Required content of your answer
|
|
39585
|
+
After you answer, your answer is transferred into a JSON object with the structure below. Write your answer as usual, but make sure it states the information for every field of that structure. If you could not establish something, say so explicitly instead of guessing.
|
|
39586
|
+
|
|
39587
|
+
${JSON.stringify(schema7.jsonSchema)}`;
|
|
39588
|
+
var SHAPING_SYSTEM = `You transfer an answer that has already been given into a fixed structure by calling the ${SUBMIT_TOOL} tool.
|
|
39589
|
+
- Use only what the answer and the question state. Do not add, estimate or correct anything.
|
|
39590
|
+
- Where the answer has no information for something: leave an optional field or map entry out, or use null or an empty value if the structure allows it. Never fill a gap with an invented value such as 0 or "unknown" just to satisfy the structure.
|
|
39591
|
+
- Keep the language of the answer for free-text fields.`;
|
|
39592
|
+
var shapeOutput = async ({
|
|
39593
|
+
model,
|
|
39594
|
+
system,
|
|
39595
|
+
question,
|
|
39596
|
+
answer,
|
|
39597
|
+
schema: schema7
|
|
39598
|
+
}) => {
|
|
39599
|
+
const usage = { inputTokens: 0, outputTokens: 0 };
|
|
39600
|
+
const basePrompt = `${question ? `Question:
|
|
39601
|
+
${question}
|
|
39602
|
+
|
|
39603
|
+
` : ""}Answer to transfer:
|
|
39604
|
+
${answer}`;
|
|
39605
|
+
const attempt = async (prompt) => {
|
|
39606
|
+
const { toolCalls, totalUsage } = await (0, import_ai16.generateText)({
|
|
39607
|
+
temperature: 0,
|
|
39608
|
+
model,
|
|
39609
|
+
system: system ? `${system}
|
|
39610
|
+
|
|
39611
|
+
---
|
|
39612
|
+
|
|
39613
|
+
${SHAPING_SYSTEM}` : SHAPING_SYSTEM,
|
|
39614
|
+
prompt,
|
|
39615
|
+
tools: {
|
|
39616
|
+
[SUBMIT_TOOL]: (0, import_ai16.tool)({
|
|
39617
|
+
description: "Submit the answer in the required structure.",
|
|
39618
|
+
inputSchema: (0, import_ai16.jsonSchema)(schema7.jsonSchema)
|
|
39619
|
+
})
|
|
39620
|
+
},
|
|
39621
|
+
toolChoice: { type: "tool", toolName: SUBMIT_TOOL },
|
|
39622
|
+
maxRetries: 2
|
|
39623
|
+
});
|
|
39624
|
+
usage.inputTokens += totalUsage?.inputTokens ?? 0;
|
|
39625
|
+
usage.outputTokens += totalUsage?.outputTokens ?? 0;
|
|
39626
|
+
const call2 = toolCalls.find((c) => c.toolName === SUBMIT_TOOL);
|
|
39627
|
+
if (!call2 || call2.invalid) {
|
|
39628
|
+
return { input: void 0, issues: [{ path: "/", message: `the model did not make a usable ${SUBMIT_TOOL} call` }] };
|
|
39629
|
+
}
|
|
39630
|
+
return { input: call2.input, issues: schema7.validate(call2.input) };
|
|
39631
|
+
};
|
|
39632
|
+
const first = await attempt(basePrompt);
|
|
39633
|
+
if (first.issues.length === 0) return { output: first.input, usage };
|
|
39634
|
+
const second = await attempt(
|
|
39635
|
+
`${basePrompt}
|
|
39636
|
+
|
|
39637
|
+
Your previous submission was rejected because it does not match the structure:
|
|
39638
|
+
${first.issues.map((i) => `- ${i.path}: ${i.message}`).join("\n")}
|
|
39639
|
+
|
|
39640
|
+
Previous submission:
|
|
39641
|
+
${JSON.stringify(first.input ?? null).slice(0, 8e3)}
|
|
39642
|
+
|
|
39643
|
+
Submit again with these problems fixed. If a rejected value had no information behind it, leave that field or entry out instead of replacing it with a made-up value.`
|
|
39644
|
+
);
|
|
39645
|
+
if (second.issues.length === 0) return { output: second.input, usage };
|
|
39646
|
+
throw new OutputSchemaMismatchError(second.issues, answer, usage);
|
|
39647
|
+
};
|
|
39648
|
+
var readOutputSchema = (raw, stream) => {
|
|
39649
|
+
if (raw === void 0 || raw === null || raw === "") return {};
|
|
39650
|
+
if (stream) {
|
|
39651
|
+
return {
|
|
39652
|
+
error: {
|
|
39653
|
+
error: "output_schema_not_streamable",
|
|
39654
|
+
message: "outputSchema cannot be combined with streaming. Send the header stream: false."
|
|
39655
|
+
}
|
|
39656
|
+
};
|
|
39657
|
+
}
|
|
39658
|
+
try {
|
|
39659
|
+
return { schema: parseOutputSchema(raw) };
|
|
39660
|
+
} catch (e) {
|
|
39661
|
+
if (e instanceof OutputSchemaInvalidError) return { error: { error: "output_schema_invalid", message: e.message } };
|
|
39662
|
+
throw e;
|
|
39663
|
+
}
|
|
39664
|
+
};
|
|
39665
|
+
var messageText = (message) => {
|
|
39666
|
+
if (typeof message === "string") return message;
|
|
39667
|
+
if (!message || typeof message !== "object") return "";
|
|
39668
|
+
const m = message;
|
|
39669
|
+
if (Array.isArray(m.parts)) {
|
|
39670
|
+
return m.parts.filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n");
|
|
39671
|
+
}
|
|
39672
|
+
return typeof m.content === "string" ? m.content : "";
|
|
39673
|
+
};
|
|
39674
|
+
var respondWithOutputSchema = async ({
|
|
39675
|
+
onUsage,
|
|
39676
|
+
...args
|
|
39677
|
+
}) => {
|
|
39678
|
+
try {
|
|
39679
|
+
const { output, usage } = await shapeOutput(args);
|
|
39680
|
+
await onUsage?.(usage);
|
|
39681
|
+
return { status: 200, body: output };
|
|
39682
|
+
} catch (e) {
|
|
39683
|
+
if (!(e instanceof OutputSchemaMismatchError)) throw e;
|
|
39684
|
+
await onUsage?.(e.usage);
|
|
39685
|
+
return { status: 422, body: { error: "output_schema_mismatch", message: e.message, issues: e.issues, text: e.text } };
|
|
39686
|
+
}
|
|
39687
|
+
};
|
|
39688
|
+
|
|
37552
39689
|
// src/exulu/memory/recalled-metadata.ts
|
|
37553
39690
|
init_cjs_shims();
|
|
37554
39691
|
function recalledMemoriesMetadata({ recall, agent, isGuest }) {
|
|
@@ -38352,7 +40489,7 @@ function decideUploadSign(args) {
|
|
|
38352
40489
|
}
|
|
38353
40490
|
return { ok: true };
|
|
38354
40491
|
}
|
|
38355
|
-
var
|
|
40492
|
+
var UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
38356
40493
|
function makeLoadAuthedProject(deps) {
|
|
38357
40494
|
return async (req, res, projectId, want) => {
|
|
38358
40495
|
const authResult = await deps.authenticate(req);
|
|
@@ -38360,7 +40497,7 @@ function makeLoadAuthedProject(deps) {
|
|
|
38360
40497
|
res.status(authResult.code || 401).json({ detail: authResult.message });
|
|
38361
40498
|
return null;
|
|
38362
40499
|
}
|
|
38363
|
-
if (!
|
|
40500
|
+
if (!UUID_RE3.test(projectId)) {
|
|
38364
40501
|
res.status(404).json({ detail: `Project ${projectId} not found.` });
|
|
38365
40502
|
return null;
|
|
38366
40503
|
}
|
|
@@ -38659,9 +40796,9 @@ init_cjs_shims();
|
|
|
38659
40796
|
init_config3();
|
|
38660
40797
|
function toolConfigOf(agent) {
|
|
38661
40798
|
const tools = agent?.tools ?? [];
|
|
38662
|
-
const
|
|
40799
|
+
const tool5 = tools.find((t) => t?.id === "agentic_context_search");
|
|
38663
40800
|
const out = {};
|
|
38664
|
-
for (const entry of
|
|
40801
|
+
for (const entry of tool5?.config ?? []) if (entry?.name) out[entry.name] = entry.variable;
|
|
38665
40802
|
return out;
|
|
38666
40803
|
}
|
|
38667
40804
|
function hasNoToolConfig(raw) {
|
|
@@ -38674,7 +40811,7 @@ function pipelineConfigFor(agent) {
|
|
|
38674
40811
|
// ee/claim-check/routes.ts
|
|
38675
40812
|
var CLAIM_CHECK_PATH = "/claims/check";
|
|
38676
40813
|
var CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
|
|
38677
|
-
var
|
|
40814
|
+
var UUID_RE4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
38678
40815
|
function hasNumericUserId(user) {
|
|
38679
40816
|
return Boolean(user?.id) && Number.isFinite(Number(user?.id));
|
|
38680
40817
|
}
|
|
@@ -38862,7 +40999,7 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
38862
40999
|
});
|
|
38863
41000
|
return;
|
|
38864
41001
|
}
|
|
38865
|
-
if (deps.findClaimCheck && body.session && body.messageId &&
|
|
41002
|
+
if (deps.findClaimCheck && body.session && body.messageId && UUID_RE4.test(body.session)) {
|
|
38866
41003
|
try {
|
|
38867
41004
|
const stored = await deps.findClaimCheck({
|
|
38868
41005
|
session: body.session,
|
|
@@ -38983,7 +41120,7 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
38983
41120
|
if (deadline) clearTimeout(deadline);
|
|
38984
41121
|
deps.limiter.release();
|
|
38985
41122
|
}
|
|
38986
|
-
if (completedResult && body.session && body.messageId &&
|
|
41123
|
+
if (completedResult && body.session && body.messageId && UUID_RE4.test(body.session)) {
|
|
38987
41124
|
if (!deps.saveClaimCheck) {
|
|
38988
41125
|
console.error(
|
|
38989
41126
|
"[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload."
|
|
@@ -39008,7 +41145,7 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
39008
41145
|
return;
|
|
39009
41146
|
}
|
|
39010
41147
|
const session = req.params.session ?? "";
|
|
39011
|
-
if (!
|
|
41148
|
+
if (!UUID_RE4.test(session)) {
|
|
39012
41149
|
res.status(400).json({ detail: "session must be a uuid." });
|
|
39013
41150
|
return;
|
|
39014
41151
|
}
|
|
@@ -39034,13 +41171,13 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
39034
41171
|
|
|
39035
41172
|
// ee/claim-check/rate-limit.ts
|
|
39036
41173
|
init_cjs_shims();
|
|
39037
|
-
var
|
|
41174
|
+
var DEFAULTS3 = { perMinute: 30, perHour: 300, maxInFlight: 20 };
|
|
39038
41175
|
var MAX_TRACKED_USERS = 1e4;
|
|
39039
|
-
var
|
|
41176
|
+
var HOUR_MS3 = 36e5;
|
|
39040
41177
|
function evict(windows3, now) {
|
|
39041
41178
|
if (windows3.size <= MAX_TRACKED_USERS) return;
|
|
39042
41179
|
for (const [key, value] of windows3) {
|
|
39043
|
-
if (now - value.lastSeen >=
|
|
41180
|
+
if (now - value.lastSeen >= HOUR_MS3) windows3.delete(key);
|
|
39044
41181
|
}
|
|
39045
41182
|
if (windows3.size <= MAX_TRACKED_USERS) return;
|
|
39046
41183
|
const sorted = [...windows3.entries()].sort((a, b) => a[1].lastSeen - b[1].lastSeen);
|
|
@@ -39050,7 +41187,7 @@ function evict(windows3, now) {
|
|
|
39050
41187
|
}
|
|
39051
41188
|
}
|
|
39052
41189
|
function claimCheckRateLimiter(opts = {}) {
|
|
39053
|
-
const { perMinute, perHour, maxInFlight } = { ...
|
|
41190
|
+
const { perMinute, perHour, maxInFlight } = { ...DEFAULTS3, ...opts };
|
|
39054
41191
|
const windows3 = /* @__PURE__ */ new Map();
|
|
39055
41192
|
let inFlight3 = 0;
|
|
39056
41193
|
return {
|
|
@@ -39277,14 +41414,14 @@ function buildWindows(sentences, preceding, following) {
|
|
|
39277
41414
|
init_cjs_shims();
|
|
39278
41415
|
init_query_preprocessing();
|
|
39279
41416
|
var MAX_CHARS_PER_SOURCE = 6e4;
|
|
39280
|
-
var
|
|
41417
|
+
var DEFAULTS4 = { passageChars: 1200, overlapChars: 200, maxCharsPerSource: MAX_CHARS_PER_SOURCE };
|
|
39281
41418
|
function tokenize(text) {
|
|
39282
41419
|
if (!text.trim()) return [];
|
|
39283
41420
|
const { processed } = preprocessQuery(text, { enableStemming: true, detectLanguage: true, silent: true });
|
|
39284
41421
|
return processed.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t) => t.length >= 3);
|
|
39285
41422
|
}
|
|
39286
41423
|
function indexSourcesWithLimits(sources, opts = {}) {
|
|
39287
|
-
const { passageChars, overlapChars, maxCharsPerSource } = { ...
|
|
41424
|
+
const { passageChars, overlapChars, maxCharsPerSource } = { ...DEFAULTS4, ...opts };
|
|
39288
41425
|
const passages = [];
|
|
39289
41426
|
const documentFrequency = /* @__PURE__ */ new Map();
|
|
39290
41427
|
const truncation = { sources: 0, droppedChars: 0, names: [] };
|
|
@@ -39962,9 +42099,9 @@ var chunk = (items, size) => {
|
|
|
39962
42099
|
};
|
|
39963
42100
|
async function runBatched(batches, label, state, call2) {
|
|
39964
42101
|
const good = [];
|
|
39965
|
-
let
|
|
39966
|
-
for (let round = 0;
|
|
39967
|
-
const settled = await mapWithConcurrency2(
|
|
42102
|
+
let pending2 = batches;
|
|
42103
|
+
for (let round = 0; pending2.length > 0; round += 1) {
|
|
42104
|
+
const settled = await mapWithConcurrency2(pending2, MAX_IN_FLIGHT, async (windows3) => call2(windows3));
|
|
39968
42105
|
const failed = [];
|
|
39969
42106
|
settled.forEach((outcome, i) => {
|
|
39970
42107
|
if (outcome.status === "fulfilled") {
|
|
@@ -39972,13 +42109,13 @@ async function runBatched(batches, label, state, call2) {
|
|
|
39972
42109
|
state.usage = addUsage(state.usage, outcome.value.usage);
|
|
39973
42110
|
return;
|
|
39974
42111
|
}
|
|
39975
|
-
failed.push(
|
|
42112
|
+
failed.push(pending2[i]);
|
|
39976
42113
|
});
|
|
39977
42114
|
if (failed.length === 0) return good;
|
|
39978
|
-
if (round === 0 && failed.length >= 2 && failed.length /
|
|
42115
|
+
if (round === 0 && failed.length >= 2 && failed.length / pending2.length > STAGE_FAILURE_ABORT) {
|
|
39979
42116
|
state.partial = true;
|
|
39980
42117
|
state.notes.push(
|
|
39981
|
-
`${label}: aborted after ${failed.length} of ${
|
|
42118
|
+
`${label}: aborted after ${failed.length} of ${pending2.length} calls failed; remaining sentences are not_checked`
|
|
39982
42119
|
);
|
|
39983
42120
|
for (const batch of failed) markNotChecked(state, batch, `${label} aborted`);
|
|
39984
42121
|
return good;
|
|
@@ -39996,7 +42133,7 @@ async function runBatched(batches, label, state, call2) {
|
|
|
39996
42133
|
batch.length === 1 ? `${label} failed for this sentence` : round === 0 ? `${label} failed for this batch of ${batch.length} sentences` : `${label} failed after bisect`
|
|
39997
42134
|
);
|
|
39998
42135
|
}
|
|
39999
|
-
|
|
42136
|
+
pending2 = next;
|
|
40000
42137
|
}
|
|
40001
42138
|
return good;
|
|
40002
42139
|
}
|
|
@@ -40808,7 +42945,7 @@ init_cjs_shims();
|
|
|
40808
42945
|
init_tags();
|
|
40809
42946
|
init_activity_client();
|
|
40810
42947
|
init_budget_service();
|
|
40811
|
-
var
|
|
42948
|
+
var DAY_MS5 = 24 * 60 * 60 * 1e3;
|
|
40812
42949
|
var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
40813
42950
|
var MAX_WINDOW_DAYS = 92;
|
|
40814
42951
|
var DEFAULT_WINDOW_DAYS = 30;
|
|
@@ -40820,7 +42957,7 @@ var parseDateParam = (raw) => {
|
|
|
40820
42957
|
if (Number.isNaN(dt.getTime())) return null;
|
|
40821
42958
|
return dt.toISOString().slice(0, 10);
|
|
40822
42959
|
};
|
|
40823
|
-
var ymdShift = (ymd2, days) => new Date(Date.parse(ymd2) + days *
|
|
42960
|
+
var ymdShift = (ymd2, days) => new Date(Date.parse(ymd2) + days * DAY_MS5).toISOString().slice(0, 10);
|
|
40824
42961
|
function resolveUsageWindow(startRaw, endRaw, now = /* @__PURE__ */ new Date()) {
|
|
40825
42962
|
const start = parseDateParam(startRaw);
|
|
40826
42963
|
const end = parseDateParam(endRaw);
|
|
@@ -40828,7 +42965,7 @@ function resolveUsageWindow(startRaw, endRaw, now = /* @__PURE__ */ new Date())
|
|
|
40828
42965
|
const end_date = end ?? now.toISOString().slice(0, 10);
|
|
40829
42966
|
let start_date = start ?? ymdShift(end_date, -(DEFAULT_WINDOW_DAYS - 1));
|
|
40830
42967
|
if (start_date > end_date) return null;
|
|
40831
|
-
const days = Math.round((Date.parse(end_date) - Date.parse(start_date)) /
|
|
42968
|
+
const days = Math.round((Date.parse(end_date) - Date.parse(start_date)) / DAY_MS5) + 1;
|
|
40832
42969
|
if (days > MAX_WINDOW_DAYS) {
|
|
40833
42970
|
start_date = ymdShift(end_date, -(MAX_WINDOW_DAYS - 1));
|
|
40834
42971
|
}
|
|
@@ -40905,7 +43042,7 @@ async function getMyUsageView(userId, window) {
|
|
|
40905
43042
|
const tag = budgetTagFor("user", userId);
|
|
40906
43043
|
if (!tag) return null;
|
|
40907
43044
|
const daysInRange = Math.round(
|
|
40908
|
-
(Date.parse(window.end_date) - Date.parse(window.start_date)) /
|
|
43045
|
+
(Date.parse(window.end_date) - Date.parse(window.start_date)) / DAY_MS5
|
|
40909
43046
|
) + 1;
|
|
40910
43047
|
const raw = await getTagDailyActivity({
|
|
40911
43048
|
startDate: window.start_date,
|
|
@@ -40926,28 +43063,146 @@ async function getMyUsageView(userId, window) {
|
|
|
40926
43063
|
|
|
40927
43064
|
// src/exulu/routes.ts
|
|
40928
43065
|
var import_multer = __toESM(require("multer"), 1);
|
|
40929
|
-
init_credential_store();
|
|
40930
43066
|
|
|
40931
|
-
// src/
|
|
43067
|
+
// src/exulu/channels/webhook.ts
|
|
40932
43068
|
init_cjs_shims();
|
|
40933
|
-
|
|
40934
|
-
|
|
40935
|
-
|
|
40936
|
-
|
|
40937
|
-
|
|
40938
|
-
|
|
40939
|
-
|
|
40940
|
-
|
|
40941
|
-
|
|
40942
|
-
|
|
40943
|
-
|
|
43069
|
+
var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
|
|
43070
|
+
var LOG_PREFIX3 = "[EXULU-CHANNEL]";
|
|
43071
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
43072
|
+
var RATE_WINDOW_MS2 = 6e4;
|
|
43073
|
+
var RATE_MAX_REQUESTS2 = 300;
|
|
43074
|
+
var rateWindowStart2 = 0;
|
|
43075
|
+
var rateWindowCount2 = 0;
|
|
43076
|
+
var channelWebhookRateLimitExceeded = (now = Date.now()) => {
|
|
43077
|
+
if (now - rateWindowStart2 >= RATE_WINDOW_MS2) {
|
|
43078
|
+
rateWindowStart2 = now;
|
|
43079
|
+
rateWindowCount2 = 0;
|
|
43080
|
+
}
|
|
43081
|
+
rateWindowCount2 += 1;
|
|
43082
|
+
return rateWindowCount2 > RATE_MAX_REQUESTS2;
|
|
43083
|
+
};
|
|
43084
|
+
var toWebRequest = (req, rawBody) => {
|
|
43085
|
+
const headers = new Headers();
|
|
43086
|
+
for (const [name, value] of Object.entries(req.headers ?? {})) {
|
|
43087
|
+
if (value === void 0) continue;
|
|
43088
|
+
for (const v of Array.isArray(value) ? value : [value]) headers.append(name, String(v));
|
|
43089
|
+
}
|
|
43090
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
43091
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
43092
|
+
return new Request(`http://localhost${req.originalUrl ?? "/"}`, {
|
|
43093
|
+
method,
|
|
43094
|
+
headers,
|
|
43095
|
+
body: hasBody ? new Uint8Array(rawBody) : void 0
|
|
43096
|
+
});
|
|
43097
|
+
};
|
|
43098
|
+
var settleWithin = async (tasks, ms) => {
|
|
43099
|
+
let timer3;
|
|
43100
|
+
try {
|
|
43101
|
+
return await Promise.race([
|
|
43102
|
+
Promise.allSettled(tasks),
|
|
43103
|
+
new Promise((resolve10) => {
|
|
43104
|
+
timer3 = setTimeout(() => resolve10(null), ms);
|
|
43105
|
+
})
|
|
43106
|
+
]);
|
|
43107
|
+
} finally {
|
|
43108
|
+
clearTimeout(timer3);
|
|
43109
|
+
}
|
|
43110
|
+
};
|
|
43111
|
+
var writeResponse = async (res, response) => {
|
|
43112
|
+
const body = Buffer.from(await response.arrayBuffer());
|
|
43113
|
+
res.status(response.status);
|
|
43114
|
+
response.headers.forEach((value, name) => {
|
|
43115
|
+
if (name.toLowerCase() !== "content-length") res.setHeader(name, value);
|
|
43116
|
+
});
|
|
43117
|
+
res.send(body);
|
|
43118
|
+
};
|
|
43119
|
+
var createChannelWebhookHandler = (deps) => async (req, res) => {
|
|
43120
|
+
if (deps.rateLimitExceeded()) {
|
|
43121
|
+
res.status(429).json({ detail: "Too many requests." });
|
|
43122
|
+
return;
|
|
43123
|
+
}
|
|
43124
|
+
if (!deps.entitled()) {
|
|
43125
|
+
res.status(503).json({ detail: "Channels are not available." });
|
|
43126
|
+
return;
|
|
43127
|
+
}
|
|
43128
|
+
const channelId = String(req.params?.channelId ?? "");
|
|
43129
|
+
if (!UUID2.test(channelId)) {
|
|
43130
|
+
res.status(404).json({ detail: "not found" });
|
|
43131
|
+
return;
|
|
43132
|
+
}
|
|
43133
|
+
let row;
|
|
43134
|
+
try {
|
|
43135
|
+
row = await deps.loadChannel(channelId);
|
|
43136
|
+
} catch (error) {
|
|
43137
|
+
console.error(`${LOG_PREFIX3} webhook channel lookup failed`, safeError(error));
|
|
43138
|
+
res.status(503).json({ detail: "temporarily unavailable" });
|
|
43139
|
+
return;
|
|
43140
|
+
}
|
|
43141
|
+
if (!row || !row.enabled || row.type !== "whatsapp") {
|
|
43142
|
+
res.status(404).json({ detail: "not found" });
|
|
43143
|
+
return;
|
|
43144
|
+
}
|
|
43145
|
+
let transport;
|
|
43146
|
+
try {
|
|
43147
|
+
if (!await deps.redisAvailable()) {
|
|
43148
|
+
res.status(503).json({ detail: "temporarily unavailable" });
|
|
43149
|
+
return;
|
|
40944
43150
|
}
|
|
40945
|
-
|
|
43151
|
+
transport = await deps.transportFor(row);
|
|
43152
|
+
} catch (error) {
|
|
43153
|
+
console.error(`${LOG_PREFIX3} webhook setup failed on channel ${channelId}`, safeError(error));
|
|
43154
|
+
res.status(503).json({ detail: "temporarily unavailable" });
|
|
43155
|
+
return;
|
|
40946
43156
|
}
|
|
40947
|
-
|
|
43157
|
+
if (!transport) {
|
|
43158
|
+
console.error(`${LOG_PREFIX3} channel ${channelId} has no usable credentials`);
|
|
43159
|
+
res.status(503).json({ detail: "temporarily unavailable" });
|
|
43160
|
+
return;
|
|
43161
|
+
}
|
|
43162
|
+
try {
|
|
43163
|
+
const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
|
|
43164
|
+
const tasks = [];
|
|
43165
|
+
const response = await transport.handleWebhook(toWebRequest(req, rawBody), {
|
|
43166
|
+
waitUntil: (task) => {
|
|
43167
|
+
tasks.push(task);
|
|
43168
|
+
}
|
|
43169
|
+
});
|
|
43170
|
+
if (tasks.length > 0) {
|
|
43171
|
+
const settled = await settleWithin(tasks, WEBHOOK_BACKGROUND_WAIT_MS);
|
|
43172
|
+
if (settled === null) {
|
|
43173
|
+
console.warn(`${LOG_PREFIX3} channel ${channelId} answered before its message handling finished`);
|
|
43174
|
+
} else if (settled.some((s) => s.status === "rejected")) {
|
|
43175
|
+
console.error(`${LOG_PREFIX3} message handling failed on channel ${channelId}`);
|
|
43176
|
+
}
|
|
43177
|
+
}
|
|
43178
|
+
await writeResponse(res, response);
|
|
43179
|
+
} catch (error) {
|
|
43180
|
+
console.error(`${LOG_PREFIX3} webhook handling failed on channel ${channelId}`, safeError(error));
|
|
43181
|
+
if (!res.headersSent) res.status(500).json({ detail: "internal error" });
|
|
43182
|
+
return;
|
|
43183
|
+
}
|
|
43184
|
+
try {
|
|
43185
|
+
deps.purgeChatState?.();
|
|
43186
|
+
} catch (error) {
|
|
43187
|
+
console.error(`${LOG_PREFIX3} chat state purge could not be started`, safeError(error));
|
|
43188
|
+
}
|
|
43189
|
+
};
|
|
43190
|
+
|
|
43191
|
+
// src/exulu/channels/queue.ts
|
|
43192
|
+
init_cjs_shims();
|
|
43193
|
+
var CHANNEL_QUEUE_CONCURRENCY = { worker: 5, queue: 10 };
|
|
43194
|
+
var CHANNEL_QUEUE_RATELIMIT = 10;
|
|
43195
|
+
function registerChannelQueue() {
|
|
43196
|
+
return queues.register(
|
|
43197
|
+
global_queues.channel_inbound,
|
|
43198
|
+
CHANNEL_QUEUE_CONCURRENCY,
|
|
43199
|
+
CHANNEL_QUEUE_RATELIMIT,
|
|
43200
|
+
CHANNEL_JOB_TIMEOUT_SECONDS
|
|
43201
|
+
);
|
|
40948
43202
|
}
|
|
40949
43203
|
|
|
40950
43204
|
// src/exulu/routes.ts
|
|
43205
|
+
init_credential_store();
|
|
40951
43206
|
init_singleton();
|
|
40952
43207
|
init_entitlements();
|
|
40953
43208
|
init_create_sandbox();
|
|
@@ -41218,87 +43473,51 @@ init_shared_artifacts();
|
|
|
41218
43473
|
init_session_files();
|
|
41219
43474
|
init_session_file_adopt();
|
|
41220
43475
|
|
|
41221
|
-
// src/exulu/public-agents.ts
|
|
41222
|
-
init_cjs_shims();
|
|
41223
|
-
init_shared_artifacts();
|
|
41224
|
-
var publicAgentView = (row, slug) => ({
|
|
41225
|
-
id: row.id,
|
|
41226
|
-
name: row.name ?? "",
|
|
41227
|
-
description: row.description ?? "",
|
|
41228
|
-
image: row.image ?? null,
|
|
41229
|
-
welcomemessage: row.welcomemessage ?? "",
|
|
41230
|
-
slug,
|
|
41231
|
-
guest_auth_mode: row.guest_auth_mode || "regular",
|
|
41232
|
-
guest_has_cover: !!row.guest_cover_image,
|
|
41233
|
-
guest_has_idle_animation: !!row.animation_idle,
|
|
41234
|
-
guest_has_responding_animation: !!row.animation_responding
|
|
41235
|
-
});
|
|
41236
|
-
var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
|
|
41237
|
-
if (agent.guest_access) {
|
|
41238
|
-
if (userId != null) return { allowed: true, via: "guest" };
|
|
41239
|
-
const mode = agent.guest_auth_mode || "regular";
|
|
41240
|
-
if (mode === "public") return { allowed: true, via: "guest" };
|
|
41241
|
-
if (mode === "password") {
|
|
41242
|
-
if (agent.guest_password_hash && guestPassword) {
|
|
41243
|
-
const ok = await verifySharePassword(guestPassword, agent.guest_password_hash);
|
|
41244
|
-
if (ok) return { allowed: true, via: "guest" };
|
|
41245
|
-
return { allowed: false, status: 401, message: "Incorrect password." };
|
|
41246
|
-
}
|
|
41247
|
-
return { allowed: false, status: 401, message: "Password required." };
|
|
41248
|
-
}
|
|
41249
|
-
return { allowed: false, status: 401, message: "Authentication required." };
|
|
41250
|
-
}
|
|
41251
|
-
if (userId == null && agent.rights_mode === "public") {
|
|
41252
|
-
return { allowed: true, via: "rbac-public" };
|
|
41253
|
-
}
|
|
41254
|
-
return { allowed: false, status: 401, message: "Authentication required." };
|
|
41255
|
-
};
|
|
41256
|
-
|
|
41257
43476
|
// src/exulu/guest-rate-limit.ts
|
|
41258
43477
|
init_cjs_shims();
|
|
41259
|
-
var
|
|
41260
|
-
var
|
|
41261
|
-
var
|
|
41262
|
-
var
|
|
43478
|
+
var MINUTE_MS2 = 6e4;
|
|
43479
|
+
var HOUR_MS4 = 36e5;
|
|
43480
|
+
var perMinuteLimit2 = () => parseInt(process.env.EXULU_GUEST_RATE_PER_MINUTE || "10", 10);
|
|
43481
|
+
var perHourLimit2 = () => parseInt(process.env.EXULU_GUEST_RATE_PER_HOUR || "60", 10);
|
|
41263
43482
|
var maxMessageChars = () => parseInt(process.env.EXULU_GUEST_MAX_MESSAGE_CHARS || "8000", 10);
|
|
41264
43483
|
var maxTotalChars = () => parseInt(process.env.EXULU_GUEST_MAX_TOTAL_CHARS || "32000", 10);
|
|
41265
43484
|
var MAX_PART_COUNT = 100;
|
|
41266
|
-
var
|
|
43485
|
+
var windows2 = /* @__PURE__ */ new Map();
|
|
41267
43486
|
var guestRateLimitExceeded = (ip, now = Date.now()) => {
|
|
41268
|
-
const state =
|
|
43487
|
+
const state = windows2.get(ip) ?? {
|
|
41269
43488
|
minuteStart: now,
|
|
41270
43489
|
minuteCount: 0,
|
|
41271
43490
|
hourStart: now,
|
|
41272
43491
|
hourCount: 0,
|
|
41273
43492
|
lastSeen: now
|
|
41274
43493
|
};
|
|
41275
|
-
if (now - state.minuteStart >=
|
|
43494
|
+
if (now - state.minuteStart >= MINUTE_MS2) {
|
|
41276
43495
|
state.minuteStart = now;
|
|
41277
43496
|
state.minuteCount = 0;
|
|
41278
43497
|
}
|
|
41279
|
-
if (now - state.hourStart >=
|
|
43498
|
+
if (now - state.hourStart >= HOUR_MS4) {
|
|
41280
43499
|
state.hourStart = now;
|
|
41281
43500
|
state.hourCount = 0;
|
|
41282
43501
|
}
|
|
41283
43502
|
state.minuteCount += 1;
|
|
41284
43503
|
state.hourCount += 1;
|
|
41285
43504
|
state.lastSeen = now;
|
|
41286
|
-
|
|
41287
|
-
if (
|
|
41288
|
-
for (const [key, value] of
|
|
41289
|
-
if (now - value.lastSeen >=
|
|
43505
|
+
windows2.set(ip, state);
|
|
43506
|
+
if (windows2.size > 1e4) {
|
|
43507
|
+
for (const [key, value] of windows2) {
|
|
43508
|
+
if (now - value.lastSeen >= HOUR_MS4) windows2.delete(key);
|
|
41290
43509
|
}
|
|
41291
|
-
if (
|
|
41292
|
-
const sorted = [...
|
|
43510
|
+
if (windows2.size > 1e4) {
|
|
43511
|
+
const sorted = [...windows2.entries()].sort(
|
|
41293
43512
|
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
41294
43513
|
);
|
|
41295
43514
|
for (const [key] of sorted) {
|
|
41296
|
-
if (
|
|
41297
|
-
|
|
43515
|
+
if (windows2.size <= 1e4) break;
|
|
43516
|
+
windows2.delete(key);
|
|
41298
43517
|
}
|
|
41299
43518
|
}
|
|
41300
43519
|
}
|
|
41301
|
-
return state.minuteCount >
|
|
43520
|
+
return state.minuteCount > perMinuteLimit2() || state.hourCount > perHourLimit2();
|
|
41302
43521
|
};
|
|
41303
43522
|
var partsTooLong = (parts) => Array.isArray(parts) && parts.some(
|
|
41304
43523
|
(p) => typeof p?.text === "string" && p.text.length > maxMessageChars()
|
|
@@ -41341,69 +43560,6 @@ var extractClientIp = (req) => {
|
|
|
41341
43560
|
return req.ip || req.socket?.remoteAddress || "unknown";
|
|
41342
43561
|
};
|
|
41343
43562
|
|
|
41344
|
-
// src/exulu/external-rate-limit.ts
|
|
41345
|
-
init_cjs_shims();
|
|
41346
|
-
var MINUTE_MS2 = 6e4;
|
|
41347
|
-
var HOUR_MS4 = 36e5;
|
|
41348
|
-
var perMinuteLimit2 = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
|
|
41349
|
-
var perHourLimit2 = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
|
|
41350
|
-
var windows2 = /* @__PURE__ */ new Map();
|
|
41351
|
-
var externalRateLimitExceeded = (userId, now = Date.now()) => {
|
|
41352
|
-
const state = windows2.get(userId) ?? {
|
|
41353
|
-
minuteStart: now,
|
|
41354
|
-
minuteCount: 0,
|
|
41355
|
-
hourStart: now,
|
|
41356
|
-
hourCount: 0,
|
|
41357
|
-
lastSeen: now
|
|
41358
|
-
};
|
|
41359
|
-
if (now - state.minuteStart >= MINUTE_MS2) {
|
|
41360
|
-
state.minuteStart = now;
|
|
41361
|
-
state.minuteCount = 0;
|
|
41362
|
-
}
|
|
41363
|
-
if (now - state.hourStart >= HOUR_MS4) {
|
|
41364
|
-
state.hourStart = now;
|
|
41365
|
-
state.hourCount = 0;
|
|
41366
|
-
}
|
|
41367
|
-
state.minuteCount += 1;
|
|
41368
|
-
state.hourCount += 1;
|
|
41369
|
-
state.lastSeen = now;
|
|
41370
|
-
windows2.set(userId, state);
|
|
41371
|
-
if (windows2.size > 1e4) {
|
|
41372
|
-
for (const [key, value] of windows2) {
|
|
41373
|
-
if (now - value.lastSeen >= HOUR_MS4) windows2.delete(key);
|
|
41374
|
-
}
|
|
41375
|
-
if (windows2.size > 1e4) {
|
|
41376
|
-
const sorted = [...windows2.entries()].sort(
|
|
41377
|
-
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
41378
|
-
);
|
|
41379
|
-
for (const [key] of sorted) {
|
|
41380
|
-
if (windows2.size <= 1e4) break;
|
|
41381
|
-
windows2.delete(key);
|
|
41382
|
-
}
|
|
41383
|
-
}
|
|
41384
|
-
}
|
|
41385
|
-
const minuteLimitExceeded = state.minuteCount > perMinuteLimit2();
|
|
41386
|
-
const hourLimitExceeded = state.hourCount > perHourLimit2();
|
|
41387
|
-
const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
|
|
41388
|
-
if (limitExceeded) {
|
|
41389
|
-
const limits = {
|
|
41390
|
-
perMinute: perMinuteLimit2(),
|
|
41391
|
-
perHour: perHourLimit2()
|
|
41392
|
-
};
|
|
41393
|
-
const current = {
|
|
41394
|
-
minute: state.minuteCount,
|
|
41395
|
-
hour: state.hourCount
|
|
41396
|
-
};
|
|
41397
|
-
console.warn(
|
|
41398
|
-
`[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
|
|
41399
|
-
);
|
|
41400
|
-
}
|
|
41401
|
-
return limitExceeded;
|
|
41402
|
-
};
|
|
41403
|
-
var isExternalUser = (user) => {
|
|
41404
|
-
return user?.role?.name === "external";
|
|
41405
|
-
};
|
|
41406
|
-
|
|
41407
43563
|
// src/exulu/routes.ts
|
|
41408
43564
|
init_skill_access();
|
|
41409
43565
|
|
|
@@ -41596,6 +43752,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
41596
43752
|
console.log("[EXULU] tracer configured", tracer);
|
|
41597
43753
|
}
|
|
41598
43754
|
app.use("/webhooks/routine", import_express3.default.raw({ type: () => true, limit: "30mb" }));
|
|
43755
|
+
app.use("/webhooks/whatsapp", import_express3.default.raw({ type: () => true, limit: "5mb" }));
|
|
41599
43756
|
app.use(
|
|
41600
43757
|
import_express3.default.json({
|
|
41601
43758
|
limit: REQUEST_SIZE_LIMIT,
|
|
@@ -41839,6 +43996,21 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
41839
43996
|
rateLimitExceeded: routineWebhookRateLimitExceeded
|
|
41840
43997
|
});
|
|
41841
43998
|
app.post("/webhooks/routine/:secret", routineWebhookHandler);
|
|
43999
|
+
const channelWebhookHandler = createChannelWebhookHandler(
|
|
44000
|
+
createChannelWebhookDeps({
|
|
44001
|
+
entitled: () => {
|
|
44002
|
+
const license = checkLicense();
|
|
44003
|
+
return license["channels"] === true && license["queues"] === true;
|
|
44004
|
+
},
|
|
44005
|
+
rateLimitExceeded: () => channelWebhookRateLimitExceeded(),
|
|
44006
|
+
getDb: async () => (await postgresClient()).db,
|
|
44007
|
+
getRedis: async () => (await redisClient()).client,
|
|
44008
|
+
loadAgent: (id) => exuluApp.get().agent(id),
|
|
44009
|
+
enqueue: async (job) => enqueueChannelMessage((await registerChannelQueue().use()).queue, job)
|
|
44010
|
+
})
|
|
44011
|
+
);
|
|
44012
|
+
app.get("/webhooks/whatsapp/:channelId", channelWebhookHandler);
|
|
44013
|
+
app.post("/webhooks/whatsapp/:channelId", channelWebhookHandler);
|
|
41842
44014
|
app.get("/ping", async (req, res) => {
|
|
41843
44015
|
const authenticationResult = await requestValidators.authenticate(req);
|
|
41844
44016
|
if (!authenticationResult.user?.id) {
|
|
@@ -42037,6 +44209,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
42037
44209
|
const contextWindow = await resolveContextWindow({
|
|
42038
44210
|
modelId: resolved.model.id
|
|
42039
44211
|
});
|
|
44212
|
+
const outputSchemaRequest = readOutputSchema(req.body?.outputSchema, headers.stream);
|
|
44213
|
+
if (outputSchemaRequest.error) {
|
|
44214
|
+
res.status(400).json(outputSchemaRequest.error);
|
|
44215
|
+
return;
|
|
44216
|
+
}
|
|
44217
|
+
const outputSchema = outputSchemaRequest.schema;
|
|
42040
44218
|
if (!!headers.stream) {
|
|
42041
44219
|
const statistics = {
|
|
42042
44220
|
label: agent.name,
|
|
@@ -42172,7 +44350,7 @@ ${customInstructions}` : agent.instructions,
|
|
|
42172
44350
|
else message2 = JSON.stringify(error);
|
|
42173
44351
|
return mapStreamErrorMessage(message2);
|
|
42174
44352
|
},
|
|
42175
|
-
generateMessageId: (0,
|
|
44353
|
+
generateMessageId: (0, import_ai17.createIdGenerator)({
|
|
42176
44354
|
prefix: "msg_",
|
|
42177
44355
|
size: 16
|
|
42178
44356
|
}),
|
|
@@ -42263,12 +44441,15 @@ ${customInstructions}` : agent.instructions,
|
|
|
42263
44441
|
return;
|
|
42264
44442
|
} else {
|
|
42265
44443
|
const customInstructions = req.body.customInstructions ? typeof req.body.customInstructions === "string" ? req.body.customInstructions : JSON.stringify(req.body.customInstructions) : "";
|
|
42266
|
-
const
|
|
44444
|
+
const baseInstructions = withGlossary(
|
|
42267
44445
|
customInstructions ? `${agent.instructions}
|
|
42268
44446
|
|
|
42269
44447
|
${customInstructions}` : agent.instructions,
|
|
42270
44448
|
agent.tools
|
|
42271
44449
|
);
|
|
44450
|
+
const instructions = outputSchema ? `${baseInstructions}
|
|
44451
|
+
|
|
44452
|
+
${outputSchemaInstructions(outputSchema)}` : baseInstructions;
|
|
42272
44453
|
let response;
|
|
42273
44454
|
try {
|
|
42274
44455
|
response = await generateSync({
|
|
@@ -42303,6 +44484,45 @@ ${customInstructions}` : agent.instructions,
|
|
|
42303
44484
|
res.status(status).send(body);
|
|
42304
44485
|
return;
|
|
42305
44486
|
}
|
|
44487
|
+
if (outputSchema) {
|
|
44488
|
+
try {
|
|
44489
|
+
const shaped = await respondWithOutputSchema({
|
|
44490
|
+
model: resolvedLanguageModel,
|
|
44491
|
+
system: baseInstructions,
|
|
44492
|
+
question: messageText(req.body.message),
|
|
44493
|
+
answer: typeof response === "string" ? response : JSON.stringify(response ?? ""),
|
|
44494
|
+
schema: outputSchema,
|
|
44495
|
+
// Same counters as the agent run itself; the run was already counted once.
|
|
44496
|
+
onUsage: async ({ inputTokens, outputTokens }) => {
|
|
44497
|
+
await Promise.all(
|
|
44498
|
+
[
|
|
44499
|
+
["inputTokens", inputTokens],
|
|
44500
|
+
["outputTokens", outputTokens]
|
|
44501
|
+
].filter(([, count]) => count > 0).map(
|
|
44502
|
+
([name, count]) => updateStatistic({
|
|
44503
|
+
name,
|
|
44504
|
+
label: agent.name,
|
|
44505
|
+
type: STATISTICS_TYPE_ENUM.AGENT_RUN,
|
|
44506
|
+
trigger: "agent",
|
|
44507
|
+
count,
|
|
44508
|
+
user: user?.id,
|
|
44509
|
+
role: user?.role?.id
|
|
44510
|
+
})
|
|
44511
|
+
)
|
|
44512
|
+
);
|
|
44513
|
+
}
|
|
44514
|
+
});
|
|
44515
|
+
res.status(shaped.status).json(shaped.body);
|
|
44516
|
+
} catch (err4) {
|
|
44517
|
+
console.error(
|
|
44518
|
+
"[EXULU] output schema shaping failed.",
|
|
44519
|
+
err4 instanceof Error ? err4.message.slice(0, 500) : err4
|
|
44520
|
+
);
|
|
44521
|
+
const { status, body } = describeRequestError(err4);
|
|
44522
|
+
res.status(status).send(body);
|
|
44523
|
+
}
|
|
44524
|
+
return;
|
|
44525
|
+
}
|
|
42306
44526
|
res.status(200).json(response);
|
|
42307
44527
|
return;
|
|
42308
44528
|
}
|
|
@@ -43163,12 +45383,12 @@ ${style.markdown}` : params.prompt;
|
|
|
43163
45383
|
const lines = selectedDetails.map(
|
|
43164
45384
|
(d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
|
|
43165
45385
|
);
|
|
43166
|
-
const
|
|
45386
|
+
const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
|
|
43167
45387
|
const messageId = (0, import_node_crypto24.randomUUID)();
|
|
43168
45388
|
const uiMessage = {
|
|
43169
45389
|
id: messageId,
|
|
43170
45390
|
role: "system",
|
|
43171
|
-
parts: [{ type: "text", text:
|
|
45391
|
+
parts: [{ type: "text", text: messageText2 }]
|
|
43172
45392
|
};
|
|
43173
45393
|
await authed.db("agent_messages").insert({
|
|
43174
45394
|
content: JSON.stringify(uiMessage),
|
|
@@ -45194,7 +47414,7 @@ ${style.markdown}` : params.prompt;
|
|
|
45194
47414
|
...s,
|
|
45195
47415
|
messages: messagesBySession.get(s.id) ?? []
|
|
45196
47416
|
}));
|
|
45197
|
-
const [feedback, promptFavorites, tracking, claimChecks] = await Promise.all([
|
|
47417
|
+
const [feedback, promptFavorites, tracking, claimChecks, channelLinks] = await Promise.all([
|
|
45198
47418
|
db2.from("feedback").where({ user: targetUser.id }).catch(() => []),
|
|
45199
47419
|
db2.from("prompt_favorites").where({ user_id: targetUser.id }).catch(() => []),
|
|
45200
47420
|
db2.from("tracking").where({ user: targetUser.id }).catch(() => []),
|
|
@@ -45202,7 +47422,10 @@ ${style.markdown}` : params.prompt;
|
|
|
45202
47422
|
// data (their answers' sentences, verbatim source quotes), so Art. 15
|
|
45203
47423
|
// covers it. Same `.catch(() => [])` as its siblings: the table only
|
|
45204
47424
|
// exists on deployments licensed for claim-check.
|
|
45205
|
-
db2.from("claim_checks").where({ user: targetUser.id }).catch(() => [])
|
|
47425
|
+
db2.from("claim_checks").where({ user: targetUser.id }).catch(() => []),
|
|
47426
|
+
// WhatsApp links (full identity: it is the user's own data). Empty and
|
|
47427
|
+
// query-free without the channels licence; never rejects.
|
|
47428
|
+
channelLinksForExport(db2, targetUser.id)
|
|
45206
47429
|
]);
|
|
45207
47430
|
const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
45208
47431
|
const readme = [
|
|
@@ -45222,6 +47445,7 @@ ${style.markdown}` : params.prompt;
|
|
|
45222
47445
|
` - prompt_favorites.json prompt-library favourites`,
|
|
45223
47446
|
` - tracking.json tracking events linked to the user`,
|
|
45224
47447
|
` - claim_checks.json answer verification results stored for the user`,
|
|
47448
|
+
` - channel_links.json messaging-channel (WhatsApp) links of the user`,
|
|
45225
47449
|
``
|
|
45226
47450
|
].join("\n");
|
|
45227
47451
|
const zip = new import_jszip4.default();
|
|
@@ -45235,6 +47459,7 @@ ${style.markdown}` : params.prompt;
|
|
|
45235
47459
|
);
|
|
45236
47460
|
zip.file("tracking.json", JSON.stringify(tracking, null, 2));
|
|
45237
47461
|
zip.file("claim_checks.json", JSON.stringify(claimChecks, null, 2));
|
|
47462
|
+
zip.file("channel_links.json", JSON.stringify(channelLinks, null, 2));
|
|
45238
47463
|
const buffer = await zip.generateAsync({ type: "nodebuffer" });
|
|
45239
47464
|
const filename = `user-${targetUser.id}-export-${exportedAt.replace(/[:.]/g, "-")}.zip`;
|
|
45240
47465
|
res.setHeader("Content-Type", "application/zip");
|
|
@@ -45263,6 +47488,7 @@ ${style.markdown}` : params.prompt;
|
|
|
45263
47488
|
await trx("prompt_favorites").where({ user_id: targetUser.id }).delete();
|
|
45264
47489
|
await trx("tracking").where({ user: targetUser.id }).delete();
|
|
45265
47490
|
await trx("rbac").where({ user_id: targetUser.id }).delete();
|
|
47491
|
+
await afterUserDelete(trx, targetUser.id);
|
|
45266
47492
|
await trx("users").where({ id: targetUser.id }).delete();
|
|
45267
47493
|
});
|
|
45268
47494
|
} catch (err4) {
|
|
@@ -45566,18 +47792,32 @@ ${style.markdown}` : params.prompt;
|
|
|
45566
47792
|
if (headers.disposition) res.setHeader("Content-Disposition", headers.disposition);
|
|
45567
47793
|
res.send(bytes);
|
|
45568
47794
|
});
|
|
47795
|
+
registerChannelApi(app, {
|
|
47796
|
+
authenticate: (req) => requestValidators.authenticate(req),
|
|
47797
|
+
getDb: async () => (await postgresClient()).db,
|
|
47798
|
+
getStore: async () => {
|
|
47799
|
+
const client2 = (await redisClient()).client;
|
|
47800
|
+
return client2 && client2.isReady ? channelStoreFromRedis(client2) : null;
|
|
47801
|
+
},
|
|
47802
|
+
loadAgent: (id) => exuluApp.get().agent(id),
|
|
47803
|
+
checkRecordAccess: (record, request3, user) => checkRecordAccess(record, request3, user),
|
|
47804
|
+
entitled: () => {
|
|
47805
|
+
const license = checkLicense();
|
|
47806
|
+
return license["channels"] === true && license["queues"] === true;
|
|
47807
|
+
}
|
|
47808
|
+
});
|
|
45569
47809
|
const resolvePublicAgentSlug = async (agentModel) => {
|
|
45570
47810
|
if (isLiteLLMEnabled()) return "/agents/litellm/run";
|
|
45571
47811
|
if (!agentModel) return "";
|
|
45572
47812
|
return "";
|
|
45573
47813
|
};
|
|
45574
|
-
const
|
|
47814
|
+
const UUID_RE5 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
45575
47815
|
const stripBucketPrefix = (key, cfg) => {
|
|
45576
47816
|
const bucket = cfg.fileUploads?.s3Bucket;
|
|
45577
47817
|
return bucket ? key.replace(`${bucket}/`, "") : key;
|
|
45578
47818
|
};
|
|
45579
47819
|
const getGuestAgentById = async (id) => {
|
|
45580
|
-
if (!
|
|
47820
|
+
if (!UUID_RE5.test(id)) return void 0;
|
|
45581
47821
|
const { db: db2 } = await postgresClient();
|
|
45582
47822
|
return db2.from("agents").where({ id, guest_access: true, active: true }).first();
|
|
45583
47823
|
};
|
|
@@ -45589,6 +47829,7 @@ ${style.markdown}` : params.prompt;
|
|
|
45589
47829
|
"description",
|
|
45590
47830
|
"image",
|
|
45591
47831
|
"welcomemessage",
|
|
47832
|
+
"welcomemessage_translations",
|
|
45592
47833
|
"model",
|
|
45593
47834
|
"guest_auth_mode",
|
|
45594
47835
|
"guest_cover_image",
|
|
@@ -45762,10 +48003,10 @@ init_cjs_shims();
|
|
|
45762
48003
|
var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
45763
48004
|
var import_node_crypto25 = require("crypto");
|
|
45764
48005
|
var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
45765
|
-
var
|
|
48006
|
+
var import_types14 = require("@modelcontextprotocol/sdk/types.js");
|
|
45766
48007
|
init_sanitize_tool_name();
|
|
45767
48008
|
var import_express4 = require("express");
|
|
45768
|
-
var
|
|
48009
|
+
var import_api5 = require("@opentelemetry/api");
|
|
45769
48010
|
init_check_record_access();
|
|
45770
48011
|
init_resolve_model();
|
|
45771
48012
|
init_supervisor();
|
|
@@ -45824,26 +48065,26 @@ var ExuluMCP = class {
|
|
|
45824
48065
|
"[EXULU] Enabled tools",
|
|
45825
48066
|
enabledTools?.map((x) => x.name + " (" + x.id + ")")
|
|
45826
48067
|
);
|
|
45827
|
-
for (const
|
|
45828
|
-
if (server.tools[
|
|
48068
|
+
for (const tool5 of enabledTools || []) {
|
|
48069
|
+
if (server.tools[tool5.id]) {
|
|
45829
48070
|
continue;
|
|
45830
48071
|
}
|
|
45831
48072
|
server.mcp.registerTool(
|
|
45832
|
-
sanitizeToolName(
|
|
48073
|
+
sanitizeToolName(tool5.name + "_agent_" + tool5.id),
|
|
45833
48074
|
{
|
|
45834
|
-
title:
|
|
45835
|
-
description:
|
|
48075
|
+
title: tool5.name + " agent",
|
|
48076
|
+
description: tool5.description,
|
|
45836
48077
|
inputSchema: {
|
|
45837
|
-
inputs:
|
|
48078
|
+
inputs: tool5.inputSchema || import_zod36.z.object({})
|
|
45838
48079
|
}
|
|
45839
48080
|
},
|
|
45840
48081
|
async ({ inputs }, args) => {
|
|
45841
|
-
console.log("[EXULU] MCP tool name",
|
|
48082
|
+
console.log("[EXULU] MCP tool name", tool5.name);
|
|
45842
48083
|
console.log("[EXULU] MCP tool inputs", inputs);
|
|
45843
48084
|
console.log("[EXULU] MCP tool args", args);
|
|
45844
48085
|
const configValues = agent.tools;
|
|
45845
48086
|
const tools = await convertExuluToolsToAiSdkTools(
|
|
45846
|
-
[
|
|
48087
|
+
[tool5],
|
|
45847
48088
|
[],
|
|
45848
48089
|
[],
|
|
45849
48090
|
allTools,
|
|
@@ -45855,13 +48096,13 @@ var ExuluMCP = class {
|
|
|
45855
48096
|
void 0,
|
|
45856
48097
|
void 0
|
|
45857
48098
|
);
|
|
45858
|
-
const convertedTool = tools[sanitizeToolName(
|
|
48099
|
+
const convertedTool = tools[sanitizeToolName(tool5.name)];
|
|
45859
48100
|
if (!convertedTool?.execute) {
|
|
45860
48101
|
console.error("[EXULU] Tool not found in converted tools array.", tools);
|
|
45861
48102
|
throw new Error("Tool not found in converted tools array.");
|
|
45862
48103
|
}
|
|
45863
48104
|
const iterator = await convertedTool.execute(inputs, {
|
|
45864
|
-
toolCallId:
|
|
48105
|
+
toolCallId: tool5.id + "_" + (0, import_node_crypto25.randomUUID)(),
|
|
45865
48106
|
messages: []
|
|
45866
48107
|
});
|
|
45867
48108
|
let result;
|
|
@@ -45875,7 +48116,7 @@ var ExuluMCP = class {
|
|
|
45875
48116
|
};
|
|
45876
48117
|
}
|
|
45877
48118
|
);
|
|
45878
|
-
server.tools[
|
|
48119
|
+
server.tools[tool5.id] = tool5.name;
|
|
45879
48120
|
}
|
|
45880
48121
|
const getListOfPromptTemplatesName = "getListOfPromptTemplates";
|
|
45881
48122
|
if (!server.tools[getListOfPromptTemplatesName]) {
|
|
@@ -46049,7 +48290,7 @@ var ExuluMCP = class {
|
|
|
46049
48290
|
let transport;
|
|
46050
48291
|
if (sessionId && this.transports[sessionId]) {
|
|
46051
48292
|
transport = this.transports[sessionId];
|
|
46052
|
-
} else if (!sessionId && (0,
|
|
48293
|
+
} else if (!sessionId && (0, import_types14.isInitializeRequest)(req.body)) {
|
|
46053
48294
|
transport = new import_streamableHttp.StreamableHTTPServerTransport({
|
|
46054
48295
|
sessionIdGenerator: () => (0, import_node_crypto25.randomUUID)(),
|
|
46055
48296
|
onsessioninitialized: (sessionId2) => {
|
|
@@ -46094,7 +48335,7 @@ var ExuluMCP = class {
|
|
|
46094
48335
|
|
|
46095
48336
|
// src/exulu/app/index.ts
|
|
46096
48337
|
var import_express7 = __toESM(require("express"), 1);
|
|
46097
|
-
var
|
|
48338
|
+
var import_api6 = require("@opentelemetry/api");
|
|
46098
48339
|
|
|
46099
48340
|
// src/exulu/logger.ts
|
|
46100
48341
|
init_cjs_shims();
|
|
@@ -46134,7 +48375,7 @@ init_cjs_shims();
|
|
|
46134
48375
|
|
|
46135
48376
|
// src/exulu/evals.ts
|
|
46136
48377
|
init_cjs_shims();
|
|
46137
|
-
var
|
|
48378
|
+
var import_ai18 = require("ai");
|
|
46138
48379
|
var ExuluEval = class {
|
|
46139
48380
|
id;
|
|
46140
48381
|
name;
|
|
@@ -46174,7 +48415,7 @@ var ExuluEval = class {
|
|
|
46174
48415
|
init_resolve_model();
|
|
46175
48416
|
init_singleton();
|
|
46176
48417
|
var import_zod37 = require("zod");
|
|
46177
|
-
var
|
|
48418
|
+
var import_ai19 = require("ai");
|
|
46178
48419
|
var llmAsJudgeEval = () => {
|
|
46179
48420
|
if (process.env.REDIS_HOST?.length && process.env.REDIS_PORT?.length) {
|
|
46180
48421
|
return new ExuluEval({
|
|
@@ -46217,13 +48458,13 @@ var llmAsJudgeEval = () => {
|
|
|
46217
48458
|
rbacBypass: true
|
|
46218
48459
|
});
|
|
46219
48460
|
console.log("[EXULU] prompt", prompt);
|
|
46220
|
-
const { output } = await (0,
|
|
48461
|
+
const { output } = await (0, import_ai19.generateText)({
|
|
46221
48462
|
temperature: 0,
|
|
46222
48463
|
model: resolved.languageModel,
|
|
46223
48464
|
system: "",
|
|
46224
48465
|
prompt,
|
|
46225
48466
|
maxRetries: 2,
|
|
46226
|
-
output:
|
|
48467
|
+
output: import_ai19.Output.object({
|
|
46227
48468
|
schema: import_zod37.z.object({
|
|
46228
48469
|
score: import_zod37.z.number().min(0).max(100).describe("The score between 0 and 100.")
|
|
46229
48470
|
})
|
|
@@ -47425,9 +49666,9 @@ var ExuluApp = class {
|
|
|
47425
49666
|
id: this._contexts?.[x]?.id ?? "",
|
|
47426
49667
|
type: "context"
|
|
47427
49668
|
})),
|
|
47428
|
-
...this._tools.map((
|
|
47429
|
-
name:
|
|
47430
|
-
id:
|
|
49669
|
+
...this._tools.map((tool5) => ({
|
|
49670
|
+
name: tool5.name ?? "",
|
|
49671
|
+
id: tool5.id ?? "",
|
|
47431
49672
|
type: "tool"
|
|
47432
49673
|
}))
|
|
47433
49674
|
];
|
|
@@ -47476,6 +49717,7 @@ var ExuluApp = class {
|
|
|
47476
49717
|
300
|
|
47477
49718
|
);
|
|
47478
49719
|
registerImportQueue();
|
|
49720
|
+
registerChannelQueue();
|
|
47479
49721
|
if (queues2?.length) {
|
|
47480
49722
|
for (const queue of queues2) {
|
|
47481
49723
|
queueSet.add(await queue);
|
|
@@ -47724,7 +49966,7 @@ var ExuluApp = class {
|
|
|
47724
49966
|
}
|
|
47725
49967
|
let tracer;
|
|
47726
49968
|
if (this._config?.telemetry?.enabled) {
|
|
47727
|
-
tracer =
|
|
49969
|
+
tracer = import_api6.trace.getTracer("exulu", "1.0.0");
|
|
47728
49970
|
}
|
|
47729
49971
|
const transports = this._config?.workers?.logger?.winston?.transports ?? this._config?.logger?.winston?.transports ?? [consoleTransport];
|
|
47730
49972
|
const logger = logger_default({
|
|
@@ -47814,7 +50056,7 @@ var ExuluApp = class {
|
|
|
47814
50056
|
const app = this._expressApp;
|
|
47815
50057
|
let tracer;
|
|
47816
50058
|
if (this._config?.telemetry?.enabled) {
|
|
47817
|
-
tracer =
|
|
50059
|
+
tracer = import_api6.trace.getTracer("exulu", "1.0.0");
|
|
47818
50060
|
}
|
|
47819
50061
|
const transports = this._config?.logger?.winston?.transports ?? [consoleTransport];
|
|
47820
50062
|
const logger = logger_default({
|
|
@@ -48715,6 +50957,8 @@ var {
|
|
|
48715
50957
|
variablesSchema: variablesSchema3,
|
|
48716
50958
|
workflowTemplatesSchema: workflowTemplatesSchema3,
|
|
48717
50959
|
workflowTriggersSchema: workflowTriggersSchema2,
|
|
50960
|
+
agentChannelsSchema: agentChannelsSchema2,
|
|
50961
|
+
channelLinksSchema: channelLinksSchema2,
|
|
48718
50962
|
rbacSchema: rbacSchema3,
|
|
48719
50963
|
projectsSchema: projectsSchema3,
|
|
48720
50964
|
jobResultsSchema: jobResultsSchema3,
|
|
@@ -48804,6 +51048,8 @@ var up = async function(knex) {
|
|
|
48804
51048
|
skillsSchema3(),
|
|
48805
51049
|
workflowTemplatesSchema3(),
|
|
48806
51050
|
workflowTriggersSchema2(),
|
|
51051
|
+
// Only present when the "channels" entitlement is licensed.
|
|
51052
|
+
...agentChannelsSchema2 && channelLinksSchema2 ? [agentChannelsSchema2(), channelLinksSchema2()] : [],
|
|
48807
51053
|
otpSendAttemptsSchema2()
|
|
48808
51054
|
];
|
|
48809
51055
|
const createTable = async (schema7) => {
|
|
@@ -48964,6 +51210,19 @@ var up = async function(knex) {
|
|
|
48964
51210
|
ON claim_checks (session, message_id, "user")`
|
|
48965
51211
|
);
|
|
48966
51212
|
}
|
|
51213
|
+
if (await knex.schema.hasTable("agent_channels")) {
|
|
51214
|
+
await knex.raw(
|
|
51215
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS agent_channels_agent_type_uidx
|
|
51216
|
+
ON agent_channels (agent, type)`
|
|
51217
|
+
);
|
|
51218
|
+
}
|
|
51219
|
+
if (await knex.schema.hasTable("channel_links")) {
|
|
51220
|
+
await knex.raw(
|
|
51221
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS channel_links_channel_identity_uidx
|
|
51222
|
+
ON channel_links (channel, identity)`
|
|
51223
|
+
);
|
|
51224
|
+
await initChatStateTables();
|
|
51225
|
+
}
|
|
48967
51226
|
};
|
|
48968
51227
|
var contextDatabases = async (contexts) => {
|
|
48969
51228
|
const { db: knex } = await postgresClient();
|
|
@@ -49086,7 +51345,7 @@ init_cjs_shims();
|
|
|
49086
51345
|
var import_node_fs12 = require("fs");
|
|
49087
51346
|
var import_node_path17 = require("path");
|
|
49088
51347
|
var import_node_child_process8 = require("child_process");
|
|
49089
|
-
var
|
|
51348
|
+
var import_pg3 = require("pg");
|
|
49090
51349
|
|
|
49091
51350
|
// src/exulu/litellm/db-setup-check.ts
|
|
49092
51351
|
init_cjs_shims();
|
|
@@ -49190,7 +51449,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
|
|
|
49190
51449
|
`LiteLLM database mode detected (${target?.host}:${target?.port}/${target?.database}).`
|
|
49191
51450
|
);
|
|
49192
51451
|
const ensureDatabaseExists2 = async () => {
|
|
49193
|
-
const probe = new
|
|
51452
|
+
const probe = new import_pg3.Client({ connectionString: litellmUrl });
|
|
49194
51453
|
try {
|
|
49195
51454
|
await probe.connect();
|
|
49196
51455
|
await probe.end();
|
|
@@ -49223,7 +51482,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
|
|
|
49223
51482
|
]);
|
|
49224
51483
|
return false;
|
|
49225
51484
|
}
|
|
49226
|
-
const admin = new
|
|
51485
|
+
const admin = new import_pg3.Client({ connectionString: url.toString() });
|
|
49227
51486
|
try {
|
|
49228
51487
|
await admin.connect();
|
|
49229
51488
|
await admin.query(`CREATE DATABASE "${targetDbName}"`);
|
|
@@ -49250,7 +51509,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
|
|
|
49250
51509
|
};
|
|
49251
51510
|
if (!await ensureDatabaseExists2()) return;
|
|
49252
51511
|
log6("Checking that the target database is safe to push into\u2026");
|
|
49253
|
-
const client2 = new
|
|
51512
|
+
const client2 = new import_pg3.Client({ connectionString: litellmUrl });
|
|
49254
51513
|
let foreignTables = [];
|
|
49255
51514
|
try {
|
|
49256
51515
|
await client2.connect();
|