@exulu/backend 5.16.0 → 5.17.1

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/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 pending = (0, import_load.load)(import_registry.default[encoding]).then((ranks) => {
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, pending);
1833
- return pending;
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) * DAY_MS);
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() + DAY_MS))
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, DAY_MS, DEFAULT_SETTINGS, TAG_MAP_TTL_MS, tagMapCache, tagMapInflight, PROVISION_TTL_MS, provisionCache, READ_TTL_MS, readCache;
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
- DAY_MS = 24 * 60 * 60 * 1e3;
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 `
@@ -6904,6 +6941,10 @@ var init_core_schema = __esm({
6904
6941
  schemas.workflowTemplatesSchema = () => addCoreFields(workflowTemplatesSchema);
6905
6942
  schemas.workflowTriggersSchema = () => addCoreFields(workflowTriggersSchema);
6906
6943
  }
6944
+ if (license["channels"]) {
6945
+ schemas.agentChannelsSchema = () => addCoreFields(agentChannelsSchema);
6946
+ schemas.channelLinksSchema = () => addCoreFields(channelLinksSchema);
6947
+ }
6907
6948
  if (license["queues"]) {
6908
6949
  schemas.jobResultsSchema = () => addCoreFields(jobResultsSchema);
6909
6950
  }
@@ -9754,7 +9795,7 @@ var init_registry = __esm({
9754
9795
  // src/exulu/auth/credential-store.ts
9755
9796
  async function get(provider, userId) {
9756
9797
  const { db: db2 } = await postgresClient();
9757
- const row = await db2.from(TABLE).where({ provider, user_id: String(userId) }).first();
9798
+ const row = await db2.from(TABLE3).where({ provider, user_id: String(userId) }).first();
9758
9799
  if (!row) {
9759
9800
  return null;
9760
9801
  }
@@ -9768,7 +9809,7 @@ async function get(provider, userId) {
9768
9809
  async function upsert(record) {
9769
9810
  const { db: db2 } = await postgresClient();
9770
9811
  const encrypted = encrypt(JSON.stringify(record.data));
9771
- await db2.from(TABLE).insert({
9812
+ await db2.from(TABLE3).insert({
9772
9813
  provider: record.provider,
9773
9814
  user_id: String(record.userId),
9774
9815
  auth_type: record.authType,
@@ -9778,7 +9819,7 @@ async function upsert(record) {
9778
9819
  }
9779
9820
  async function listByUser(userId) {
9780
9821
  const { db: db2 } = await postgresClient();
9781
- const list = await db2.from(TABLE).where({ user_id: String(userId) }).orderBy("provider");
9822
+ const list = await db2.from(TABLE3).where({ user_id: String(userId) }).orderBy("provider");
9782
9823
  return list.map((row) => ({
9783
9824
  provider: row.provider,
9784
9825
  authType: row.auth_type,
@@ -9788,16 +9829,16 @@ async function listByUser(userId) {
9788
9829
  }
9789
9830
  async function del(provider, userId) {
9790
9831
  const { db: db2 } = await postgresClient();
9791
- await db2.from(TABLE).where({ provider, user_id: String(userId) }).del();
9832
+ await db2.from(TABLE3).where({ provider, user_id: String(userId) }).del();
9792
9833
  }
9793
- var import_crypto_js, TABLE, encrypt, decrypt, credentialStore;
9834
+ var import_crypto_js, TABLE3, encrypt, decrypt, credentialStore;
9794
9835
  var init_credential_store = __esm({
9795
9836
  "src/exulu/auth/credential-store.ts"() {
9796
9837
  "use strict";
9797
9838
  init_cjs_shims();
9798
9839
  import_crypto_js = __toESM(require("crypto-js"), 1);
9799
9840
  init_client();
9800
- TABLE = "user_credentials";
9841
+ TABLE3 = "user_credentials";
9801
9842
  encrypt = (value) => import_crypto_js.default.AES.encrypt(value, process.env.NEXTAUTH_SECRET).toString();
9802
9843
  decrypt = (value) => import_crypto_js.default.AES.decrypt(value, process.env.NEXTAUTH_SECRET).toString(import_crypto_js.default.enc.Utf8);
9803
9844
  credentialStore = { get, upsert, listByUser, delete: del };
@@ -11342,11 +11383,11 @@ var init_context_read_tools = __esm({
11342
11383
  };
11343
11384
  readContextItem = async (context, args, caller, deps = {}) => {
11344
11385
  const { user } = caller;
11345
- const NOT_FOUND = itemNotFoundMessage(context, "read");
11386
+ const NOT_FOUND2 = itemNotFoundMessage(context, "read");
11346
11387
  const checkAccess = deps.checkAccess ?? checkItemReadAccess;
11347
11388
  const readable = readableContextFields(context);
11348
11389
  if (treatAsGuest(caller.req, user)) {
11349
- return { ok: false, message: NOT_FOUND };
11390
+ return { ok: false, message: NOT_FOUND2 };
11350
11391
  }
11351
11392
  if (!args.id && !args.external_id) {
11352
11393
  return { ok: false, message: "Provide the id or external_id of the item to read." };
@@ -11360,10 +11401,10 @@ var init_context_read_tools = __esm({
11360
11401
  item: { id: args.id, external_id: args.external_id }
11361
11402
  });
11362
11403
  if (!record?.id) {
11363
- return { ok: false, message: NOT_FOUND };
11404
+ return { ok: false, message: NOT_FOUND2 };
11364
11405
  }
11365
11406
  if (!await checkAccess(context, record, user)) {
11366
- return { ok: false, message: NOT_FOUND };
11407
+ return { ok: false, message: NOT_FOUND2 };
11367
11408
  }
11368
11409
  const explicit = Array.isArray(args.fields) && args.fields.length > 0;
11369
11410
  return { ok: true, item: projectRow(record, selection.fields, explicit) };
@@ -11728,7 +11769,7 @@ var init_context_write_tools = __esm({
11728
11769
  if (perms.update) {
11729
11770
  const { shape, contentKeys, fileFields } = buildWriteSchema(context, "update");
11730
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." : "";
11731
- const NOT_FOUND = itemNotFoundMessage(context, "write");
11772
+ const NOT_FOUND2 = itemNotFoundMessage(context, "write");
11732
11773
  tools.push(
11733
11774
  new ExuluTool({
11734
11775
  id: `update_${segment}_item`,
@@ -11752,11 +11793,11 @@ var init_context_write_tools = __esm({
11752
11793
  item: { id: params.id, external_id: params.external_id }
11753
11794
  });
11754
11795
  if (!existing?.id) {
11755
- return { result: NOT_FOUND };
11796
+ return { result: NOT_FOUND2 };
11756
11797
  }
11757
11798
  const allowed = await checkItemWriteAccess(context, existing, user);
11758
11799
  if (!allowed) {
11759
- return { result: NOT_FOUND };
11800
+ return { result: NOT_FOUND2 };
11760
11801
  }
11761
11802
  const enumError = canonicalizeEnumFields(context, params);
11762
11803
  if (enumError) {
@@ -12299,10 +12340,10 @@ async function createProjectAndAttach(db2, user, input) {
12299
12340
  }
12300
12341
  function planMove(args) {
12301
12342
  const skipped = [];
12302
- let pool2;
12343
+ let pool3;
12303
12344
  if (args.requested) {
12304
12345
  const byName = new Map(args.files.map((f) => [f.name, f]));
12305
- pool2 = [];
12346
+ pool3 = [];
12306
12347
  const seen = /* @__PURE__ */ new Set();
12307
12348
  for (const raw of args.requested) {
12308
12349
  const name = String(raw ?? "").trim();
@@ -12314,18 +12355,18 @@ function planMove(args) {
12314
12355
  }
12315
12356
  const hit = byName.get(name);
12316
12357
  if (!hit) skipped.push({ name, reason: SKIP_UNKNOWN });
12317
- else pool2.push(hit);
12358
+ else pool3.push(hit);
12318
12359
  }
12319
12360
  } else {
12320
- pool2 = args.files.filter((f) => isDefaultMoveCandidate(f.name));
12361
+ pool3 = args.files.filter((f) => isDefaultMoveCandidate(f.name));
12321
12362
  }
12322
12363
  const groups = /* @__PURE__ */ new Map();
12323
- for (const f of pool2) {
12364
+ for (const f of pool3) {
12324
12365
  const safe = sanitizeFilename(f.name);
12325
12366
  groups.set(safe, [...groups.get(safe) ?? [], f]);
12326
12367
  }
12327
12368
  const usable = [];
12328
- for (const f of pool2) {
12369
+ for (const f of pool3) {
12329
12370
  const safe = sanitizeFilename(f.name);
12330
12371
  if (!safe) skipped.push({ name: f.name, reason: "Could not derive a safe filename." });
12331
12372
  else if ((groups.get(safe) ?? []).length > 1) skipped.push({ name: f.name, reason: SKIP_CLASH });
@@ -12491,15 +12532,15 @@ function originFromMetadata(metadata) {
12491
12532
  return metadata?.[ORIGIN_METADATA_KEY] === "agent" ? "agent" : "user";
12492
12533
  }
12493
12534
  function createOriginResolver(head) {
12494
- const cache2 = /* @__PURE__ */ new Map();
12535
+ const cache3 = /* @__PURE__ */ new Map();
12495
12536
  return async (file) => {
12496
12537
  const stamp2 = file.lastModified instanceof Date ? file.lastModified.toISOString() : String(file.lastModified);
12497
12538
  const id = `${file.key}\0${stamp2}`;
12498
- const hit = cache2.get(id);
12539
+ const hit = cache3.get(id);
12499
12540
  if (hit) return hit;
12500
12541
  try {
12501
12542
  const origin = originFromMetadata(await head(file.key));
12502
- cache2.set(id, origin);
12543
+ cache3.set(id, origin);
12503
12544
  return origin;
12504
12545
  } catch {
12505
12546
  return "user";
@@ -14063,7 +14104,7 @@ async function sweepStaleHelpers(sessionDir) {
14063
14104
  for (const name of names) {
14064
14105
  if (!name.startsWith(prefix)) continue;
14065
14106
  const st = await (0, import_promises2.lstat)((0, import_node_path6.join)(root, name)).catch(() => null);
14066
- if (st && Date.now() - st.mtimeMs > DAY_MS2) await removeTreeSafely((0, import_node_path6.join)(root, name), sessionDir);
14107
+ if (st && Date.now() - st.mtimeMs > DAY_MS3) await removeTreeSafely((0, import_node_path6.join)(root, name), sessionDir);
14067
14108
  }
14068
14109
  }
14069
14110
  }
@@ -14188,7 +14229,7 @@ async function resolveSandboxProjectId(args, deps) {
14188
14229
  return null;
14189
14230
  }
14190
14231
  }
14191
- var import_promises2, import_node_crypto6, import_node_path6, import_node_child_process3, import_node_util2, isFlatName, HELPER_KINDS, helperRoot, helperPath, execFileAsync2, DAY_MS2, errCode;
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;
14192
14233
  var init_project_sync = __esm({
14193
14234
  "ee/invoke-skills/project-sync.ts"() {
14194
14235
  "use strict";
@@ -14206,7 +14247,7 @@ var init_project_sync = __esm({
14206
14247
  helperRoot = (sessionDir, kind) => (0, import_node_path6.join)((0, import_node_path6.dirname)(sessionDir), kind);
14207
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")}`);
14208
14249
  execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
14209
- DAY_MS2 = 24 * 60 * 60 * 1e3;
14250
+ DAY_MS3 = 24 * 60 * 60 * 1e3;
14210
14251
  errCode = (err4) => err4?.code;
14211
14252
  }
14212
14253
  });
@@ -14892,6 +14933,11 @@ var init_inventory = __esm({
14892
14933
  DEBUG: "runtime",
14893
14934
  BACKEND: "runtime",
14894
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",
14895
14941
  // Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
14896
14942
  AUTH_MODE: "runtime",
14897
14943
  // "password" | "otp" mode selector, echoed by GET /config
@@ -17143,9 +17189,9 @@ var init_auth_tool_model_output = __esm({
17143
17189
  "use strict";
17144
17190
  init_cjs_shims();
17145
17191
  init_scrub_text();
17146
- buildAuthToolModelOutput = (tool4) => ({ output }) => {
17192
+ buildAuthToolModelOutput = (tool5) => ({ output }) => {
17147
17193
  if (output && typeof output === "object" && output.credentialRequest) {
17148
- const auth = tool4.authentication;
17194
+ const auth = tool5.authentication;
17149
17195
  const labels = auth?.authType === "user_credentials" ? auth.fields.map((f) => f.label) : [];
17150
17196
  const provider = output.credentialRequest.provider ?? (auth && "provider" in auth ? auth.provider : "unknown");
17151
17197
  return { type: "text", value: credentialScrubText(provider, labels) };
@@ -18418,10 +18464,10 @@ var init_doc_processor = __esm({
18418
18464
  if (!fileType) {
18419
18465
  throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
18420
18466
  }
18421
- const UUID2 = (0, import_crypto4.randomUUID)();
18467
+ const UUID3 = (0, import_crypto4.randomUUID)();
18422
18468
  let buffer;
18423
18469
  if (Buffer.isBuffer(file)) {
18424
- filePath = path3.join(tempDir, `${UUID2}.${fileType}`);
18470
+ filePath = path3.join(tempDir, `${UUID3}.${fileType}`);
18425
18471
  await fs2.promises.writeFile(filePath, file);
18426
18472
  buffer = file;
18427
18473
  } else {
@@ -18429,7 +18475,7 @@ var init_doc_processor = __esm({
18429
18475
  if (filePath.startsWith("http")) {
18430
18476
  const response = await fetch(filePath);
18431
18477
  const array = await response.arrayBuffer();
18432
- const tempFilePath = path3.join(tempDir, `${UUID2}.${fileType}`);
18478
+ const tempFilePath = path3.join(tempDir, `${UUID3}.${fileType}`);
18433
18479
  await fs2.promises.writeFile(tempFilePath, Buffer.from(array));
18434
18480
  buffer = Buffer.from(array);
18435
18481
  filePath = tempFilePath;
@@ -18622,7 +18668,7 @@ async function readThroughDocument(args) {
18622
18668
  const pointerAt = pointerKey(bucket, sourceKey, s3prefix);
18623
18669
  const fromStoredText = (stored) => {
18624
18670
  if (!stored) return null;
18625
- if (now().getTime() - stored.lastModified.getTime() > cacheDays * DAY_MS3) return null;
18671
+ if (now().getTime() - stored.lastModified.getTime() > cacheDays * DAY_MS4) return null;
18626
18672
  const pages = Number(stored.metadata?.[PAGES_METADATA_KEY]);
18627
18673
  const totalPages = Number.isInteger(pages) && pages > 0 ? pages : countPageMarkers(stored.text);
18628
18674
  return { text: stored.text, totalPages, fromStore: true };
@@ -18729,7 +18775,7 @@ function createStoreIo(exuluConfig) {
18729
18775
  putText: (key, text, metadata) => putS3ObjectTextExact(key, text, metadata, exuluConfig, key.endsWith(".json") ? "application/json" : void 0)
18730
18776
  };
18731
18777
  }
18732
- var import_crypto5, inFlight, DAY_MS3, sha256Hex, PAGES_METADATA_KEY, warn2;
18778
+ var import_crypto5, inFlight, DAY_MS4, sha256Hex, PAGES_METADATA_KEY, warn2;
18733
18779
  var init_store3 = __esm({
18734
18780
  "src/exulu/document-cache/store.ts"() {
18735
18781
  "use strict";
@@ -18738,7 +18784,7 @@ var init_store3 = __esm({
18738
18784
  init_uppy();
18739
18785
  init_keys();
18740
18786
  inFlight = /* @__PURE__ */ new Map();
18741
- DAY_MS3 = 24 * 60 * 60 * 1e3;
18787
+ DAY_MS4 = 24 * 60 * 60 * 1e3;
18742
18788
  sha256Hex = (bytes) => (0, import_crypto5.createHash)("sha256").update(bytes).digest("hex");
18743
18789
  PAGES_METADATA_KEY = "exulu-pages";
18744
18790
  warn2 = (what, err4) => console.warn(`[EXULU] document store: ${what}:`, err4 instanceof Error ? err4.message : String(err4));
@@ -19584,9 +19630,9 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19584
19630
  };
19585
19631
  OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
19586
19632
  generateS3Key = (filename) => `${(0, import_node_crypto10.randomUUID)()}-${filename}`;
19587
- hydrateVariables = async (tool4) => {
19633
+ hydrateVariables = async (tool5) => {
19588
19634
  const { db: db2 } = await postgresClient();
19589
- const promises2 = tool4.config.map(async (toolConfig) => {
19635
+ const promises2 = tool5.config.map(async (toolConfig) => {
19590
19636
  if (!toolConfig.variable) {
19591
19637
  return toolConfig;
19592
19638
  }
@@ -19632,7 +19678,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19632
19678
  return toolConfig;
19633
19679
  });
19634
19680
  await Promise.all(promises2);
19635
- return tool4;
19681
+ return tool5;
19636
19682
  };
19637
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) => {
19638
19684
  if (!currentTools) return {};
@@ -19784,7 +19830,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19784
19830
  let projectSearchContextIds;
19785
19831
  console.log("[EXULU] Creating agentic search tool", contexts?.length, model);
19786
19832
  if (contexts?.length && model && !disabled.has("agentic_context_search")) {
19787
- const index = currentTools.findIndex((tool4) => tool4.id === "agentic_context_search");
19833
+ const index = currentTools.findIndex((tool5) => tool5.id === "agentic_context_search");
19788
19834
  const memoryContext = agent?.memory ? contexts.find((c) => c.id === agent.memory) : void 0;
19789
19835
  if (index !== -1) {
19790
19836
  const agenticSearchTool = createAgenticRetrievalTool({
@@ -19834,7 +19880,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19834
19880
  }
19835
19881
  }
19836
19882
  } else {
19837
- const agenticSearchTool = currentTools.find((tool4) => tool4.id === "agentic_context_search");
19883
+ const agenticSearchTool = currentTools.find((tool5) => tool5.id === "agentic_context_search");
19838
19884
  if (agenticSearchTool) {
19839
19885
  currentTools.splice(currentTools.indexOf(agenticSearchTool), 1);
19840
19886
  }
@@ -19871,9 +19917,9 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19871
19917
  );
19872
19918
  }
19873
19919
  }
19874
- const sanitizedTools = currentTools ? currentTools.map((tool4) => ({
19875
- ...tool4,
19876
- name: sanitizeToolName(tool4.name)
19920
+ const sanitizedTools = currentTools ? currentTools.map((tool5) => ({
19921
+ ...tool5,
19922
+ name: sanitizeToolName(tool5.name)
19877
19923
  })) : [];
19878
19924
  console.log(
19879
19925
  "[EXULU] Sanitized tools",
@@ -20291,8 +20337,8 @@ var init_tool2 = __esm({
20291
20337
  void 0,
20292
20338
  agent
20293
20339
  );
20294
- const tool4 = tools[sanitizeName(this.name)] || tools[this.name] || tools[this.id];
20295
- if (!tool4?.execute) {
20340
+ const tool5 = tools[sanitizeName(this.name)] || tools[this.name] || tools[this.id];
20341
+ if (!tool5?.execute) {
20296
20342
  throw new Error("Tool " + sanitizeName(this.name) + " not found in " + JSON.stringify(tools));
20297
20343
  }
20298
20344
  console.log("[EXULU] Tool found", this.name);
@@ -20302,7 +20348,7 @@ var init_tool2 = __esm({
20302
20348
  toolCallId,
20303
20349
  messages: []
20304
20350
  });
20305
- const generator = tool4.execute(inputs, {
20351
+ const generator = tool5.execute(inputs, {
20306
20352
  toolCallId,
20307
20353
  messages: []
20308
20354
  });
@@ -20764,7 +20810,7 @@ var init_text_utils = __esm({
20764
20810
 
20765
20811
  // ee/agentic-retrieval/pipeline/prefilter.ts
20766
20812
  async function exactTokenPrefilter({
20767
- cacheKey,
20813
+ cacheKey: cacheKey2,
20768
20814
  tokens,
20769
20815
  context,
20770
20816
  fields,
@@ -20772,13 +20818,13 @@ async function exactTokenPrefilter({
20772
20818
  minTokenLength = 3,
20773
20819
  limit
20774
20820
  }) {
20775
- const cache2 = await ensureItemsCache({ cacheKey, context, fields, normalize });
20821
+ const cache3 = await ensureItemsCache({ cacheKey: cacheKey2, context, fields, normalize });
20776
20822
  const strip = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
20777
20823
  const normalizedTokens = [...new Set(tokens.map(strip))].filter((t) => t.length >= minTokenLength);
20778
20824
  if (!normalizedTokens.length) {
20779
20825
  return [];
20780
20826
  }
20781
- const matches = cache2.items.filter((item) => {
20827
+ const matches = cache3.items.filter((item) => {
20782
20828
  const haystack = strip(item.normalized || "");
20783
20829
  return normalizedTokens.some((token) => haystack.includes(token));
20784
20830
  });
@@ -20790,7 +20836,7 @@ async function exactTokenPrefilter({
20790
20836
  }));
20791
20837
  }
20792
20838
  async function fuzzyPrefilter({
20793
- cacheKey,
20839
+ cacheKey: cacheKey2,
20794
20840
  relevantKeywords,
20795
20841
  importantKeyword,
20796
20842
  context,
@@ -20801,14 +20847,14 @@ async function fuzzyPrefilter({
20801
20847
  supplementSeparatorVariants = false,
20802
20848
  supplementBudget = SUPPLEMENT_BUDGET
20803
20849
  }) {
20804
- const cache2 = await ensureItemsCache({ cacheKey, context, fields, normalize });
20850
+ const cache3 = await ensureItemsCache({ cacheKey: cacheKey2, context, fields, normalize });
20805
20851
  if (!relevantKeywords?.length) {
20806
20852
  return [];
20807
20853
  }
20808
20854
  const uniqueKeywords = [...new Set(relevantKeywords.flatMap((k) => k.split(" ")))];
20809
- const index = import_fuse.default.parseIndex(cache2.fuseIndex);
20855
+ const index = import_fuse.default.parseIndex(cache3.fuseIndex);
20810
20856
  const fuse = new import_fuse.default(
20811
- cache2.items,
20857
+ cache3.items,
20812
20858
  {
20813
20859
  includeScore: true,
20814
20860
  useExtendedSearch: true,
@@ -20897,7 +20943,7 @@ async function fuzzyPrefilter({
20897
20943
  ].sort((a, b) => b.length - a.length);
20898
20944
  if (supplementTokens.length > 0) {
20899
20945
  const seen = new Set(prefiltered.map((p) => p.id));
20900
- const candidates = cache2.items.filter(
20946
+ const candidates = cache3.items.filter(
20901
20947
  (item) => item.id && !seen.has(item.id) && supplementTokens.some((t) => (item.stripped ?? "").includes(t))
20902
20948
  ).map((item, idx) => {
20903
20949
  const nameStripped = stripSeparators(item.name ?? "");
@@ -21017,12 +21063,12 @@ var init_prefilter = __esm({
21017
21063
  SUPPLEMENT_BUDGET_WIDE = 50;
21018
21064
  itemCaches = {};
21019
21065
  ensureItemsCache = async ({
21020
- cacheKey,
21066
+ cacheKey: cacheKey2,
21021
21067
  context,
21022
21068
  fields,
21023
21069
  normalize
21024
21070
  }) => {
21025
- if (!itemCaches[cacheKey] || Date.now() - itemCaches[cacheKey].tsp.getTime() > 5 * 60 * 1e3 || itemCaches[cacheKey].items.length === 0) {
21071
+ if (!itemCaches[cacheKey2] || Date.now() - itemCaches[cacheKey2].tsp.getTime() > 5 * 60 * 1e3 || itemCaches[cacheKey2].items.length === 0) {
21026
21072
  const result = await context.getItems({ fields, filters: [] });
21027
21073
  const normalizedItems = result.map((item) => {
21028
21074
  const normalized = normalize(item);
@@ -21039,14 +21085,14 @@ var init_prefilter = __esm({
21039
21085
  stripped: stripSeparators(normalized ?? item.name ?? "")
21040
21086
  };
21041
21087
  });
21042
- itemCaches[cacheKey] = {
21043
- cacheKey,
21088
+ itemCaches[cacheKey2] = {
21089
+ cacheKey: cacheKey2,
21044
21090
  items: normalizedItems,
21045
21091
  tsp: /* @__PURE__ */ new Date(),
21046
21092
  fuseIndex: import_fuse.default.createIndex(["normalized"], normalizedItems)
21047
21093
  };
21048
21094
  }
21049
- return itemCaches[cacheKey];
21095
+ return itemCaches[cacheKey2];
21050
21096
  };
21051
21097
  FUZZY_EXTRACTION_PROMPT = (set) => `
21052
21098
  You are checking whether the user's question references any "${set.name}".
@@ -22270,12 +22316,12 @@ async function rerankResults(opts) {
22270
22316
  duplicateOf = /* @__PURE__ */ new Map();
22271
22317
  }
22272
22318
  }
22273
- const selectDistinct = (pool2, n) => {
22274
- if (duplicateOf.size === 0) return pool2.slice(0, n);
22319
+ const selectDistinct = (pool3, n) => {
22320
+ if (duplicateOf.size === 0) return pool3.slice(0, n);
22275
22321
  const picked = [];
22276
22322
  const pickedIds = /* @__PURE__ */ new Set();
22277
22323
  const deferred = [];
22278
- for (const c of pool2) {
22324
+ for (const c of pool3) {
22279
22325
  if (picked.length >= n) break;
22280
22326
  const id = c.chunk_id;
22281
22327
  if (id && (duplicateOf.get(id) ?? []).some((other) => pickedIds.has(other))) {
@@ -23170,7 +23216,7 @@ __export(index_exports, {
23170
23216
  });
23171
23217
  module.exports = __toCommonJS(index_exports);
23172
23218
  init_cjs_shims();
23173
- var import_config13 = require("dotenv/config");
23219
+ var import_config20 = require("dotenv/config");
23174
23220
 
23175
23221
  // src/redis/client.ts
23176
23222
  init_cjs_shims();
@@ -23290,6 +23336,140 @@ var import_express6 = require("express");
23290
23336
  init_cjs_shims();
23291
23337
  var import_express2 = require("express");
23292
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
+
23293
23473
  // src/validators/requests.ts
23294
23474
  init_cjs_shims();
23295
23475
  init_user();
@@ -23582,7 +23762,8 @@ init_entitlements();
23582
23762
  var global_queues = {
23583
23763
  eval_runs: "eval_runs",
23584
23764
  email_intake: "email_intake",
23585
- import: "import"
23765
+ import: "import",
23766
+ channel_inbound: "channel_inbound"
23586
23767
  };
23587
23768
  var ExuluQueues = class {
23588
23769
  queues;
@@ -23991,9 +24172,9 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
23991
24172
  if (result.tools) {
23992
24173
  result.tools = await Promise.all(
23993
24174
  result.tools.map(
23994
- async (tool4) => {
24175
+ async (tool5) => {
23995
24176
  let hydrated;
23996
- if (tool4.id === "agentic_context_search") {
24177
+ if (tool5.id === "agentic_context_search") {
23997
24178
  const instance2 = createAgenticRetrievalTool({
23998
24179
  contexts: [],
23999
24180
  user,
@@ -24008,22 +24189,22 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
24008
24189
  name: instance2.name,
24009
24190
  description: instance2.description,
24010
24191
  category: instance2.category,
24011
- config: tool4.config
24192
+ config: tool5.config
24012
24193
  };
24013
24194
  }
24014
- if (tool4.type === "agent") {
24015
- if (tool4.id === result.id) {
24195
+ if (tool5.type === "agent") {
24196
+ if (tool5.id === result.id) {
24016
24197
  return null;
24017
24198
  }
24018
- const instance2 = await exuluApp.get().agent(tool4.id);
24199
+ const instance2 = await exuluApp.get().agent(tool5.id);
24019
24200
  if (!instance2) {
24020
24201
  throw new Error(
24021
- "Trying to load a tool of type 'agent', but the associated agent with id " + tool4.id + " was not found in the database."
24202
+ "Trying to load a tool of type 'agent', but the associated agent with id " + tool5.id + " was not found in the database."
24022
24203
  );
24023
24204
  }
24024
24205
  if (!instance2.model) {
24025
24206
  throw new Error(
24026
- "Trying to load a tool of type 'agent', but the associated agent with id " + tool4.id + " does not have a model set for it."
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."
24027
24208
  );
24028
24209
  }
24029
24210
  const hasAccessToAgent = await checkRecordAccess(instance2, "read", user);
@@ -24043,13 +24224,13 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
24043
24224
  throw new Error("Litellm not configured or running.");
24044
24225
  }
24045
24226
  } else {
24046
- hydrated = tools.find((t) => t.id === tool4.id);
24227
+ hydrated = tools.find((t) => t.id === tool5.id);
24047
24228
  }
24048
24229
  const hydratedTool = {
24049
- ...tool4,
24230
+ ...tool5,
24050
24231
  name: hydrated?.name || "",
24051
24232
  description: hydrated?.description || "",
24052
- category: tool4?.category || "default",
24233
+ category: tool5?.category || "default",
24053
24234
  needsApproval: true
24054
24235
  };
24055
24236
  console.log("[EXULU] hydratedTool", hydratedTool);
@@ -24059,7 +24240,7 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
24059
24240
  );
24060
24241
  if (args.project) {
24061
24242
  const hasAgentic = result.tools.some(
24062
- (tool4) => tool4?.id === "agentic_context_search"
24243
+ (tool5) => tool5?.id === "agentic_context_search"
24063
24244
  );
24064
24245
  if (!hasAgentic) {
24065
24246
  const instance2 = createAgenticRetrievalTool({
@@ -24080,7 +24261,7 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
24080
24261
  }
24081
24262
  }
24082
24263
  }
24083
- result.tools = result.tools.filter((tool4) => tool4 !== null);
24264
+ result.tools = result.tools.filter((tool5) => tool5 !== null);
24084
24265
  } else {
24085
24266
  result.tools = [];
24086
24267
  }
@@ -25652,6 +25833,837 @@ var applyAgentGuestFieldTransforms = async (input) => {
25652
25833
  return input;
25653
25834
  };
25654
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
+
25655
26667
  // src/graphql/mutations/should-generate-embeddings.ts
25656
26668
  init_cjs_shims();
25657
26669
  var shouldGenerateEmbeddings = ({
@@ -26408,6 +27420,9 @@ function createMutations(table, contexts, tools, config) {
26408
27420
  insert.onConflict().merge();
26409
27421
  }
26410
27422
  let results = await insert;
27423
+ if (tableNamePlural === "agents" && args.upsert) {
27424
+ await afterAgentWrite(db2, results[0], args.input);
27425
+ }
26411
27426
  if (table.RBAC && rbacData && results[0]) {
26412
27427
  await handleRBACUpdate(db2, table.name.singular, results[0].id, rbacData, []);
26413
27428
  }
@@ -26491,6 +27506,9 @@ function createMutations(table, contexts, tools, config) {
26491
27506
  if (!result?.id) {
26492
27507
  throw new Error("Something went wrong with the update, no id returned.");
26493
27508
  }
27509
+ if (tableNamePlural === "agents") {
27510
+ await afterAgentWrite(db2, result, args.input);
27511
+ }
26494
27512
  if (table.RBAC && rbacData && result.id) {
26495
27513
  const existingRbacRecords = await db2.from("rbac").where({
26496
27514
  entity: table.name.singular,
@@ -26575,6 +27593,9 @@ function createMutations(table, contexts, tools, config) {
26575
27593
  const requestedFields = getRequestedFields(info);
26576
27594
  const columns = await db2(tableNamePlural).columnInfo();
26577
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
+ }
26578
27599
  const { job } = await postprocessUpdate({
26579
27600
  table,
26580
27601
  requestedFields,
@@ -26634,6 +27655,12 @@ function createMutations(table, contexts, tools, config) {
26634
27655
  tools,
26635
27656
  result
26636
27657
  });
27658
+ if (tableNamePlural === "agents") {
27659
+ await afterAgentDelete(db2, id);
27660
+ }
27661
+ if (tableNamePlural === "users") {
27662
+ await afterUserDeleteBestEffort(db2, id);
27663
+ }
26637
27664
  return finalizeRequestedFields({
26638
27665
  args,
26639
27666
  table,
@@ -26674,6 +27701,12 @@ function createMutations(table, contexts, tools, config) {
26674
27701
  tools,
26675
27702
  result
26676
27703
  });
27704
+ if (tableNamePlural === "agents") {
27705
+ await afterAgentDelete(db2, result.id);
27706
+ }
27707
+ if (tableNamePlural === "users") {
27708
+ await afterUserDeleteBestEffort(db2, result.id);
27709
+ }
26677
27710
  return finalizeRequestedFields({
26678
27711
  args,
26679
27712
  table,
@@ -27242,12 +28275,12 @@ var bullmq = {
27242
28275
  if (!data.inputs) {
27243
28276
  throw new Error(`Missing property "inputs" in data for job ${id}.`);
27244
28277
  }
27245
- 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") {
27246
28279
  throw new Error(
27247
- `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".`
27248
28281
  );
27249
28282
  }
27250
- 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) {
27251
28284
  throw new Error(
27252
28285
  `Either a workflow, embedder, processor, eval_run, eval_functions or source must be set for job ${id}.`
27253
28286
  );
@@ -28206,12 +29239,12 @@ var generateSync = async ({
28206
29239
  );
28207
29240
  const turnBudget = resolveTurnStepBudget(maxStepCount, agent);
28208
29241
  const includesContextSearchTool = currentTools?.some(
28209
- (tool4) => tool4.name.toLowerCase().includes("context_search") || tool4.id.includes("context_search") || tool4.type === "context"
29242
+ (tool5) => tool5.name.toLowerCase().includes("context_search") || tool5.id.includes("context_search") || tool5.type === "context"
28210
29243
  );
28211
29244
  const includesWebSearchTool = currentTools?.some(
28212
- (tool4) => tool4.name.toLowerCase().includes("web_search") || tool4.id.includes("web_search") || tool4.type === "web_search"
29245
+ (tool5) => tool5.name.toLowerCase().includes("web_search") || tool5.id.includes("web_search") || tool5.type === "web_search"
28213
29246
  );
28214
- console.log("[EXULU] Current tools: " + currentTools?.map((tool4) => tool4.name).join("\n"));
29247
+ console.log("[EXULU] Current tools: " + currentTools?.map((tool5) => tool5.name).join("\n"));
28215
29248
  console.log("[EXULU] Includes context search tool: " + includesContextSearchTool);
28216
29249
  if (includesContextSearchTool && shouldShowSourcesToUser(toolConfigs, user)) {
28217
29250
  system += `
@@ -28665,12 +29698,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
28665
29698
  );
28666
29699
  console.log("[EXULU] Converted tools", Object.keys(tools));
28667
29700
  const includesContextSearchTool = currentTools?.some(
28668
- (tool4) => tool4.name.toLowerCase().includes("context_search") || tool4.id.includes("context_search") || tool4.type === "context"
29701
+ (tool5) => tool5.name.toLowerCase().includes("context_search") || tool5.id.includes("context_search") || tool5.type === "context"
28669
29702
  );
28670
29703
  const includesWebSearchTool = currentTools?.some(
28671
- (tool4) => tool4.name.toLowerCase().includes("web_search") || tool4.id.includes("web_search") || tool4.type === "web_search"
29704
+ (tool5) => tool5.name.toLowerCase().includes("web_search") || tool5.id.includes("web_search") || tool5.type === "web_search"
28672
29705
  );
28673
- console.log("[EXULU] Current tools: " + currentTools?.map((tool4) => tool4.name).join("\n"));
29706
+ console.log("[EXULU] Current tools: " + currentTools?.map((tool5) => tool5.name).join("\n"));
28674
29707
  console.log("[EXULU] Includes context search tool: " + includesContextSearchTool);
28675
29708
  console.log("[EXULU] Includes web search tool: " + includesWebSearchTool);
28676
29709
  if (includesContextSearchTool && shouldShowSourcesToUser(toolConfigs, user)) {
@@ -28930,7 +29963,7 @@ var getEnabledTools = async (agent, allExuluTools, allContexts, disabledTools =
28930
29963
  }
28931
29964
  console.log("[EXULU] available tools", enabledTools?.length);
28932
29965
  console.log("[EXULU] disabled tools", disabledTools?.length);
28933
- enabledTools = enabledTools.filter((tool4) => !disabledTools.includes(tool4.id));
29966
+ enabledTools = enabledTools.filter((tool5) => !disabledTools.includes(tool5.id));
28934
29967
  return enabledTools;
28935
29968
  };
28936
29969
 
@@ -28981,9 +30014,9 @@ var resolveContextWindow = async ({
28981
30014
  // ee/workers.ts
28982
30015
  init_client();
28983
30016
  init_prune_job_results();
28984
- var import_api = require("@opentelemetry/api");
30017
+ var import_api2 = require("@opentelemetry/api");
28985
30018
  var import_uuid3 = require("uuid");
28986
- var import_ai8 = require("ai");
30019
+ var import_ai9 = require("ai");
28987
30020
  var import_crypto_js6 = require("crypto-js");
28988
30021
  init_statistics();
28989
30022
  init_jobs();
@@ -29534,6 +30567,927 @@ async function handleEmailIntake(payload, deps) {
29534
30567
  return fireRun({ db: db2, deps, trigger, email, s3Key: payload.s3Key, jobResultId });
29535
30568
  }
29536
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
+
29537
31491
  // src/exulu/routines/flow-steps.ts
29538
31492
  init_cjs_shims();
29539
31493
  var EMAIL_RUN_VARIABLES = /* @__PURE__ */ new Set([
@@ -30023,18 +31977,18 @@ var startPoolMonitoring = () => {
30023
31977
  if (poolStats) {
30024
31978
  const used = poolStats.numUsed?.() || 0;
30025
31979
  const free = poolStats.numFree?.() || 0;
30026
- const pending = poolStats.numPendingAcquires?.() || 0;
31980
+ const pending2 = poolStats.numPendingAcquires?.() || 0;
30027
31981
  const total = used + free;
30028
31982
  console.log("[EXULU] Connection pool health check:", {
30029
31983
  used,
30030
31984
  free,
30031
- pending,
31985
+ pending: pending2,
30032
31986
  total,
30033
31987
  utilization: total > 0 ? `${Math.round(used / total * 100)}%` : "0%"
30034
31988
  });
30035
- if (pending > 10) {
31989
+ if (pending2 > 10) {
30036
31990
  console.warn(
30037
- `[EXULU] WARNING: ${pending} jobs waiting for database connections. Consider increasing pool size or reducing worker concurrency.`
31991
+ `[EXULU] WARNING: ${pending2} jobs waiting for database connections. Consider increasing pool size or reducing worker concurrency.`
30038
31992
  );
30039
31993
  }
30040
31994
  }
@@ -30873,6 +32827,13 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
30873
32827
  );
30874
32828
  return { result, metadata: {} };
30875
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
+ }
30876
32837
  throw new Error(`Invalid job type: ${data.type} for job ${bullmqJob.name}.`);
30877
32838
  } catch (error) {
30878
32839
  console.error(
@@ -31255,7 +33216,7 @@ var processUiMessagesFlow = async ({
31255
33216
  user,
31256
33217
  // Legacy blanket pre-approval unless this run respects
31257
33218
  // approvals (spec §5.2 — auto_approve_tools = false routines).
31258
- approvedTools: respectToolApprovals ? void 0 : tools.map((tool4) => "tool-" + sanitizeToolName(tool4.name)),
33219
+ approvedTools: respectToolApprovals ? void 0 : tools.map((tool5) => "tool-" + sanitizeToolName(tool5.name)),
31259
33220
  instructions: agent.instructions,
31260
33221
  session: sessionId,
31261
33222
  previousMessages: messageHistory.messages,
@@ -31293,7 +33254,7 @@ var processUiMessagesFlow = async ({
31293
33254
  // message onto one frozen-createdAt row — which sorts the tool
31294
33255
  // approval to the top of the transcript and leaves it out of the
31295
33256
  // last-message slot the approval handler acts on (buttons inert).
31296
- generateMessageId: (0, import_ai8.createIdGenerator)({
33257
+ generateMessageId: (0, import_ai9.createIdGenerator)({
31297
33258
  prefix: "msg_",
31298
33259
  size: 16
31299
33260
  }),
@@ -31488,7 +33449,7 @@ var applyRoutineRunFilters = (query, args, allowedWorkflowIds, doneKeys) => {
31488
33449
  }
31489
33450
  return q;
31490
33451
  };
31491
- var parseMaybeJson = (value) => {
33452
+ var parseMaybeJson2 = (value) => {
31492
33453
  if (value == null) {
31493
33454
  return null;
31494
33455
  }
@@ -31503,18 +33464,18 @@ var parseMaybeJson = (value) => {
31503
33464
  };
31504
33465
  var mapRoutineRunRow = (row, routineById) => {
31505
33466
  const routine = row.workflow ? routineById.get(row.workflow) : void 0;
31506
- const tokens = parseMaybeJson(row.metadata)?.tokens;
33467
+ const tokens = parseMaybeJson2(row.metadata)?.tokens;
31507
33468
  return {
31508
33469
  id: row.id,
31509
33470
  job_id: row.job_id ?? null,
31510
33471
  state: row.state,
31511
33472
  trigger: row.trigger ?? null,
31512
- trigger_metadata: parseMaybeJson(row.trigger_metadata),
33473
+ trigger_metadata: parseMaybeJson2(row.trigger_metadata),
31513
33474
  session: row.session ?? null,
31514
33475
  workflow: row.workflow,
31515
33476
  workflowName: routine?.name ?? null,
31516
33477
  agent: routine?.agent ?? null,
31517
- error: parseMaybeJson(row.error),
33478
+ error: parseMaybeJson2(row.error),
31518
33479
  tries: row.tries ?? null,
31519
33480
  createdAt: row.createdAt,
31520
33481
  updatedAt: row.updatedAt,
@@ -31523,7 +33484,7 @@ var mapRoutineRunRow = (row, routineById) => {
31523
33484
  costUsd: tokens?.costUsd ?? null,
31524
33485
  work_status: row.work_status ?? null,
31525
33486
  work_status_updated_at: row.work_status_updated_at ?? null,
31526
- work_status_updated_by: parseMaybeJson(row.work_status_updated_by)
33487
+ work_status_updated_by: parseMaybeJson2(row.work_status_updated_by)
31527
33488
  };
31528
33489
  };
31529
33490
 
@@ -31541,7 +33502,7 @@ init_rbac_update();
31541
33502
 
31542
33503
  // src/exulu/recall/service.ts
31543
33504
  init_cjs_shims();
31544
- var import_ai9 = require("ai");
33505
+ var import_ai10 = require("ai");
31545
33506
  init_singleton();
31546
33507
  init_client();
31547
33508
  init_resolve_model();
@@ -31823,7 +33784,7 @@ function resolveBotIdentity(request3, workspace) {
31823
33784
  }
31824
33785
 
31825
33786
  // src/exulu/recall/service.ts
31826
- var TABLE2 = "transcription_jobs";
33787
+ var TABLE5 = "transcription_jobs";
31827
33788
  var RECONCILE_STALE_MS = 10 * 60 * 1e3;
31828
33789
  var RECONCILE_PROBE_QUIET_MS = 60 * 60 * 1e3;
31829
33790
  var RECONCILE_GIVE_UP_MS = 24 * 60 * 60 * 1e3;
@@ -31861,7 +33822,7 @@ var recallService = {
31861
33822
  const startOfMonth = new Date(
31862
33823
  Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)
31863
33824
  );
31864
- const [row] = await db2(TABLE2).where({ source: "recall" }).andWhere("createdAt", ">=", startOfMonth).whereNotNull("duration_seconds").sum({ total: "duration_seconds" });
33825
+ const [row] = await db2(TABLE5).where({ source: "recall" }).andWhere("createdAt", ">=", startOfMonth).whereNotNull("duration_seconds").sum({ total: "duration_seconds" });
31865
33826
  return Number(row?.total ?? 0);
31866
33827
  },
31867
33828
  /**
@@ -31906,7 +33867,7 @@ var recallService = {
31906
33867
  const { db: db2 } = await postgresClient();
31907
33868
  const now = /* @__PURE__ */ new Date();
31908
33869
  const joinAt = input.join_at ? new Date(input.join_at) : now;
31909
- const [inserted] = await db2(TABLE2).insert({
33870
+ const [inserted] = await db2(TABLE5).insert({
31910
33871
  source: "recall",
31911
33872
  status: "queued",
31912
33873
  title: input.title ?? null,
@@ -31939,10 +33900,10 @@ var recallService = {
31939
33900
  notifyChat: notifyChat ? { message: "This meeting is being recorded and transcribed." } : void 0,
31940
33901
  retentionHours: settings.videoRetentionHours.value
31941
33902
  });
31942
- const [updated] = await db2(TABLE2).where({ id: inserted.id }).update({ recall_bot_id: bot.id, updatedAt: /* @__PURE__ */ new Date() }).returning("*");
33903
+ const [updated] = await db2(TABLE5).where({ id: inserted.id }).update({ recall_bot_id: bot.id, updatedAt: /* @__PURE__ */ new Date() }).returning("*");
31943
33904
  return this._row(updated);
31944
33905
  } catch (err4) {
31945
- const [failed] = await db2(TABLE2).where({ id: inserted.id }).update({
33906
+ const [failed] = await db2(TABLE5).where({ id: inserted.id }).update({
31946
33907
  status: "failed",
31947
33908
  error: err4.message,
31948
33909
  updatedAt: /* @__PURE__ */ new Date()
@@ -31995,7 +33956,7 @@ var recallService = {
31995
33956
  return;
31996
33957
  }
31997
33958
  const { db: db2 } = await postgresClient();
31998
- const claimed = await db2(TABLE2).where({ id: jobId }).whereNotIn("status", [
33959
+ const claimed = await db2(TABLE5).where({ id: jobId }).whereNotIn("status", [
31999
33960
  "transcribing",
32000
33961
  "awaiting_review",
32001
33962
  "reviewed",
@@ -32012,7 +33973,7 @@ var recallService = {
32012
33973
  return;
32013
33974
  }
32014
33975
  try {
32015
- const row = await db2(TABLE2).where({ id: jobId }).first();
33976
+ const row = await db2(TABLE5).where({ id: jobId }).first();
32016
33977
  const transcript = await recallClient.createAsyncTranscript(
32017
33978
  recordingId,
32018
33979
  row?.language || "auto"
@@ -32024,7 +33985,7 @@ var recallService = {
32024
33985
  },
32025
33986
  async _onTranscriptDone(jobId, transcriptId, recordingId) {
32026
33987
  const { db: db2 } = await postgresClient();
32027
- const dbRow = await db2(TABLE2).where({ id: jobId }).first();
33988
+ const dbRow = await db2(TABLE5).where({ id: jobId }).first();
32028
33989
  if (!dbRow) return;
32029
33990
  const job = this._row(dbRow);
32030
33991
  if ((job.status === "awaiting_review" || job.status === "reviewed" || job.status === "saved") && job.raw_segments && job.raw_segments.length > 0) {
@@ -32117,7 +34078,7 @@ var recallService = {
32117
34078
  */
32118
34079
  async runPostProcessing(jobId) {
32119
34080
  const { db: db2 } = await postgresClient();
32120
- const dbRow = await db2(TABLE2).where({ id: jobId }).first();
34081
+ const dbRow = await db2(TABLE5).where({ id: jobId }).first();
32121
34082
  if (!dbRow) return [];
32122
34083
  const job = this._row(dbRow);
32123
34084
  const prompts = job.post_processing_prompts ?? [];
@@ -32130,7 +34091,7 @@ var recallService = {
32130
34091
  log3(`post-processing for job ${jobId} skipped: no transcript.`);
32131
34092
  return [];
32132
34093
  }
32133
- const claimed = await db2(TABLE2).where({ id: jobId }).whereRaw(
34094
+ const claimed = await db2(TABLE5).where({ id: jobId }).whereRaw(
32134
34095
  `(post_processing_outputs IS NULL OR (post_processing_outputs::text = '[]' AND "updatedAt" < ?))`,
32135
34096
  [new Date(Date.now() - POST_PROCESSING_REDO_STALE_MS)]
32136
34097
  ).update({ post_processing_outputs: "[]", updatedAt: /* @__PURE__ */ new Date() });
@@ -32153,7 +34114,7 @@ var recallService = {
32153
34114
  async _mergeOutputs(jobId, entries) {
32154
34115
  const { db: db2 } = await postgresClient();
32155
34116
  for (let attempt = 1; attempt <= 5; attempt++) {
32156
- const row = await db2(TABLE2).where({ id: jobId }).first();
34117
+ const row = await db2(TABLE5).where({ id: jobId }).first();
32157
34118
  if (!row) return entries;
32158
34119
  const raw = row.post_processing_outputs ?? null;
32159
34120
  const snapshot = raw == null ? null : typeof raw === "string" ? raw : JSON.stringify(raw);
@@ -32166,7 +34127,7 @@ var recallService = {
32166
34127
  ),
32167
34128
  ...entries
32168
34129
  ];
32169
- const updated = await db2(TABLE2).where({ id: jobId }).whereRaw(
34130
+ const updated = await db2(TABLE5).where({ id: jobId }).whereRaw(
32170
34131
  "post_processing_outputs::jsonb IS NOT DISTINCT FROM ?::jsonb",
32171
34132
  [snapshot]
32172
34133
  ).update({
@@ -32186,7 +34147,7 @@ var recallService = {
32186
34147
  */
32187
34148
  async runOnePostProcessing(jobId, promptId, agentId) {
32188
34149
  const { db: db2 } = await postgresClient();
32189
- const dbRow = await db2(TABLE2).where({ id: jobId }).first();
34150
+ const dbRow = await db2(TABLE5).where({ id: jobId }).first();
32190
34151
  if (!dbRow) throw new Error(`transcription_job ${jobId} not found`);
32191
34152
  const job = this._row(dbRow);
32192
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;
@@ -32221,7 +34182,7 @@ var recallService = {
32221
34182
  job.speakers ?? {},
32222
34183
  { timestamps: true }
32223
34184
  );
32224
- const { text } = await (0, import_ai9.generateText)({
34185
+ const { text } = await (0, import_ai10.generateText)({
32225
34186
  model: resolved.languageModel,
32226
34187
  system: withGlossary(agent.instructions, agent.tools) || void 0,
32227
34188
  prompt: `${prompt.content}
@@ -32269,10 +34230,10 @@ ${transcriptText}`,
32269
34230
  if (!recallEnabled()) return 0;
32270
34231
  const { db: db2 } = await postgresClient();
32271
34232
  const now = Date.now();
32272
- const stuck = await db2(TABLE2).where({ source: "recall" }).whereIn("status", ["queued", "transcribing"]).whereRaw(`("join_at" IS NULL OR "join_at" < ?)`, [
34233
+ const stuck = await db2(TABLE5).where({ source: "recall" }).whereIn("status", ["queued", "transcribing"]).whereRaw(`("join_at" IS NULL OR "join_at" < ?)`, [
32273
34234
  new Date(now - RECONCILE_STALE_MS)
32274
34235
  ]).where("updatedAt", "<", new Date(now - RECONCILE_STALE_MS)).orderBy("updatedAt", "asc").limit(limit);
32275
- const redo = await db2(TABLE2).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(
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(
32276
34237
  "(post_processing_outputs IS NULL OR post_processing_outputs::text = '[]')"
32277
34238
  ).where("updatedAt", "<", new Date(now - POST_PROCESSING_REDO_STALE_MS)).orderBy("updatedAt", "asc").limit(limit);
32278
34239
  let acted = 0;
@@ -32408,7 +34369,7 @@ ${transcriptText}`,
32408
34369
  });
32409
34370
  } else {
32410
34371
  const { db: db2 } = await postgresClient();
32411
- const claimed = await db2(TABLE2).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() });
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() });
32412
34373
  if (!claimed) return false;
32413
34374
  log3(
32414
34375
  `reconcile: re-requesting transcript for job ${job.id} (lost before createAsyncTranscript)`
@@ -32458,16 +34419,16 @@ ${transcriptText}`,
32458
34419
  async _findJob(botId, recordingId, transcriptId) {
32459
34420
  const { db: db2 } = await postgresClient();
32460
34421
  let dbRow;
32461
- if (botId) dbRow = await db2(TABLE2).where({ recall_bot_id: botId }).first();
34422
+ if (botId) dbRow = await db2(TABLE5).where({ recall_bot_id: botId }).first();
32462
34423
  if (!dbRow && recordingId)
32463
- dbRow = await db2(TABLE2).where({ recall_recording_id: recordingId }).first();
34424
+ dbRow = await db2(TABLE5).where({ recall_recording_id: recordingId }).first();
32464
34425
  if (!dbRow && transcriptId)
32465
- dbRow = await db2(TABLE2).where({ recall_transcript_id: transcriptId }).first();
34426
+ dbRow = await db2(TABLE5).where({ recall_transcript_id: transcriptId }).first();
32466
34427
  return dbRow ? this._row(dbRow) : null;
32467
34428
  },
32468
34429
  async _update(id, patch) {
32469
34430
  const { db: db2 } = await postgresClient();
32470
- await db2(TABLE2).where({ id }).update({ ...patch, updatedAt: /* @__PURE__ */ new Date() });
34431
+ await db2(TABLE5).where({ id }).update({ ...patch, updatedAt: /* @__PURE__ */ new Date() });
32471
34432
  },
32472
34433
  async _fail(id, error) {
32473
34434
  await this._update(id, { status: "failed", error });
@@ -32600,7 +34561,7 @@ async function assertOwnsTranscriptionJob(db2, user, id) {
32600
34561
  }
32601
34562
 
32602
34563
  // src/exulu/transcription/service.ts
32603
- var TABLE3 = "transcription_jobs";
34564
+ var TABLE6 = "transcription_jobs";
32604
34565
  var log4 = (msg) => console.log(`[EXULU-TRANSCRIPTION] ${msg}`);
32605
34566
  var parseJsonField = (v) => {
32606
34567
  if (v == null) return null;
@@ -32639,7 +34600,7 @@ var transcriptionService = {
32639
34600
  }
32640
34601
  const { db: db2 } = await postgresClient();
32641
34602
  const now = /* @__PURE__ */ new Date();
32642
- const [inserted] = await db2(TABLE3).insert({
34603
+ const [inserted] = await db2(TABLE6).insert({
32643
34604
  audio_s3key: input.s3Key,
32644
34605
  title: input.title ?? input.filename,
32645
34606
  status: "queued",
@@ -32662,14 +34623,14 @@ var transcriptionService = {
32662
34623
  num_speakers: input.num_speakers ?? void 0,
32663
34624
  hotwords: input.hotwords
32664
34625
  });
32665
- const [updated] = await db2(TABLE3).where({ id: row.id }).update({
34626
+ const [updated] = await db2(TABLE6).where({ id: row.id }).update({
32666
34627
  whisper_job_id: submitted.job_id,
32667
34628
  status: "transcribing",
32668
34629
  updatedAt: /* @__PURE__ */ new Date()
32669
34630
  }).returning("*");
32670
34631
  return this._rowFromDb(updated);
32671
34632
  } catch (err4) {
32672
- const [failed] = await db2(TABLE3).where({ id: row.id }).update({
34633
+ const [failed] = await db2(TABLE6).where({ id: row.id }).update({
32673
34634
  status: "failed",
32674
34635
  error: err4.message,
32675
34636
  updatedAt: /* @__PURE__ */ new Date()
@@ -32686,7 +34647,7 @@ var transcriptionService = {
32686
34647
  async pollOnce(maxPerTick = 50) {
32687
34648
  if (!transcriptionClient.isConfigured()) return;
32688
34649
  const { db: db2 } = await postgresClient();
32689
- const rows = await db2(TABLE3).where({ status: "transcribing" }).whereNotNull("whisper_job_id").limit(maxPerTick);
34650
+ const rows = await db2(TABLE6).where({ status: "transcribing" }).whereNotNull("whisper_job_id").limit(maxPerTick);
32690
34651
  for (const dbRow of rows) {
32691
34652
  const row = this._rowFromDb(dbRow);
32692
34653
  if (!row.whisper_job_id) continue;
@@ -32696,7 +34657,7 @@ var transcriptionService = {
32696
34657
  } catch (err4) {
32697
34658
  const code = err4.code;
32698
34659
  if (code === "JOB_NOT_FOUND") {
32699
- await db2(TABLE3).where({ id: row.id }).update({
34660
+ await db2(TABLE6).where({ id: row.id }).update({
32700
34661
  status: "failed",
32701
34662
  error: "lost on server restart",
32702
34663
  updatedAt: /* @__PURE__ */ new Date()
@@ -32712,14 +34673,14 @@ var transcriptionService = {
32712
34673
  async _applyJobUpdate(row, job) {
32713
34674
  const { db: db2 } = await postgresClient();
32714
34675
  if ((job.status === "queued" || job.status === "running") && job.duration_seconds != null && row.duration_seconds !== job.duration_seconds) {
32715
- await db2(TABLE3).where({ id: row.id }).update({
34676
+ await db2(TABLE6).where({ id: row.id }).update({
32716
34677
  duration_seconds: job.duration_seconds,
32717
34678
  updatedAt: /* @__PURE__ */ new Date()
32718
34679
  });
32719
34680
  }
32720
34681
  if (job.status === "running" || job.status === "queued") return;
32721
34682
  if (job.status === "completed") {
32722
- await db2(TABLE3).where({ id: row.id }).update({
34683
+ await db2(TABLE6).where({ id: row.id }).update({
32723
34684
  status: "awaiting_review",
32724
34685
  raw_segments: JSON.stringify(job.segments ?? []),
32725
34686
  language: job.language ?? null,
@@ -32738,7 +34699,7 @@ var transcriptionService = {
32738
34699
  return;
32739
34700
  }
32740
34701
  if (job.status === "failed") {
32741
- await db2(TABLE3).where({ id: row.id }).update({
34702
+ await db2(TABLE6).where({ id: row.id }).update({
32742
34703
  status: "failed",
32743
34704
  error: job.error ?? "transcription failed",
32744
34705
  updatedAt: /* @__PURE__ */ new Date()
@@ -32746,7 +34707,7 @@ var transcriptionService = {
32746
34707
  return;
32747
34708
  }
32748
34709
  if (job.status === "cancelled") {
32749
- await db2(TABLE3).where({ id: row.id }).update({
34710
+ await db2(TABLE6).where({ id: row.id }).update({
32750
34711
  status: "cancelled",
32751
34712
  updatedAt: /* @__PURE__ */ new Date()
32752
34713
  });
@@ -32754,7 +34715,7 @@ var transcriptionService = {
32754
34715
  },
32755
34716
  async cancelJob(id) {
32756
34717
  const { db: db2 } = await postgresClient();
32757
- const dbRow = await db2(TABLE3).where({ id }).first();
34718
+ const dbRow = await db2(TABLE6).where({ id }).first();
32758
34719
  if (!dbRow) throw new Error(`transcription_job ${id} not found`);
32759
34720
  const row = this._rowFromDb(dbRow);
32760
34721
  if (row.whisper_job_id && transcriptionClient.isConfigured()) {
@@ -32767,7 +34728,7 @@ var transcriptionService = {
32767
34728
  }
32768
34729
  }
32769
34730
  }
32770
- const [updated] = await db2(TABLE3).where({ id }).update({ status: "cancelled", updatedAt: /* @__PURE__ */ new Date() }).returning("*");
34731
+ const [updated] = await db2(TABLE6).where({ id }).update({ status: "cancelled", updatedAt: /* @__PURE__ */ new Date() }).returning("*");
32771
34732
  return this._rowFromDb(updated);
32772
34733
  },
32773
34734
  /**
@@ -32790,7 +34751,7 @@ var transcriptionService = {
32790
34751
  */
32791
34752
  async markReviewed(id, input) {
32792
34753
  const { db: db2 } = await postgresClient();
32793
- const dbRow = await db2(TABLE3).where({ id }).first();
34754
+ const dbRow = await db2(TABLE6).where({ id }).first();
32794
34755
  if (!dbRow) throw new Error(`transcription_job ${id} not found`);
32795
34756
  const row = this._rowFromDb(dbRow);
32796
34757
  if (row.status !== "awaiting_review" && row.status !== "reviewed") {
@@ -32802,7 +34763,7 @@ var transcriptionService = {
32802
34763
  throw new Error(`transcription_job ${id} has no raw_segments to review`);
32803
34764
  }
32804
34765
  const resolvedCorrected = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments ?? null;
32805
- const [updated] = await db2(TABLE3).where({ id }).update({
34766
+ const [updated] = await db2(TABLE6).where({ id }).update({
32806
34767
  status: "reviewed",
32807
34768
  reviewed_at: row.reviewed_at ?? /* @__PURE__ */ new Date(),
32808
34769
  title: input.title ?? row.title,
@@ -32829,7 +34790,7 @@ var transcriptionService = {
32829
34790
  */
32830
34791
  async finalize(id, input) {
32831
34792
  const { db: db2 } = await postgresClient();
32832
- const dbRow = await db2(TABLE3).where({ id }).first();
34793
+ const dbRow = await db2(TABLE6).where({ id }).first();
32833
34794
  if (!dbRow) throw new Error(`transcription_job ${id} not found`);
32834
34795
  const row = this._rowFromDb(dbRow);
32835
34796
  if (row.status !== "awaiting_review" && row.status !== "reviewed" && row.status !== "saved") {
@@ -32874,7 +34835,7 @@ var transcriptionService = {
32874
34835
  );
32875
34836
  item = result.item;
32876
34837
  } catch (err4) {
32877
- await db2(TABLE3).where({ id }).update({
34838
+ await db2(TABLE6).where({ id }).update({
32878
34839
  speakers: JSON.stringify(input.speakers),
32879
34840
  error: `Failed to save: ${err4.message}`,
32880
34841
  updatedAt: /* @__PURE__ */ new Date()
@@ -32920,7 +34881,7 @@ var transcriptionService = {
32920
34881
  }
32921
34882
  }
32922
34883
  const nextCorrectedSegments = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments;
32923
- const [updated] = await db2(TABLE3).where({ id }).update({
34884
+ const [updated] = await db2(TABLE6).where({ id }).update({
32924
34885
  status: "saved",
32925
34886
  reviewed_at: row.reviewed_at ?? /* @__PURE__ */ new Date(),
32926
34887
  saved_item_id: itemId,
@@ -32961,7 +34922,7 @@ var transcriptionService = {
32961
34922
  if (err4 instanceof TranscriptionJobAccessError) return void 0;
32962
34923
  throw err4;
32963
34924
  }
32964
- const dbRow = await db2(TABLE3).where({ id: jobId }).first();
34925
+ const dbRow = await db2(TABLE6).where({ id: jobId }).first();
32965
34926
  if (!dbRow) return void 0;
32966
34927
  const row = this._rowFromDb(dbRow);
32967
34928
  return {
@@ -33001,7 +34962,7 @@ var transcriptionService = {
33001
34962
  init_cjs_shims();
33002
34963
  init_client();
33003
34964
  init_supervisor();
33004
- var TABLE4 = "transcription_jobs";
34965
+ var TABLE7 = "transcription_jobs";
33005
34966
  var log5 = (msg) => console.log(`[EXULU-LIVE-RECORDING] ${msg}`);
33006
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.";
33007
34968
  function liveRecordingEnabled() {
@@ -33027,7 +34988,7 @@ var liveRecordingService = {
33027
34988
  async start(input) {
33028
34989
  const { db: db2 } = await postgresClient();
33029
34990
  const now = /* @__PURE__ */ new Date();
33030
- const [inserted] = await db2(TABLE4).insert({
34991
+ const [inserted] = await db2(TABLE7).insert({
33031
34992
  source: "live",
33032
34993
  status: "recording",
33033
34994
  chunk_count: 0,
@@ -33057,7 +35018,7 @@ var liveRecordingService = {
33057
35018
  text: input.text,
33058
35019
  speaker: "unknown"
33059
35020
  };
33060
- const affected = await db2(TABLE4).where({ id: input.id, status: "recording", chunk_count: input.seq }).update({
35021
+ const affected = await db2(TABLE7).where({ id: input.id, status: "recording", chunk_count: input.seq }).update({
33061
35022
  raw_segments: db2.raw("COALESCE(raw_segments, '[]'::jsonb) || ?::jsonb", [
33062
35023
  JSON.stringify([segment])
33063
35024
  ]),
@@ -33067,7 +35028,7 @@ var liveRecordingService = {
33067
35028
  updatedAt: /* @__PURE__ */ new Date()
33068
35029
  });
33069
35030
  if (affected === 1) return { kind: "appended", chunkCount: input.seq + 1 };
33070
- const row = await db2(TABLE4).select(["status", "chunk_count", "raw_segments"]).where({ id: input.id }).first();
35031
+ const row = await db2(TABLE7).select(["status", "chunk_count", "raw_segments"]).where({ id: input.id }).first();
33071
35032
  if (!row) throw new Error(`transcription_job ${input.id} not found`);
33072
35033
  if (row.status !== "recording") return { kind: "not_recording", status: row.status };
33073
35034
  const chunkCount = Number(row.chunk_count ?? 0);
@@ -33084,9 +35045,9 @@ var liveRecordingService = {
33084
35045
  if (typeof input.duration_seconds === "number" && input.duration_seconds > 0) {
33085
35046
  patch.duration_seconds = input.duration_seconds;
33086
35047
  }
33087
- const [updated] = await db2(TABLE4).where({ id, status: "recording" }).update(patch).returning("*");
35048
+ const [updated] = await db2(TABLE7).where({ id, status: "recording" }).update(patch).returning("*");
33088
35049
  if (!updated) {
33089
- const row = await db2(TABLE4).where({ id }).first();
35050
+ const row = await db2(TABLE7).where({ id }).first();
33090
35051
  if (!row) throw new Error(`transcription_job ${id} not found`);
33091
35052
  throw new Error(
33092
35053
  `transcription_job ${id} is in status '${row.status}'; can only stop from 'recording'`
@@ -34140,7 +36101,7 @@ function groupDuplicates(pairs, cap) {
34140
36101
  // src/exulu/memory/conflicts/scan.ts
34141
36102
  var INSERT_CHUNK = 500;
34142
36103
  var num5 = (v) => typeof v === "number" ? v : Number(v ?? 0) || 0;
34143
- var pool = async (items, limit, worker) => {
36104
+ var pool2 = async (items, limit, worker) => {
34144
36105
  let next = 0;
34145
36106
  const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
34146
36107
  while (next < items.length) {
@@ -34204,7 +36165,7 @@ async function runScan({ db: db2, context, user, judge, now = /* @__PURE__ */ ne
34204
36165
  const toJudge = needJudgement.slice(0, JUDGE_CALLS_PER_SCAN);
34205
36166
  unjudged += needJudgement.length - toJudge.length;
34206
36167
  const fresh = /* @__PURE__ */ new Map();
34207
- await pool(toJudge, JUDGE_CONCURRENCY, async (pair) => {
36168
+ await pool2(toJudge, JUDGE_CONCURRENCY, async (pair) => {
34208
36169
  const key = pairKey(context.id, pair.a, pair.b);
34209
36170
  try {
34210
36171
  const verdict = await judge(wordings.get(pair.a) ?? "", wordings.get(pair.b) ?? "", AbortSignal.timeout(JUDGE_TIMEOUT_MS));
@@ -34272,7 +36233,7 @@ async function runScan({ db: db2, context, user, judge, now = /* @__PURE__ */ ne
34272
36233
 
34273
36234
  // src/exulu/memory/conflicts/judge.ts
34274
36235
  init_cjs_shims();
34275
- var import_ai10 = require("ai");
36236
+ var import_ai11 = require("ai");
34276
36237
  var import_zod26 = require("zod");
34277
36238
  init_resolve_model();
34278
36239
  var schema = import_zod26.z.object({
@@ -34287,7 +36248,7 @@ Answer with JSON: verdict = "same" when both state the same fact or instruction
34287
36248
  async function makeModelJudge({ modelId, agent, user }) {
34288
36249
  const { languageModel } = await resolveModel({ modelId, agent, user, rbacBypass: true });
34289
36250
  return async (a, b, signal) => {
34290
- const { output } = await (0, import_ai10.generateText)({
36251
+ const { output } = await (0, import_ai11.generateText)({
34291
36252
  temperature: 0,
34292
36253
  model: languageModel,
34293
36254
  system: SYSTEM,
@@ -34298,7 +36259,7 @@ Memory B:
34298
36259
  ${b}`,
34299
36260
  maxRetries: 1,
34300
36261
  ...signal ? { abortSignal: signal } : {},
34301
- output: import_ai10.Output.object({ schema })
36262
+ output: import_ai11.Output.object({ schema })
34302
36263
  });
34303
36264
  return { verdict: output.verdict, reason: output.reason.slice(0, 160) };
34304
36265
  };
@@ -34306,14 +36267,14 @@ ${b}`,
34306
36267
  async function makeMergeSuggester({ modelId, agent, user }) {
34307
36268
  const { languageModel } = await resolveModel({ modelId, agent, user, rbacBypass: true });
34308
36269
  return async (members) => {
34309
- const { output } = await (0, import_ai10.generateText)({
36270
+ const { output } = await (0, import_ai11.generateText)({
34310
36271
  temperature: 0,
34311
36272
  model: languageModel,
34312
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 }.",
34313
36274
  prompt: members.map((m, i) => `Memory ${i + 1}:
34314
36275
  ${m.information}`).join("\n\n"),
34315
36276
  maxRetries: 1,
34316
- output: import_ai10.Output.object({ schema: import_zod26.z.object({ information: import_zod26.z.string().min(1).max(400) }) })
36277
+ output: import_ai11.Output.object({ schema: import_zod26.z.object({ information: import_zod26.z.string().min(1).max(400) }) })
34317
36278
  });
34318
36279
  const types = members.map((m) => m.type).filter((t) => !!t);
34319
36280
  const type = types.length ? [...types].sort((x, y) => types.filter((t) => t === y).length - types.filter((t) => t === x).length)[0] ?? null : null;
@@ -35596,12 +37557,12 @@ type EmbeddingModelOption {
35596
37557
  contextQueueNames: async () => {
35597
37558
  const names = /* @__PURE__ */ new Set();
35598
37559
  for (const ctx of contexts ?? []) {
35599
- const pending = [
37560
+ const pending2 = [
35600
37561
  ctx.processor?.config?.queue,
35601
37562
  ctx.embedder?.queue,
35602
37563
  ...(ctx.sources ?? []).map((source) => source.config?.queue)
35603
37564
  ];
35604
- for (const queue of pending) {
37565
+ for (const queue of pending2) {
35605
37566
  const config2 = await Promise.resolve(queue).catch(() => void 0);
35606
37567
  if (config2?.queue?.name) names.add(config2.queue.name);
35607
37568
  }
@@ -36879,7 +38840,7 @@ type EmbeddingModelOption {
36879
38840
  })
36880
38841
  );
36881
38842
  let agenticRetrievalTool = void 0;
36882
- const filtered = agentTools.filter((tool4) => tool4 !== null);
38843
+ const filtered = agentTools.filter((tool5) => tool5 !== null);
36883
38844
  let allTools = [...filtered, ...tools];
36884
38845
  if (contexts?.length) {
36885
38846
  agenticRetrievalTool = createAgenticRetrievalTool({
@@ -36899,21 +38860,21 @@ type EmbeddingModelOption {
36899
38860
  if (search && search.trim()) {
36900
38861
  const searchTerm = search.toLowerCase().trim();
36901
38862
  allTools = allTools.filter(
36902
- (tool4) => tool4.name?.toLowerCase().includes(searchTerm) || tool4.description?.toLowerCase().includes(searchTerm)
38863
+ (tool5) => tool5.name?.toLowerCase().includes(searchTerm) || tool5.description?.toLowerCase().includes(searchTerm)
36903
38864
  );
36904
38865
  }
36905
38866
  if (category && category.trim()) {
36906
- allTools = allTools.filter((tool4) => tool4.category === category);
38867
+ allTools = allTools.filter((tool5) => tool5.category === category);
36907
38868
  }
36908
38869
  const total = allTools.length;
36909
38870
  const start = page * limit;
36910
38871
  const end = start + limit;
36911
38872
  const paginatedTools = allTools.slice(start, end);
36912
38873
  return {
36913
- items: paginatedTools.map((tool4) => {
38874
+ items: paginatedTools.map((tool5) => {
36914
38875
  const object = {};
36915
38876
  requestedFields.forEach((field) => {
36916
- object[field] = tool4[field];
38877
+ object[field] = tool5[field];
36917
38878
  });
36918
38879
  return object;
36919
38880
  }),
@@ -36923,7 +38884,7 @@ type EmbeddingModelOption {
36923
38884
  };
36924
38885
  };
36925
38886
  resolvers2.Query["toolCategories"] = async () => {
36926
- const array = tools.map((tool4) => tool4.category).filter((category) => category && typeof category === "string");
38887
+ const array = tools.map((tool5) => tool5.category).filter((category) => category && typeof category === "string");
36927
38888
  array.push("contexts");
36928
38889
  array.push("agents");
36929
38890
  return [...new Set(array)].sort();
@@ -37216,7 +39177,7 @@ var import_crypto_js7 = require("crypto-js");
37216
39177
  var import_openai = require("openai");
37217
39178
  var import_fs5 = __toESM(require("fs"), 1);
37218
39179
  var import_node_crypto24 = require("crypto");
37219
- var import_api2 = require("@opentelemetry/api");
39180
+ var import_api3 = require("@opentelemetry/api");
37220
39181
  init_check_record_access();
37221
39182
  var import_jszip4 = __toESM(require("jszip"), 1);
37222
39183
 
@@ -37331,7 +39292,7 @@ async function seedBundledSkills({
37331
39292
  }
37332
39293
 
37333
39294
  // src/exulu/routes.ts
37334
- var import_ai15 = require("ai");
39295
+ var import_ai17 = require("ai");
37335
39296
  var import_cookie_parser = __toESM(require("cookie-parser"), 1);
37336
39297
  init_convert_context_to_table_definition();
37337
39298
  init_context();
@@ -37339,10 +39300,10 @@ init_statistics2();
37339
39300
 
37340
39301
  // src/exulu/suggestions.ts
37341
39302
  init_cjs_shims();
37342
- var import_ai11 = require("ai");
39303
+ var import_ai12 = require("ai");
37343
39304
  var import_zod27 = require("zod");
37344
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.";
37345
- var submitSuggestionsTool = (0, import_ai11.tool)({
39306
+ var submitSuggestionsTool = (0, import_ai12.tool)({
37346
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.",
37347
39308
  inputSchema: import_zod27.z.object({
37348
39309
  suggestions: import_zod27.z.array(import_zod27.z.string()).max(3)
@@ -37381,12 +39342,12 @@ var generateSuggestions = async ({
37381
39342
 
37382
39343
  ${SUGGESTIONS_SYSTEM_PROMPT}` : SUGGESTIONS_SYSTEM_PROMPT;
37383
39344
  const trimmed = trimMessagesForSuggestions(messages);
37384
- const { toolCalls, totalUsage } = await (0, import_ai11.generateText)({
39345
+ const { toolCalls, totalUsage } = await (0, import_ai12.generateText)({
37385
39346
  temperature: 0,
37386
39347
  model: languageModel,
37387
39348
  system,
37388
39349
  // ignoreIncompleteToolCalls keeps persisted preliminary tool parts (e.g. a read aborted mid-way) out of model messages.
37389
- messages: await (0, import_ai11.convertToModelMessages)(trimmed, {
39350
+ messages: await (0, import_ai12.convertToModelMessages)(trimmed, {
37390
39351
  ignoreIncompleteToolCalls: true
37391
39352
  }),
37392
39353
  tools: { submit_suggestions: submitSuggestionsTool },
@@ -37412,17 +39373,17 @@ init_context_budget();
37412
39373
 
37413
39374
  // src/exulu/stream-persistence.ts
37414
39375
  init_cjs_shims();
37415
- var import_ai12 = require("ai");
39376
+ var import_ai13 = require("ai");
37416
39377
  var persistThroughDisconnect = () => ({
37417
39378
  consumeSseStream: ({ stream }) => {
37418
- void (0, import_ai12.consumeStream)({ stream });
39379
+ void (0, import_ai13.consumeStream)({ stream });
37419
39380
  }
37420
39381
  });
37421
39382
 
37422
39383
  // src/exulu/compact-session.ts
37423
39384
  init_cjs_shims();
37424
39385
  var import_node_crypto22 = require("crypto");
37425
- var import_ai13 = require("ai");
39386
+ var import_ai14 = require("ai");
37426
39387
  init_truncate_tool_output();
37427
39388
  init_context_budget();
37428
39389
  var CompactionInsufficientError = class extends Error {
@@ -37482,7 +39443,7 @@ var compactSession = async ({
37482
39443
  }) => {
37483
39444
  const budget = deriveContextBudget(contextWindow);
37484
39445
  const rows = await getAgentMessages({ session: sessionID, user: user.id });
37485
- const all = await (0, import_ai13.validateUIMessages)({
39446
+ const all = await (0, import_ai14.validateUIMessages)({
37486
39447
  messages: dropEmptyMessages(rows.map((r) => JSON.parse(r.content)))
37487
39448
  });
37488
39449
  const history = sliceHistoryAtCheckpoint(all);
@@ -37499,7 +39460,7 @@ var compactSession = async ({
37499
39460
 
37500
39461
  Focus especially on: ${steer.trim()}` : SUMMARY_SYSTEM;
37501
39462
  const doSummarize = summarize ?? (async ({ system: sys, prompt, maxOutputTokens }) => {
37502
- const { text } = await (0, import_ai13.generateText)({
39463
+ const { text } = await (0, import_ai14.generateText)({
37503
39464
  model: languageModel,
37504
39465
  system: sys,
37505
39466
  prompt,
@@ -37540,13 +39501,13 @@ ${summary}` }],
37540
39501
 
37541
39502
  // src/exulu/request-error.ts
37542
39503
  init_cjs_shims();
37543
- var import_ai14 = require("ai");
39504
+ var import_ai15 = require("ai");
37544
39505
  init_context_budget();
37545
39506
  function describeRequestError(err4) {
37546
39507
  if (err4 instanceof ContextCompactionRequiredError) {
37547
39508
  return { status: 413, body: err4.message };
37548
39509
  }
37549
- if (import_ai14.TypeValidationError.isInstance(err4)) {
39510
+ if (import_ai15.TypeValidationError.isInstance(err4)) {
37550
39511
  const cause = err4.cause;
37551
39512
  const detail = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
37552
39513
  return {
@@ -37557,6 +39518,174 @@ function describeRequestError(err4) {
37557
39518
  return { status: 500, body: err4 instanceof Error ? err4.message : String(err4) };
37558
39519
  }
37559
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.js"), 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
+
37560
39689
  // src/exulu/memory/recalled-metadata.ts
37561
39690
  init_cjs_shims();
37562
39691
  function recalledMemoriesMetadata({ recall, agent, isGuest }) {
@@ -38360,7 +40489,7 @@ function decideUploadSign(args) {
38360
40489
  }
38361
40490
  return { ok: true };
38362
40491
  }
38363
- var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
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;
38364
40493
  function makeLoadAuthedProject(deps) {
38365
40494
  return async (req, res, projectId, want) => {
38366
40495
  const authResult = await deps.authenticate(req);
@@ -38368,7 +40497,7 @@ function makeLoadAuthedProject(deps) {
38368
40497
  res.status(authResult.code || 401).json({ detail: authResult.message });
38369
40498
  return null;
38370
40499
  }
38371
- if (!UUID_RE2.test(projectId)) {
40500
+ if (!UUID_RE3.test(projectId)) {
38372
40501
  res.status(404).json({ detail: `Project ${projectId} not found.` });
38373
40502
  return null;
38374
40503
  }
@@ -38667,9 +40796,9 @@ init_cjs_shims();
38667
40796
  init_config3();
38668
40797
  function toolConfigOf(agent) {
38669
40798
  const tools = agent?.tools ?? [];
38670
- const tool4 = tools.find((t) => t?.id === "agentic_context_search");
40799
+ const tool5 = tools.find((t) => t?.id === "agentic_context_search");
38671
40800
  const out = {};
38672
- for (const entry of tool4?.config ?? []) if (entry?.name) out[entry.name] = entry.variable;
40801
+ for (const entry of tool5?.config ?? []) if (entry?.name) out[entry.name] = entry.variable;
38673
40802
  return out;
38674
40803
  }
38675
40804
  function hasNoToolConfig(raw) {
@@ -38682,7 +40811,7 @@ function pipelineConfigFor(agent) {
38682
40811
  // ee/claim-check/routes.ts
38683
40812
  var CLAIM_CHECK_PATH = "/claims/check";
38684
40813
  var CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
38685
- var UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
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;
38686
40815
  function hasNumericUserId(user) {
38687
40816
  return Boolean(user?.id) && Number.isFinite(Number(user?.id));
38688
40817
  }
@@ -38870,7 +40999,7 @@ function registerClaimCheckRoutes(app, deps) {
38870
40999
  });
38871
41000
  return;
38872
41001
  }
38873
- if (deps.findClaimCheck && body.session && body.messageId && UUID_RE3.test(body.session)) {
41002
+ if (deps.findClaimCheck && body.session && body.messageId && UUID_RE4.test(body.session)) {
38874
41003
  try {
38875
41004
  const stored = await deps.findClaimCheck({
38876
41005
  session: body.session,
@@ -38991,7 +41120,7 @@ function registerClaimCheckRoutes(app, deps) {
38991
41120
  if (deadline) clearTimeout(deadline);
38992
41121
  deps.limiter.release();
38993
41122
  }
38994
- if (completedResult && body.session && body.messageId && UUID_RE3.test(body.session)) {
41123
+ if (completedResult && body.session && body.messageId && UUID_RE4.test(body.session)) {
38995
41124
  if (!deps.saveClaimCheck) {
38996
41125
  console.error(
38997
41126
  "[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload."
@@ -39016,7 +41145,7 @@ function registerClaimCheckRoutes(app, deps) {
39016
41145
  return;
39017
41146
  }
39018
41147
  const session = req.params.session ?? "";
39019
- if (!UUID_RE3.test(session)) {
41148
+ if (!UUID_RE4.test(session)) {
39020
41149
  res.status(400).json({ detail: "session must be a uuid." });
39021
41150
  return;
39022
41151
  }
@@ -39042,13 +41171,13 @@ function registerClaimCheckRoutes(app, deps) {
39042
41171
 
39043
41172
  // ee/claim-check/rate-limit.ts
39044
41173
  init_cjs_shims();
39045
- var DEFAULTS = { perMinute: 30, perHour: 300, maxInFlight: 20 };
41174
+ var DEFAULTS3 = { perMinute: 30, perHour: 300, maxInFlight: 20 };
39046
41175
  var MAX_TRACKED_USERS = 1e4;
39047
- var HOUR_MS2 = 36e5;
41176
+ var HOUR_MS3 = 36e5;
39048
41177
  function evict(windows3, now) {
39049
41178
  if (windows3.size <= MAX_TRACKED_USERS) return;
39050
41179
  for (const [key, value] of windows3) {
39051
- if (now - value.lastSeen >= HOUR_MS2) windows3.delete(key);
41180
+ if (now - value.lastSeen >= HOUR_MS3) windows3.delete(key);
39052
41181
  }
39053
41182
  if (windows3.size <= MAX_TRACKED_USERS) return;
39054
41183
  const sorted = [...windows3.entries()].sort((a, b) => a[1].lastSeen - b[1].lastSeen);
@@ -39058,7 +41187,7 @@ function evict(windows3, now) {
39058
41187
  }
39059
41188
  }
39060
41189
  function claimCheckRateLimiter(opts = {}) {
39061
- const { perMinute, perHour, maxInFlight } = { ...DEFAULTS, ...opts };
41190
+ const { perMinute, perHour, maxInFlight } = { ...DEFAULTS3, ...opts };
39062
41191
  const windows3 = /* @__PURE__ */ new Map();
39063
41192
  let inFlight3 = 0;
39064
41193
  return {
@@ -39285,14 +41414,14 @@ function buildWindows(sentences, preceding, following) {
39285
41414
  init_cjs_shims();
39286
41415
  init_query_preprocessing();
39287
41416
  var MAX_CHARS_PER_SOURCE = 6e4;
39288
- var DEFAULTS2 = { passageChars: 1200, overlapChars: 200, maxCharsPerSource: MAX_CHARS_PER_SOURCE };
41417
+ var DEFAULTS4 = { passageChars: 1200, overlapChars: 200, maxCharsPerSource: MAX_CHARS_PER_SOURCE };
39289
41418
  function tokenize(text) {
39290
41419
  if (!text.trim()) return [];
39291
41420
  const { processed } = preprocessQuery(text, { enableStemming: true, detectLanguage: true, silent: true });
39292
41421
  return processed.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t) => t.length >= 3);
39293
41422
  }
39294
41423
  function indexSourcesWithLimits(sources, opts = {}) {
39295
- const { passageChars, overlapChars, maxCharsPerSource } = { ...DEFAULTS2, ...opts };
41424
+ const { passageChars, overlapChars, maxCharsPerSource } = { ...DEFAULTS4, ...opts };
39296
41425
  const passages = [];
39297
41426
  const documentFrequency = /* @__PURE__ */ new Map();
39298
41427
  const truncation = { sources: 0, droppedChars: 0, names: [] };
@@ -39970,9 +42099,9 @@ var chunk = (items, size) => {
39970
42099
  };
39971
42100
  async function runBatched(batches, label, state, call2) {
39972
42101
  const good = [];
39973
- let pending = batches;
39974
- for (let round = 0; pending.length > 0; round += 1) {
39975
- const settled = await mapWithConcurrency2(pending, MAX_IN_FLIGHT, async (windows3) => call2(windows3));
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));
39976
42105
  const failed = [];
39977
42106
  settled.forEach((outcome, i) => {
39978
42107
  if (outcome.status === "fulfilled") {
@@ -39980,13 +42109,13 @@ async function runBatched(batches, label, state, call2) {
39980
42109
  state.usage = addUsage(state.usage, outcome.value.usage);
39981
42110
  return;
39982
42111
  }
39983
- failed.push(pending[i]);
42112
+ failed.push(pending2[i]);
39984
42113
  });
39985
42114
  if (failed.length === 0) return good;
39986
- if (round === 0 && failed.length >= 2 && failed.length / pending.length > STAGE_FAILURE_ABORT) {
42115
+ if (round === 0 && failed.length >= 2 && failed.length / pending2.length > STAGE_FAILURE_ABORT) {
39987
42116
  state.partial = true;
39988
42117
  state.notes.push(
39989
- `${label}: aborted after ${failed.length} of ${pending.length} calls failed; remaining sentences are not_checked`
42118
+ `${label}: aborted after ${failed.length} of ${pending2.length} calls failed; remaining sentences are not_checked`
39990
42119
  );
39991
42120
  for (const batch of failed) markNotChecked(state, batch, `${label} aborted`);
39992
42121
  return good;
@@ -40004,7 +42133,7 @@ async function runBatched(batches, label, state, call2) {
40004
42133
  batch.length === 1 ? `${label} failed for this sentence` : round === 0 ? `${label} failed for this batch of ${batch.length} sentences` : `${label} failed after bisect`
40005
42134
  );
40006
42135
  }
40007
- pending = next;
42136
+ pending2 = next;
40008
42137
  }
40009
42138
  return good;
40010
42139
  }
@@ -40816,7 +42945,7 @@ init_cjs_shims();
40816
42945
  init_tags();
40817
42946
  init_activity_client();
40818
42947
  init_budget_service();
40819
- var DAY_MS4 = 24 * 60 * 60 * 1e3;
42948
+ var DAY_MS5 = 24 * 60 * 60 * 1e3;
40820
42949
  var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
40821
42950
  var MAX_WINDOW_DAYS = 92;
40822
42951
  var DEFAULT_WINDOW_DAYS = 30;
@@ -40828,7 +42957,7 @@ var parseDateParam = (raw) => {
40828
42957
  if (Number.isNaN(dt.getTime())) return null;
40829
42958
  return dt.toISOString().slice(0, 10);
40830
42959
  };
40831
- var ymdShift = (ymd2, days) => new Date(Date.parse(ymd2) + days * DAY_MS4).toISOString().slice(0, 10);
42960
+ var ymdShift = (ymd2, days) => new Date(Date.parse(ymd2) + days * DAY_MS5).toISOString().slice(0, 10);
40832
42961
  function resolveUsageWindow(startRaw, endRaw, now = /* @__PURE__ */ new Date()) {
40833
42962
  const start = parseDateParam(startRaw);
40834
42963
  const end = parseDateParam(endRaw);
@@ -40836,7 +42965,7 @@ function resolveUsageWindow(startRaw, endRaw, now = /* @__PURE__ */ new Date())
40836
42965
  const end_date = end ?? now.toISOString().slice(0, 10);
40837
42966
  let start_date = start ?? ymdShift(end_date, -(DEFAULT_WINDOW_DAYS - 1));
40838
42967
  if (start_date > end_date) return null;
40839
- const days = Math.round((Date.parse(end_date) - Date.parse(start_date)) / DAY_MS4) + 1;
42968
+ const days = Math.round((Date.parse(end_date) - Date.parse(start_date)) / DAY_MS5) + 1;
40840
42969
  if (days > MAX_WINDOW_DAYS) {
40841
42970
  start_date = ymdShift(end_date, -(MAX_WINDOW_DAYS - 1));
40842
42971
  }
@@ -40913,7 +43042,7 @@ async function getMyUsageView(userId, window) {
40913
43042
  const tag = budgetTagFor("user", userId);
40914
43043
  if (!tag) return null;
40915
43044
  const daysInRange = Math.round(
40916
- (Date.parse(window.end_date) - Date.parse(window.start_date)) / DAY_MS4
43045
+ (Date.parse(window.end_date) - Date.parse(window.start_date)) / DAY_MS5
40917
43046
  ) + 1;
40918
43047
  const raw = await getTagDailyActivity({
40919
43048
  startDate: window.start_date,
@@ -40934,28 +43063,146 @@ async function getMyUsageView(userId, window) {
40934
43063
 
40935
43064
  // src/exulu/routes.ts
40936
43065
  var import_multer = __toESM(require("multer"), 1);
40937
- init_credential_store();
40938
43066
 
40939
- // src/utils/check-api-key-scope.ts
43067
+ // src/exulu/channels/webhook.ts
40940
43068
  init_cjs_shims();
40941
- function checkApiKeyScope(user, agentId) {
40942
- if (!user || user.type !== "api") return { allowed: true };
40943
- if (!user.scope_mode || user.scope_mode === "admin") return { allowed: true };
40944
- if (user.scope_mode === "agents") {
40945
- const ids = Array.isArray(user.agent_ids) ? user.agent_ids : [];
40946
- if (!ids.includes(agentId)) {
40947
- return {
40948
- allowed: false,
40949
- reason: `API key is not scoped to agent ${agentId}.`,
40950
- code: 403
40951
- };
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;
40952
43150
  }
40953
- return { allowed: true };
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;
40954
43156
  }
40955
- return { allowed: false, reason: "Unknown scope_mode.", code: 401 };
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
+ );
40956
43202
  }
40957
43203
 
40958
43204
  // src/exulu/routes.ts
43205
+ init_credential_store();
40959
43206
  init_singleton();
40960
43207
  init_entitlements();
40961
43208
  init_create_sandbox();
@@ -41226,107 +43473,51 @@ init_shared_artifacts();
41226
43473
  init_session_files();
41227
43474
  init_session_file_adopt();
41228
43475
 
41229
- // src/exulu/public-agents.ts
41230
- init_cjs_shims();
41231
- init_shared_artifacts();
41232
- var LOCALE_KEY = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})?$/;
41233
- var welcomeTranslations = (raw) => {
41234
- let value = raw;
41235
- if (typeof value === "string") {
41236
- try {
41237
- value = JSON.parse(value);
41238
- } catch {
41239
- return {};
41240
- }
41241
- }
41242
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
41243
- const result = {};
41244
- for (const [key, text] of Object.entries(value)) {
41245
- if (!LOCALE_KEY.test(key) || typeof text !== "string") continue;
41246
- const trimmed = text.trim();
41247
- if (trimmed) result[key] = trimmed;
41248
- }
41249
- return result;
41250
- };
41251
- var publicAgentView = (row, slug) => ({
41252
- id: row.id,
41253
- name: row.name ?? "",
41254
- description: row.description ?? "",
41255
- image: row.image ?? null,
41256
- welcomemessage: row.welcomemessage ?? "",
41257
- welcomemessage_translations: welcomeTranslations(row.welcomemessage_translations),
41258
- slug,
41259
- guest_auth_mode: row.guest_auth_mode || "regular",
41260
- guest_has_cover: !!row.guest_cover_image,
41261
- guest_has_idle_animation: !!row.animation_idle,
41262
- guest_has_responding_animation: !!row.animation_responding
41263
- });
41264
- var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
41265
- if (agent.guest_access) {
41266
- if (userId != null) return { allowed: true, via: "guest" };
41267
- const mode = agent.guest_auth_mode || "regular";
41268
- if (mode === "public") return { allowed: true, via: "guest" };
41269
- if (mode === "password") {
41270
- if (agent.guest_password_hash && guestPassword) {
41271
- const ok = await verifySharePassword(guestPassword, agent.guest_password_hash);
41272
- if (ok) return { allowed: true, via: "guest" };
41273
- return { allowed: false, status: 401, message: "Incorrect password." };
41274
- }
41275
- return { allowed: false, status: 401, message: "Password required." };
41276
- }
41277
- return { allowed: false, status: 401, message: "Authentication required." };
41278
- }
41279
- if (userId == null && agent.rights_mode === "public") {
41280
- return { allowed: true, via: "rbac-public" };
41281
- }
41282
- return { allowed: false, status: 401, message: "Authentication required." };
41283
- };
41284
-
41285
43476
  // src/exulu/guest-rate-limit.ts
41286
43477
  init_cjs_shims();
41287
- var MINUTE_MS = 6e4;
41288
- var HOUR_MS3 = 36e5;
41289
- var perMinuteLimit = () => parseInt(process.env.EXULU_GUEST_RATE_PER_MINUTE || "10", 10);
41290
- var perHourLimit = () => parseInt(process.env.EXULU_GUEST_RATE_PER_HOUR || "60", 10);
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);
41291
43482
  var maxMessageChars = () => parseInt(process.env.EXULU_GUEST_MAX_MESSAGE_CHARS || "8000", 10);
41292
43483
  var maxTotalChars = () => parseInt(process.env.EXULU_GUEST_MAX_TOTAL_CHARS || "32000", 10);
41293
43484
  var MAX_PART_COUNT = 100;
41294
- var windows = /* @__PURE__ */ new Map();
43485
+ var windows2 = /* @__PURE__ */ new Map();
41295
43486
  var guestRateLimitExceeded = (ip, now = Date.now()) => {
41296
- const state = windows.get(ip) ?? {
43487
+ const state = windows2.get(ip) ?? {
41297
43488
  minuteStart: now,
41298
43489
  minuteCount: 0,
41299
43490
  hourStart: now,
41300
43491
  hourCount: 0,
41301
43492
  lastSeen: now
41302
43493
  };
41303
- if (now - state.minuteStart >= MINUTE_MS) {
43494
+ if (now - state.minuteStart >= MINUTE_MS2) {
41304
43495
  state.minuteStart = now;
41305
43496
  state.minuteCount = 0;
41306
43497
  }
41307
- if (now - state.hourStart >= HOUR_MS3) {
43498
+ if (now - state.hourStart >= HOUR_MS4) {
41308
43499
  state.hourStart = now;
41309
43500
  state.hourCount = 0;
41310
43501
  }
41311
43502
  state.minuteCount += 1;
41312
43503
  state.hourCount += 1;
41313
43504
  state.lastSeen = now;
41314
- windows.set(ip, state);
41315
- if (windows.size > 1e4) {
41316
- for (const [key, value] of windows) {
41317
- if (now - value.lastSeen >= HOUR_MS3) windows.delete(key);
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);
41318
43509
  }
41319
- if (windows.size > 1e4) {
41320
- const sorted = [...windows.entries()].sort(
43510
+ if (windows2.size > 1e4) {
43511
+ const sorted = [...windows2.entries()].sort(
41321
43512
  (a, b) => a[1].lastSeen - b[1].lastSeen
41322
43513
  );
41323
43514
  for (const [key] of sorted) {
41324
- if (windows.size <= 1e4) break;
41325
- windows.delete(key);
43515
+ if (windows2.size <= 1e4) break;
43516
+ windows2.delete(key);
41326
43517
  }
41327
43518
  }
41328
43519
  }
41329
- return state.minuteCount > perMinuteLimit() || state.hourCount > perHourLimit();
43520
+ return state.minuteCount > perMinuteLimit2() || state.hourCount > perHourLimit2();
41330
43521
  };
41331
43522
  var partsTooLong = (parts) => Array.isArray(parts) && parts.some(
41332
43523
  (p) => typeof p?.text === "string" && p.text.length > maxMessageChars()
@@ -41369,69 +43560,6 @@ var extractClientIp = (req) => {
41369
43560
  return req.ip || req.socket?.remoteAddress || "unknown";
41370
43561
  };
41371
43562
 
41372
- // src/exulu/external-rate-limit.ts
41373
- init_cjs_shims();
41374
- var MINUTE_MS2 = 6e4;
41375
- var HOUR_MS4 = 36e5;
41376
- var perMinuteLimit2 = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
41377
- var perHourLimit2 = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
41378
- var windows2 = /* @__PURE__ */ new Map();
41379
- var externalRateLimitExceeded = (userId, now = Date.now()) => {
41380
- const state = windows2.get(userId) ?? {
41381
- minuteStart: now,
41382
- minuteCount: 0,
41383
- hourStart: now,
41384
- hourCount: 0,
41385
- lastSeen: now
41386
- };
41387
- if (now - state.minuteStart >= MINUTE_MS2) {
41388
- state.minuteStart = now;
41389
- state.minuteCount = 0;
41390
- }
41391
- if (now - state.hourStart >= HOUR_MS4) {
41392
- state.hourStart = now;
41393
- state.hourCount = 0;
41394
- }
41395
- state.minuteCount += 1;
41396
- state.hourCount += 1;
41397
- state.lastSeen = now;
41398
- windows2.set(userId, state);
41399
- if (windows2.size > 1e4) {
41400
- for (const [key, value] of windows2) {
41401
- if (now - value.lastSeen >= HOUR_MS4) windows2.delete(key);
41402
- }
41403
- if (windows2.size > 1e4) {
41404
- const sorted = [...windows2.entries()].sort(
41405
- (a, b) => a[1].lastSeen - b[1].lastSeen
41406
- );
41407
- for (const [key] of sorted) {
41408
- if (windows2.size <= 1e4) break;
41409
- windows2.delete(key);
41410
- }
41411
- }
41412
- }
41413
- const minuteLimitExceeded = state.minuteCount > perMinuteLimit2();
41414
- const hourLimitExceeded = state.hourCount > perHourLimit2();
41415
- const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
41416
- if (limitExceeded) {
41417
- const limits = {
41418
- perMinute: perMinuteLimit2(),
41419
- perHour: perHourLimit2()
41420
- };
41421
- const current = {
41422
- minute: state.minuteCount,
41423
- hour: state.hourCount
41424
- };
41425
- console.warn(
41426
- `[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
41427
- );
41428
- }
41429
- return limitExceeded;
41430
- };
41431
- var isExternalUser = (user) => {
41432
- return user?.role?.name === "external";
41433
- };
41434
-
41435
43563
  // src/exulu/routes.ts
41436
43564
  init_skill_access();
41437
43565
 
@@ -41624,6 +43752,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
41624
43752
  console.log("[EXULU] tracer configured", tracer);
41625
43753
  }
41626
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" }));
41627
43756
  app.use(
41628
43757
  import_express3.default.json({
41629
43758
  limit: REQUEST_SIZE_LIMIT,
@@ -41867,6 +43996,21 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
41867
43996
  rateLimitExceeded: routineWebhookRateLimitExceeded
41868
43997
  });
41869
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);
41870
44014
  app.get("/ping", async (req, res) => {
41871
44015
  const authenticationResult = await requestValidators.authenticate(req);
41872
44016
  if (!authenticationResult.user?.id) {
@@ -42065,6 +44209,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
42065
44209
  const contextWindow = await resolveContextWindow({
42066
44210
  modelId: resolved.model.id
42067
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;
42068
44218
  if (!!headers.stream) {
42069
44219
  const statistics = {
42070
44220
  label: agent.name,
@@ -42200,7 +44350,7 @@ ${customInstructions}` : agent.instructions,
42200
44350
  else message2 = JSON.stringify(error);
42201
44351
  return mapStreamErrorMessage(message2);
42202
44352
  },
42203
- generateMessageId: (0, import_ai15.createIdGenerator)({
44353
+ generateMessageId: (0, import_ai17.createIdGenerator)({
42204
44354
  prefix: "msg_",
42205
44355
  size: 16
42206
44356
  }),
@@ -42291,12 +44441,15 @@ ${customInstructions}` : agent.instructions,
42291
44441
  return;
42292
44442
  } else {
42293
44443
  const customInstructions = req.body.customInstructions ? typeof req.body.customInstructions === "string" ? req.body.customInstructions : JSON.stringify(req.body.customInstructions) : "";
42294
- const instructions = withGlossary(
44444
+ const baseInstructions = withGlossary(
42295
44445
  customInstructions ? `${agent.instructions}
42296
44446
 
42297
44447
  ${customInstructions}` : agent.instructions,
42298
44448
  agent.tools
42299
44449
  );
44450
+ const instructions = outputSchema ? `${baseInstructions}
44451
+
44452
+ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
42300
44453
  let response;
42301
44454
  try {
42302
44455
  response = await generateSync({
@@ -42331,6 +44484,45 @@ ${customInstructions}` : agent.instructions,
42331
44484
  res.status(status).send(body);
42332
44485
  return;
42333
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
+ }
42334
44526
  res.status(200).json(response);
42335
44527
  return;
42336
44528
  }
@@ -43191,12 +45383,12 @@ ${style.markdown}` : params.prompt;
43191
45383
  const lines = selectedDetails.map(
43192
45384
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
43193
45385
  );
43194
- const messageText = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
45386
+ const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
43195
45387
  const messageId = (0, import_node_crypto24.randomUUID)();
43196
45388
  const uiMessage = {
43197
45389
  id: messageId,
43198
45390
  role: "system",
43199
- parts: [{ type: "text", text: messageText }]
45391
+ parts: [{ type: "text", text: messageText2 }]
43200
45392
  };
43201
45393
  await authed.db("agent_messages").insert({
43202
45394
  content: JSON.stringify(uiMessage),
@@ -45222,7 +47414,7 @@ ${style.markdown}` : params.prompt;
45222
47414
  ...s,
45223
47415
  messages: messagesBySession.get(s.id) ?? []
45224
47416
  }));
45225
- const [feedback, promptFavorites, tracking, claimChecks] = await Promise.all([
47417
+ const [feedback, promptFavorites, tracking, claimChecks, channelLinks] = await Promise.all([
45226
47418
  db2.from("feedback").where({ user: targetUser.id }).catch(() => []),
45227
47419
  db2.from("prompt_favorites").where({ user_id: targetUser.id }).catch(() => []),
45228
47420
  db2.from("tracking").where({ user: targetUser.id }).catch(() => []),
@@ -45230,7 +47422,10 @@ ${style.markdown}` : params.prompt;
45230
47422
  // data (their answers' sentences, verbatim source quotes), so Art. 15
45231
47423
  // covers it. Same `.catch(() => [])` as its siblings: the table only
45232
47424
  // exists on deployments licensed for claim-check.
45233
- 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)
45234
47429
  ]);
45235
47430
  const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
45236
47431
  const readme = [
@@ -45250,6 +47445,7 @@ ${style.markdown}` : params.prompt;
45250
47445
  ` - prompt_favorites.json prompt-library favourites`,
45251
47446
  ` - tracking.json tracking events linked to the user`,
45252
47447
  ` - claim_checks.json answer verification results stored for the user`,
47448
+ ` - channel_links.json messaging-channel (WhatsApp) links of the user`,
45253
47449
  ``
45254
47450
  ].join("\n");
45255
47451
  const zip = new import_jszip4.default();
@@ -45263,6 +47459,7 @@ ${style.markdown}` : params.prompt;
45263
47459
  );
45264
47460
  zip.file("tracking.json", JSON.stringify(tracking, null, 2));
45265
47461
  zip.file("claim_checks.json", JSON.stringify(claimChecks, null, 2));
47462
+ zip.file("channel_links.json", JSON.stringify(channelLinks, null, 2));
45266
47463
  const buffer = await zip.generateAsync({ type: "nodebuffer" });
45267
47464
  const filename = `user-${targetUser.id}-export-${exportedAt.replace(/[:.]/g, "-")}.zip`;
45268
47465
  res.setHeader("Content-Type", "application/zip");
@@ -45291,6 +47488,7 @@ ${style.markdown}` : params.prompt;
45291
47488
  await trx("prompt_favorites").where({ user_id: targetUser.id }).delete();
45292
47489
  await trx("tracking").where({ user: targetUser.id }).delete();
45293
47490
  await trx("rbac").where({ user_id: targetUser.id }).delete();
47491
+ await afterUserDelete(trx, targetUser.id);
45294
47492
  await trx("users").where({ id: targetUser.id }).delete();
45295
47493
  });
45296
47494
  } catch (err4) {
@@ -45594,18 +47792,32 @@ ${style.markdown}` : params.prompt;
45594
47792
  if (headers.disposition) res.setHeader("Content-Disposition", headers.disposition);
45595
47793
  res.send(bytes);
45596
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
+ });
45597
47809
  const resolvePublicAgentSlug = async (agentModel) => {
45598
47810
  if (isLiteLLMEnabled()) return "/agents/litellm/run";
45599
47811
  if (!agentModel) return "";
45600
47812
  return "";
45601
47813
  };
45602
- const UUID_RE4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
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;
45603
47815
  const stripBucketPrefix = (key, cfg) => {
45604
47816
  const bucket = cfg.fileUploads?.s3Bucket;
45605
47817
  return bucket ? key.replace(`${bucket}/`, "") : key;
45606
47818
  };
45607
47819
  const getGuestAgentById = async (id) => {
45608
- if (!UUID_RE4.test(id)) return void 0;
47820
+ if (!UUID_RE5.test(id)) return void 0;
45609
47821
  const { db: db2 } = await postgresClient();
45610
47822
  return db2.from("agents").where({ id, guest_access: true, active: true }).first();
45611
47823
  };
@@ -45791,10 +48003,10 @@ init_cjs_shims();
45791
48003
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
45792
48004
  var import_node_crypto25 = require("crypto");
45793
48005
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
45794
- var import_types13 = require("@modelcontextprotocol/sdk/types.js");
48006
+ var import_types14 = require("@modelcontextprotocol/sdk/types.js");
45795
48007
  init_sanitize_tool_name();
45796
48008
  var import_express4 = require("express");
45797
- var import_api3 = require("@opentelemetry/api");
48009
+ var import_api5 = require("@opentelemetry/api");
45798
48010
  init_check_record_access();
45799
48011
  init_resolve_model();
45800
48012
  init_supervisor();
@@ -45853,26 +48065,26 @@ var ExuluMCP = class {
45853
48065
  "[EXULU] Enabled tools",
45854
48066
  enabledTools?.map((x) => x.name + " (" + x.id + ")")
45855
48067
  );
45856
- for (const tool4 of enabledTools || []) {
45857
- if (server.tools[tool4.id]) {
48068
+ for (const tool5 of enabledTools || []) {
48069
+ if (server.tools[tool5.id]) {
45858
48070
  continue;
45859
48071
  }
45860
48072
  server.mcp.registerTool(
45861
- sanitizeToolName(tool4.name + "_agent_" + tool4.id),
48073
+ sanitizeToolName(tool5.name + "_agent_" + tool5.id),
45862
48074
  {
45863
- title: tool4.name + " agent",
45864
- description: tool4.description,
48075
+ title: tool5.name + " agent",
48076
+ description: tool5.description,
45865
48077
  inputSchema: {
45866
- inputs: tool4.inputSchema || import_zod36.z.object({})
48078
+ inputs: tool5.inputSchema || import_zod36.z.object({})
45867
48079
  }
45868
48080
  },
45869
48081
  async ({ inputs }, args) => {
45870
- console.log("[EXULU] MCP tool name", tool4.name);
48082
+ console.log("[EXULU] MCP tool name", tool5.name);
45871
48083
  console.log("[EXULU] MCP tool inputs", inputs);
45872
48084
  console.log("[EXULU] MCP tool args", args);
45873
48085
  const configValues = agent.tools;
45874
48086
  const tools = await convertExuluToolsToAiSdkTools(
45875
- [tool4],
48087
+ [tool5],
45876
48088
  [],
45877
48089
  [],
45878
48090
  allTools,
@@ -45884,13 +48096,13 @@ var ExuluMCP = class {
45884
48096
  void 0,
45885
48097
  void 0
45886
48098
  );
45887
- const convertedTool = tools[sanitizeToolName(tool4.name)];
48099
+ const convertedTool = tools[sanitizeToolName(tool5.name)];
45888
48100
  if (!convertedTool?.execute) {
45889
48101
  console.error("[EXULU] Tool not found in converted tools array.", tools);
45890
48102
  throw new Error("Tool not found in converted tools array.");
45891
48103
  }
45892
48104
  const iterator = await convertedTool.execute(inputs, {
45893
- toolCallId: tool4.id + "_" + (0, import_node_crypto25.randomUUID)(),
48105
+ toolCallId: tool5.id + "_" + (0, import_node_crypto25.randomUUID)(),
45894
48106
  messages: []
45895
48107
  });
45896
48108
  let result;
@@ -45904,7 +48116,7 @@ var ExuluMCP = class {
45904
48116
  };
45905
48117
  }
45906
48118
  );
45907
- server.tools[tool4.id] = tool4.name;
48119
+ server.tools[tool5.id] = tool5.name;
45908
48120
  }
45909
48121
  const getListOfPromptTemplatesName = "getListOfPromptTemplates";
45910
48122
  if (!server.tools[getListOfPromptTemplatesName]) {
@@ -46078,7 +48290,7 @@ var ExuluMCP = class {
46078
48290
  let transport;
46079
48291
  if (sessionId && this.transports[sessionId]) {
46080
48292
  transport = this.transports[sessionId];
46081
- } else if (!sessionId && (0, import_types13.isInitializeRequest)(req.body)) {
48293
+ } else if (!sessionId && (0, import_types14.isInitializeRequest)(req.body)) {
46082
48294
  transport = new import_streamableHttp.StreamableHTTPServerTransport({
46083
48295
  sessionIdGenerator: () => (0, import_node_crypto25.randomUUID)(),
46084
48296
  onsessioninitialized: (sessionId2) => {
@@ -46123,7 +48335,7 @@ var ExuluMCP = class {
46123
48335
 
46124
48336
  // src/exulu/app/index.ts
46125
48337
  var import_express7 = __toESM(require("express"), 1);
46126
- var import_api4 = require("@opentelemetry/api");
48338
+ var import_api6 = require("@opentelemetry/api");
46127
48339
 
46128
48340
  // src/exulu/logger.ts
46129
48341
  init_cjs_shims();
@@ -46163,7 +48375,7 @@ init_cjs_shims();
46163
48375
 
46164
48376
  // src/exulu/evals.ts
46165
48377
  init_cjs_shims();
46166
- var import_ai16 = require("ai");
48378
+ var import_ai18 = require("ai");
46167
48379
  var ExuluEval = class {
46168
48380
  id;
46169
48381
  name;
@@ -46203,7 +48415,7 @@ var ExuluEval = class {
46203
48415
  init_resolve_model();
46204
48416
  init_singleton();
46205
48417
  var import_zod37 = require("zod");
46206
- var import_ai17 = require("ai");
48418
+ var import_ai19 = require("ai");
46207
48419
  var llmAsJudgeEval = () => {
46208
48420
  if (process.env.REDIS_HOST?.length && process.env.REDIS_PORT?.length) {
46209
48421
  return new ExuluEval({
@@ -46246,13 +48458,13 @@ var llmAsJudgeEval = () => {
46246
48458
  rbacBypass: true
46247
48459
  });
46248
48460
  console.log("[EXULU] prompt", prompt);
46249
- const { output } = await (0, import_ai17.generateText)({
48461
+ const { output } = await (0, import_ai19.generateText)({
46250
48462
  temperature: 0,
46251
48463
  model: resolved.languageModel,
46252
48464
  system: "",
46253
48465
  prompt,
46254
48466
  maxRetries: 2,
46255
- output: import_ai17.Output.object({
48467
+ output: import_ai19.Output.object({
46256
48468
  schema: import_zod37.z.object({
46257
48469
  score: import_zod37.z.number().min(0).max(100).describe("The score between 0 and 100.")
46258
48470
  })
@@ -47454,9 +49666,9 @@ var ExuluApp = class {
47454
49666
  id: this._contexts?.[x]?.id ?? "",
47455
49667
  type: "context"
47456
49668
  })),
47457
- ...this._tools.map((tool4) => ({
47458
- name: tool4.name ?? "",
47459
- id: tool4.id ?? "",
49669
+ ...this._tools.map((tool5) => ({
49670
+ name: tool5.name ?? "",
49671
+ id: tool5.id ?? "",
47460
49672
  type: "tool"
47461
49673
  }))
47462
49674
  ];
@@ -47505,6 +49717,7 @@ var ExuluApp = class {
47505
49717
  300
47506
49718
  );
47507
49719
  registerImportQueue();
49720
+ registerChannelQueue();
47508
49721
  if (queues2?.length) {
47509
49722
  for (const queue of queues2) {
47510
49723
  queueSet.add(await queue);
@@ -47753,7 +49966,7 @@ var ExuluApp = class {
47753
49966
  }
47754
49967
  let tracer;
47755
49968
  if (this._config?.telemetry?.enabled) {
47756
- tracer = import_api4.trace.getTracer("exulu", "1.0.0");
49969
+ tracer = import_api6.trace.getTracer("exulu", "1.0.0");
47757
49970
  }
47758
49971
  const transports = this._config?.workers?.logger?.winston?.transports ?? this._config?.logger?.winston?.transports ?? [consoleTransport];
47759
49972
  const logger = logger_default({
@@ -47843,7 +50056,7 @@ var ExuluApp = class {
47843
50056
  const app = this._expressApp;
47844
50057
  let tracer;
47845
50058
  if (this._config?.telemetry?.enabled) {
47846
- tracer = import_api4.trace.getTracer("exulu", "1.0.0");
50059
+ tracer = import_api6.trace.getTracer("exulu", "1.0.0");
47847
50060
  }
47848
50061
  const transports = this._config?.logger?.winston?.transports ?? [consoleTransport];
47849
50062
  const logger = logger_default({
@@ -48744,6 +50957,8 @@ var {
48744
50957
  variablesSchema: variablesSchema3,
48745
50958
  workflowTemplatesSchema: workflowTemplatesSchema3,
48746
50959
  workflowTriggersSchema: workflowTriggersSchema2,
50960
+ agentChannelsSchema: agentChannelsSchema2,
50961
+ channelLinksSchema: channelLinksSchema2,
48747
50962
  rbacSchema: rbacSchema3,
48748
50963
  projectsSchema: projectsSchema3,
48749
50964
  jobResultsSchema: jobResultsSchema3,
@@ -48833,6 +51048,8 @@ var up = async function(knex) {
48833
51048
  skillsSchema3(),
48834
51049
  workflowTemplatesSchema3(),
48835
51050
  workflowTriggersSchema2(),
51051
+ // Only present when the "channels" entitlement is licensed.
51052
+ ...agentChannelsSchema2 && channelLinksSchema2 ? [agentChannelsSchema2(), channelLinksSchema2()] : [],
48836
51053
  otpSendAttemptsSchema2()
48837
51054
  ];
48838
51055
  const createTable = async (schema7) => {
@@ -48993,6 +51210,19 @@ var up = async function(knex) {
48993
51210
  ON claim_checks (session, message_id, "user")`
48994
51211
  );
48995
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
+ }
48996
51226
  };
48997
51227
  var contextDatabases = async (contexts) => {
48998
51228
  const { db: knex } = await postgresClient();
@@ -49115,7 +51345,7 @@ init_cjs_shims();
49115
51345
  var import_node_fs12 = require("fs");
49116
51346
  var import_node_path17 = require("path");
49117
51347
  var import_node_child_process8 = require("child_process");
49118
- var import_pg = require("pg");
51348
+ var import_pg3 = require("pg");
49119
51349
 
49120
51350
  // src/exulu/litellm/db-setup-check.ts
49121
51351
  init_cjs_shims();
@@ -49219,7 +51449,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
49219
51449
  `LiteLLM database mode detected (${target?.host}:${target?.port}/${target?.database}).`
49220
51450
  );
49221
51451
  const ensureDatabaseExists2 = async () => {
49222
- const probe = new import_pg.Client({ connectionString: litellmUrl });
51452
+ const probe = new import_pg3.Client({ connectionString: litellmUrl });
49223
51453
  try {
49224
51454
  await probe.connect();
49225
51455
  await probe.end();
@@ -49252,7 +51482,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
49252
51482
  ]);
49253
51483
  return false;
49254
51484
  }
49255
- const admin = new import_pg.Client({ connectionString: url.toString() });
51485
+ const admin = new import_pg3.Client({ connectionString: url.toString() });
49256
51486
  try {
49257
51487
  await admin.connect();
49258
51488
  await admin.query(`CREATE DATABASE "${targetDbName}"`);
@@ -49279,7 +51509,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
49279
51509
  };
49280
51510
  if (!await ensureDatabaseExists2()) return;
49281
51511
  log6("Checking that the target database is safe to push into\u2026");
49282
- const client2 = new import_pg.Client({ connectionString: litellmUrl });
51512
+ const client2 = new import_pg3.Client({ connectionString: litellmUrl });
49283
51513
  let foreignTables = [];
49284
51514
  try {
49285
51515
  await client2.connect();