@exulu/backend 5.17.1 → 5.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -669,7 +669,7 @@ var ExuluTool = class _ExuluTool {
669
669
  if (!agent) {
670
670
  throw new Error("Agent not found.");
671
671
  }
672
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-BCHKS5CK.js");
672
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-6GKOSRRE.js");
673
673
  const tools = await convertExuluToolsToAiSdkTools2(
674
674
  [this],
675
675
  [],
@@ -1570,6 +1570,36 @@ forms \u2014 the bare number on its own, and each individual part when a multi-p
1570
1570
  is referenced (e.g. "ISO 8100-1-2" must yield "8100-1" AND "8100-2").
1571
1571
  Do NOT include generic single words on their own.
1572
1572
  If the question references none, return hasMatches false and an empty array.`;
1573
+ var alnumRuns = (text) => text.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
1574
+ function identifiersInQuestion(matches, question) {
1575
+ const words = alnumRuns(question);
1576
+ const joinedWords = words.join("");
1577
+ const inQuestion = (part) => words.some((word) => word.includes(part) || isTypoOf(word, part));
1578
+ return matches.filter((match) => {
1579
+ const parts = alnumRuns(match);
1580
+ const long = parts.filter((part) => part.length >= 2);
1581
+ if (long.length === 0) return false;
1582
+ if (long.every(inQuestion)) return true;
1583
+ return parts.length >= 2 && joinedWords.includes(parts.join(""));
1584
+ });
1585
+ }
1586
+ function isTypoOf(word, part) {
1587
+ if (part.length < 3 || word === part) return false;
1588
+ if (Math.abs(word.length - part.length) > 1) return false;
1589
+ if (word.length === part.length) {
1590
+ const diff = [];
1591
+ for (let i2 = 0; i2 < part.length; i2++) if (word[i2] !== part[i2]) diff.push(i2);
1592
+ if (diff.length === 2 && diff[1] === diff[0] + 1) {
1593
+ return word[diff[0]] === part[diff[1]] && word[diff[1]] === part[diff[0]];
1594
+ }
1595
+ return part.length >= 5 && diff.length === 1;
1596
+ }
1597
+ if (part.length < 5) return false;
1598
+ const [short, longer] = word.length < part.length ? [word, part] : [part, word];
1599
+ let i = 0;
1600
+ while (i < short.length && short[i] === longer[i]) i++;
1601
+ return short.slice(i) === longer.slice(i + 1);
1602
+ }
1573
1603
  async function resolveIdentifierPins({
1574
1604
  question,
1575
1605
  identifierSets,
@@ -1595,7 +1625,14 @@ async function resolveIdentifierPins({
1595
1625
  })
1596
1626
  });
1597
1627
  if (!output?.hasMatches || !output.matches?.length) return;
1598
- steps.push({ text: `Detected ${set.name} in the question: ${output.matches.join(", ")}` });
1628
+ const matches = identifiersInQuestion(output.matches, question);
1629
+ if (!matches.length) {
1630
+ steps.push({
1631
+ text: `Ignored ${set.name} that are not in the question: ${output.matches.join(", ")}`
1632
+ });
1633
+ return;
1634
+ }
1635
+ steps.push({ text: `Detected ${set.name} in the question: ${matches.join(", ")}` });
1599
1636
  await Promise.all(
1600
1637
  set.contexts.map(async (ctxId) => {
1601
1638
  const ctx = contextsById.get(ctxId);
@@ -1606,9 +1643,9 @@ async function resolveIdentifierPins({
1606
1643
  fields: ["name", "id", "external_id"],
1607
1644
  normalize: (item) => item.external_id ? normalizeFileName(item.external_id) : item.name
1608
1645
  };
1609
- const matched = set.strategy === "exact" ? await exactTokenPrefilter({ ...common, tokens: output.matches }) : await fuzzyPrefilter({
1646
+ const matched = set.strategy === "exact" ? await exactTokenPrefilter({ ...common, tokens: matches }) : await fuzzyPrefilter({
1610
1647
  ...common,
1611
- relevantKeywords: output.matches,
1648
+ relevantKeywords: matches,
1612
1649
  cutoff: DEFAULT_PREFILTER_CUTOFF,
1613
1650
  // Identifier pins are a hard id-whitelist over filenames,
1614
1651
  // which is exactly the case the supplement exists for.
@@ -3,7 +3,7 @@ import {
3
3
  OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS,
4
4
  convertExuluToolsToAiSdkTools,
5
5
  hydrateVariables
6
- } from "./chunk-ZNG2HEDN.js";
6
+ } from "./chunk-PNBVWUEA.js";
7
7
  import "./chunk-NBAFO66K.js";
8
8
  import "./chunk-F534XOQR.js";
9
9
  import "./chunk-6URU62NI.js";
package/dist/index.cjs CHANGED
@@ -20979,6 +20979,35 @@ async function fuzzyPrefilter({
20979
20979
  );
20980
20980
  return prefiltered;
20981
20981
  }
20982
+ function identifiersInQuestion(matches, question) {
20983
+ const words = alnumRuns(question);
20984
+ const joinedWords = words.join("");
20985
+ const inQuestion = (part) => words.some((word) => word.includes(part) || isTypoOf(word, part));
20986
+ return matches.filter((match) => {
20987
+ const parts = alnumRuns(match);
20988
+ const long = parts.filter((part) => part.length >= 2);
20989
+ if (long.length === 0) return false;
20990
+ if (long.every(inQuestion)) return true;
20991
+ return parts.length >= 2 && joinedWords.includes(parts.join(""));
20992
+ });
20993
+ }
20994
+ function isTypoOf(word, part) {
20995
+ if (part.length < 3 || word === part) return false;
20996
+ if (Math.abs(word.length - part.length) > 1) return false;
20997
+ if (word.length === part.length) {
20998
+ const diff = [];
20999
+ for (let i2 = 0; i2 < part.length; i2++) if (word[i2] !== part[i2]) diff.push(i2);
21000
+ if (diff.length === 2 && diff[1] === diff[0] + 1) {
21001
+ return word[diff[0]] === part[diff[1]] && word[diff[1]] === part[diff[0]];
21002
+ }
21003
+ return part.length >= 5 && diff.length === 1;
21004
+ }
21005
+ if (part.length < 5) return false;
21006
+ const [short, longer] = word.length < part.length ? [word, part] : [part, word];
21007
+ let i = 0;
21008
+ while (i < short.length && short[i] === longer[i]) i++;
21009
+ return short.slice(i) === longer.slice(i + 1);
21010
+ }
20982
21011
  async function resolveIdentifierPins({
20983
21012
  question,
20984
21013
  identifierSets,
@@ -21004,7 +21033,14 @@ async function resolveIdentifierPins({
21004
21033
  })
21005
21034
  });
21006
21035
  if (!output?.hasMatches || !output.matches?.length) return;
21007
- steps.push({ text: `Detected ${set.name} in the question: ${output.matches.join(", ")}` });
21036
+ const matches = identifiersInQuestion(output.matches, question);
21037
+ if (!matches.length) {
21038
+ steps.push({
21039
+ text: `Ignored ${set.name} that are not in the question: ${output.matches.join(", ")}`
21040
+ });
21041
+ return;
21042
+ }
21043
+ steps.push({ text: `Detected ${set.name} in the question: ${matches.join(", ")}` });
21008
21044
  await Promise.all(
21009
21045
  set.contexts.map(async (ctxId) => {
21010
21046
  const ctx = contextsById.get(ctxId);
@@ -21015,9 +21051,9 @@ async function resolveIdentifierPins({
21015
21051
  fields: ["name", "id", "external_id"],
21016
21052
  normalize: (item) => item.external_id ? normalizeFileName(item.external_id) : item.name
21017
21053
  };
21018
- const matched = set.strategy === "exact" ? await exactTokenPrefilter({ ...common, tokens: output.matches }) : await fuzzyPrefilter({
21054
+ const matched = set.strategy === "exact" ? await exactTokenPrefilter({ ...common, tokens: matches }) : await fuzzyPrefilter({
21019
21055
  ...common,
21020
- relevantKeywords: output.matches,
21056
+ relevantKeywords: matches,
21021
21057
  cutoff: DEFAULT_PREFILTER_CUTOFF,
21022
21058
  // Identifier pins are a hard id-whitelist over filenames,
21023
21059
  // which is exactly the case the supplement exists for.
@@ -21048,7 +21084,7 @@ async function resolveIdentifierPins({
21048
21084
  );
21049
21085
  return { pinsByContext, exactPinsByContext, steps };
21050
21086
  }
21051
- var import_fuse, import_zod21, SUPPLEMENT_MIN_TOKEN_LENGTH, SUPPLEMENT_BUDGET, SUPPLEMENT_BUDGET_WIDE, itemCaches, ensureItemsCache, FUZZY_EXTRACTION_PROMPT, EXACT_EXTRACTION_PROMPT;
21087
+ var import_fuse, import_zod21, SUPPLEMENT_MIN_TOKEN_LENGTH, SUPPLEMENT_BUDGET, SUPPLEMENT_BUDGET_WIDE, itemCaches, ensureItemsCache, FUZZY_EXTRACTION_PROMPT, EXACT_EXTRACTION_PROMPT, alnumRuns;
21052
21088
  var init_prefilter = __esm({
21053
21089
  "ee/agentic-retrieval/pipeline/prefilter.ts"() {
21054
21090
  "use strict";
@@ -21109,6 +21145,7 @@ forms \u2014 the bare number on its own, and each individual part when a multi-p
21109
21145
  is referenced (e.g. "ISO 8100-1-2" must yield "8100-1" AND "8100-2").
21110
21146
  Do NOT include generic single words on their own.
21111
21147
  If the question references none, return hasMatches false and an empty array.`;
21148
+ alnumRuns = (text) => text.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
21112
21149
  }
21113
21150
  });
21114
21151
 
@@ -26036,12 +26073,12 @@ var channelView = (row) => ({
26036
26073
  needsCredentials: readSecrets(row) === null
26037
26074
  });
26038
26075
  var maskIdentity = (identity) => identity.length < 4 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022 ${identity.slice(-4)}`;
26039
- var linkPageUrl = (agentId) => {
26076
+ var linkPageUrl = (agentId, locale) => {
26040
26077
  const base = [process.env.CHANNEL_LINK_BASE_URL, process.env.FRONTEND, process.env.NEXTAUTH_URL].map((v) => (v ?? "").trim()).find((v) => v !== "");
26041
26078
  if (!base) {
26042
26079
  throw new ChannelSetupError("None of CHANNEL_LINK_BASE_URL, FRONTEND and NEXTAUTH_URL is set; the channel link page has no URL");
26043
26080
  }
26044
- return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp`;
26081
+ return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp${locale ? `?lang=${locale}` : ""}`;
26045
26082
  };
26046
26083
 
26047
26084
  // src/exulu/channels/decide.ts
@@ -26555,11 +26592,19 @@ var registerChannelApi = (app, deps) => {
26555
26592
  if (!row) return void res.json({ links: [] });
26556
26593
  const at = now();
26557
26594
  const links = await createLinkStore(db2).listForChannel(row.id);
26595
+ const mayReadUsers = gate.user.super_admin === true || gate.user.role?.users === "read" || gate.user.role?.users === "write";
26596
+ const emails = /* @__PURE__ */ new Map();
26597
+ const ids = [...new Set(links.map((l) => l.user))];
26598
+ if (mayReadUsers && ids.length > 0) {
26599
+ const owners = await db2("users").whereIn("id", ids).select("id", "email");
26600
+ for (const o of owners) emails.set(o.id, o.email ?? null);
26601
+ }
26558
26602
  res.json({
26559
26603
  links: links.map((l) => ({
26560
26604
  id: l.id,
26561
26605
  identityMasked: maskIdentity(l.identity),
26562
26606
  userId: l.user,
26607
+ userEmail: emails.get(l.user) ?? null,
26563
26608
  linked_at: l.linked_at,
26564
26609
  expires_at: l.expires_at,
26565
26610
  last_seen_at: l.last_seen_at,
@@ -26568,6 +26613,19 @@ var registerChannelApi = (app, deps) => {
26568
26613
  });
26569
26614
  })
26570
26615
  );
26616
+ app.post(
26617
+ `${base}/verify-token`,
26618
+ route("rotate verify token", async (req, res) => {
26619
+ const gate = await adminAgent(req, res);
26620
+ if (!gate) return;
26621
+ const db2 = await deps.getDb();
26622
+ const row = await loadChannel(db2, gate.agent.id);
26623
+ if (!row) return void res.status(404).json({ detail: "Channel not found." });
26624
+ const verifyToken = (0, import_crypto7.randomBytes)(24).toString("base64url");
26625
+ await db2(TABLE4).where({ id: row.id }).update({ verify_token: verifyToken, updatedAt: now() });
26626
+ res.json({ verifyToken });
26627
+ })
26628
+ );
26571
26629
  app.delete(
26572
26630
  `${base}/links/:linkId`,
26573
26631
  route("revoke link", async (req, res) => {
@@ -26588,24 +26646,53 @@ var registerChannelApi = (app, deps) => {
26588
26646
  res.status(204).end();
26589
26647
  })
26590
26648
  );
26591
- const customerChannel = async (req, opts) => {
26649
+ const customerChannel = async (req) => {
26592
26650
  const agent = await loadAgent(String(req.params.id ?? ""));
26593
26651
  if (!agent) return null;
26594
26652
  const db2 = await deps.getDb();
26595
26653
  const row = await loadChannel(db2, agent.id);
26596
26654
  if (!row) return null;
26597
- if (opts.requireEnabled && !row.enabled) return null;
26598
26655
  return { db: db2, agent, row };
26599
26656
  };
26657
+ const linkableConfig = (agent, row) => {
26658
+ if (!deps.entitled() || !row.enabled) return null;
26659
+ const config = tryParseConfig(row.config);
26660
+ return config && canEnableChannel(agent).ok ? config : null;
26661
+ };
26662
+ app.get(
26663
+ "/public-agents/:id/channels/whatsapp/links",
26664
+ route("customer links", async (req, res) => {
26665
+ const user = await signedIn(req, res);
26666
+ if (!user) return;
26667
+ const none = { available: false, links: [] };
26668
+ if (!deps.entitled()) return void res.json(none);
26669
+ const agent = await loadAgent(String(req.params.id ?? ""));
26670
+ if (!agent) return void res.json(none);
26671
+ const db2 = await deps.getDb();
26672
+ const row = await loadChannel(db2, agent.id);
26673
+ const links = row ? await createLinkStore(db2).listForUser(row.id, user.id) : [];
26674
+ const available = !!row && linkableConfig(agent, row) !== null && await channelAccessAllowed({
26675
+ db: db2,
26676
+ loadAgent: (id) => loadAgent(id),
26677
+ agentId: agent.id,
26678
+ channelId: row.id,
26679
+ userId: user.id
26680
+ });
26681
+ res.json({
26682
+ available,
26683
+ links: links.filter((l) => !l.revoked_at).map((l) => ({ id: l.id, identityMasked: maskIdentity(l.identity), expires_at: l.expires_at }))
26684
+ });
26685
+ })
26686
+ );
26600
26687
  app.post(
26601
26688
  "/public-agents/:id/channels/whatsapp/link-code",
26602
26689
  route("issue link code", async (req, res) => {
26603
26690
  const user = await signedIn(req, res);
26604
26691
  if (!user) return;
26605
26692
  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);
26693
+ const found = await customerChannel(req);
26694
+ const config = found ? linkableConfig(found.agent, found.row) : null;
26695
+ if (!found || !config) return void res.status(404).json(NOT_FOUND);
26609
26696
  const { db: db2, agent, row } = found;
26610
26697
  const allowed = await channelAccessAllowed({
26611
26698
  db: db2,
@@ -26650,7 +26737,7 @@ var registerChannelApi = (app, deps) => {
26650
26737
  if (!user) return;
26651
26738
  const linkId = String(req.params.linkId ?? "");
26652
26739
  if (!UUID_RE2.test(linkId)) return void res.status(404).json(NOT_FOUND);
26653
- const found = await customerChannel(req, { requireEnabled: false });
26740
+ const found = await customerChannel(req);
26654
26741
  if (!found) return void res.status(404).json(NOT_FOUND);
26655
26742
  const { db: db2, row } = found;
26656
26743
  const link = await db2("channel_links").where({ id: linkId, channel: row.id, user: user.id }).first();
@@ -31328,7 +31415,7 @@ var createDecideDeps = (p) => {
31328
31415
  now: env.now ?? (() => /* @__PURE__ */ new Date()),
31329
31416
  config,
31330
31417
  // lazily: a missing URL variable must only affect the link reply, never linked users
31331
- linkUrl: () => linkPageUrl(row.agent),
31418
+ linkUrl: () => linkPageUrl(row.agent, config.locale),
31332
31419
  links: createLinkStore(db2),
31333
31420
  consumeCode: (code) => consumeCode(store, code),
31334
31421
  codeAttemptsExceeded: (identity) => codeAttemptsExceeded(store, row.id, identity),
@@ -42928,6 +43015,25 @@ See docs/superpowers/specs/2026-05-31-in-chat-image-generation-design.md for the
42928
43015
  // src/exulu/routes.ts
42929
43016
  var import_node_path15 = require("path");
42930
43017
  init_rbac_resolver();
43018
+
43019
+ // src/exulu/session-access.ts
43020
+ init_cjs_shims();
43021
+ init_rbac_resolver();
43022
+ init_check_record_access();
43023
+ var SESSION_RBAC_ENTITY = "agent_session";
43024
+ async function hasSessionAccess(db2, session, rights, user) {
43025
+ const rbac = await RBACResolver(
43026
+ db2,
43027
+ SESSION_RBAC_ENTITY,
43028
+ session.id,
43029
+ session.rights_mode || "private"
43030
+ );
43031
+ const record = { ...session, RBAC: rbac };
43032
+ if (await checkRecordAccess(record, rights, user)) return true;
43033
+ return rights === "read" ? checkRecordAccess(record, "write", user) : false;
43034
+ }
43035
+
43036
+ // src/exulu/routes.ts
42931
43037
  init_tags();
42932
43038
  init_admin_client();
42933
43039
  init_env();
@@ -44995,17 +45101,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
44995
45101
  res.status(404).json({ detail: `Session ${sessionId} not found.` });
44996
45102
  return null;
44997
45103
  }
44998
- const sessionRbac = await RBACResolver(
44999
- db2,
45000
- "agent_sessions",
45001
- session.id,
45002
- session.rights_mode || "private"
45003
- );
45004
- const allowed = await checkRecordAccess(
45005
- { ...session, RBAC: sessionRbac },
45006
- rights,
45007
- authResult.user
45008
- );
45104
+ const allowed = await hasSessionAccess(db2, session, rights, authResult.user);
45009
45105
  if (!allowed) {
45010
45106
  res.status(403).json({ detail: `You don't have ${rights} access to this session.` });
45011
45107
  return null;
@@ -45033,7 +45129,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
45033
45129
  }
45034
45130
  const rbac = await RBACResolver(
45035
45131
  db2,
45036
- "platform_configurations",
45132
+ "platform_configuration",
45037
45133
  row.id,
45038
45134
  row.rights_mode || "private"
45039
45135
  );
@@ -49158,7 +49254,7 @@ var loadAvailableStyles = async (user) => {
49158
49254
  for (const row of rows) {
49159
49255
  const rbac = await RBACResolver(
49160
49256
  db2,
49161
- "platform_configurations",
49257
+ "platform_configuration",
49162
49258
  row.id,
49163
49259
  row.rights_mode || "private"
49164
49260
  );
package/dist/index.js CHANGED
@@ -246,7 +246,7 @@ import {
246
246
  willEmbedOnQueue,
247
247
  withRunSession,
248
248
  workflowTemplatesSchema
249
- } from "./chunk-ZNG2HEDN.js";
249
+ } from "./chunk-PNBVWUEA.js";
250
250
  import {
251
251
  LITELLM_UI_PATH,
252
252
  ResolveModelError,
@@ -2965,12 +2965,12 @@ var channelView = (row) => ({
2965
2965
  needsCredentials: readSecrets(row) === null
2966
2966
  });
2967
2967
  var maskIdentity = (identity) => identity.length < 4 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022 ${identity.slice(-4)}`;
2968
- var linkPageUrl = (agentId) => {
2968
+ var linkPageUrl = (agentId, locale) => {
2969
2969
  const base = [process.env.CHANNEL_LINK_BASE_URL, process.env.FRONTEND, process.env.NEXTAUTH_URL].map((v) => (v ?? "").trim()).find((v) => v !== "");
2970
2970
  if (!base) {
2971
2971
  throw new ChannelSetupError("None of CHANNEL_LINK_BASE_URL, FRONTEND and NEXTAUTH_URL is set; the channel link page has no URL");
2972
2972
  }
2973
- return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp`;
2973
+ return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp${locale ? `?lang=${locale}` : ""}`;
2974
2974
  };
2975
2975
 
2976
2976
  // src/exulu/channels/link-codes.ts
@@ -3478,11 +3478,19 @@ var registerChannelApi = (app, deps) => {
3478
3478
  if (!row) return void res.json({ links: [] });
3479
3479
  const at = now();
3480
3480
  const links = await createLinkStore(db).listForChannel(row.id);
3481
+ const mayReadUsers = gate.user.super_admin === true || gate.user.role?.users === "read" || gate.user.role?.users === "write";
3482
+ const emails = /* @__PURE__ */ new Map();
3483
+ const ids = [...new Set(links.map((l) => l.user))];
3484
+ if (mayReadUsers && ids.length > 0) {
3485
+ const owners = await db("users").whereIn("id", ids).select("id", "email");
3486
+ for (const o of owners) emails.set(o.id, o.email ?? null);
3487
+ }
3481
3488
  res.json({
3482
3489
  links: links.map((l) => ({
3483
3490
  id: l.id,
3484
3491
  identityMasked: maskIdentity(l.identity),
3485
3492
  userId: l.user,
3493
+ userEmail: emails.get(l.user) ?? null,
3486
3494
  linked_at: l.linked_at,
3487
3495
  expires_at: l.expires_at,
3488
3496
  last_seen_at: l.last_seen_at,
@@ -3491,6 +3499,19 @@ var registerChannelApi = (app, deps) => {
3491
3499
  });
3492
3500
  })
3493
3501
  );
3502
+ app.post(
3503
+ `${base}/verify-token`,
3504
+ route("rotate verify token", async (req, res) => {
3505
+ const gate = await adminAgent(req, res);
3506
+ if (!gate) return;
3507
+ const db = await deps.getDb();
3508
+ const row = await loadChannel(db, gate.agent.id);
3509
+ if (!row) return void res.status(404).json({ detail: "Channel not found." });
3510
+ const verifyToken = randomBytes(24).toString("base64url");
3511
+ await db(TABLE3).where({ id: row.id }).update({ verify_token: verifyToken, updatedAt: now() });
3512
+ res.json({ verifyToken });
3513
+ })
3514
+ );
3494
3515
  app.delete(
3495
3516
  `${base}/links/:linkId`,
3496
3517
  route("revoke link", async (req, res) => {
@@ -3511,24 +3532,53 @@ var registerChannelApi = (app, deps) => {
3511
3532
  res.status(204).end();
3512
3533
  })
3513
3534
  );
3514
- const customerChannel = async (req, opts) => {
3535
+ const customerChannel = async (req) => {
3515
3536
  const agent = await loadAgent(String(req.params.id ?? ""));
3516
3537
  if (!agent) return null;
3517
3538
  const db = await deps.getDb();
3518
3539
  const row = await loadChannel(db, agent.id);
3519
3540
  if (!row) return null;
3520
- if (opts.requireEnabled && !row.enabled) return null;
3521
3541
  return { db, agent, row };
3522
3542
  };
3543
+ const linkableConfig = (agent, row) => {
3544
+ if (!deps.entitled() || !row.enabled) return null;
3545
+ const config = tryParseConfig(row.config);
3546
+ return config && canEnableChannel(agent).ok ? config : null;
3547
+ };
3548
+ app.get(
3549
+ "/public-agents/:id/channels/whatsapp/links",
3550
+ route("customer links", async (req, res) => {
3551
+ const user = await signedIn(req, res);
3552
+ if (!user) return;
3553
+ const none = { available: false, links: [] };
3554
+ if (!deps.entitled()) return void res.json(none);
3555
+ const agent = await loadAgent(String(req.params.id ?? ""));
3556
+ if (!agent) return void res.json(none);
3557
+ const db = await deps.getDb();
3558
+ const row = await loadChannel(db, agent.id);
3559
+ const links = row ? await createLinkStore(db).listForUser(row.id, user.id) : [];
3560
+ const available = !!row && linkableConfig(agent, row) !== null && await channelAccessAllowed({
3561
+ db,
3562
+ loadAgent: (id) => loadAgent(id),
3563
+ agentId: agent.id,
3564
+ channelId: row.id,
3565
+ userId: user.id
3566
+ });
3567
+ res.json({
3568
+ available,
3569
+ links: links.filter((l) => !l.revoked_at).map((l) => ({ id: l.id, identityMasked: maskIdentity(l.identity), expires_at: l.expires_at }))
3570
+ });
3571
+ })
3572
+ );
3523
3573
  app.post(
3524
3574
  "/public-agents/:id/channels/whatsapp/link-code",
3525
3575
  route("issue link code", async (req, res) => {
3526
3576
  const user = await signedIn(req, res);
3527
3577
  if (!user) return;
3528
3578
  if (!deps.entitled()) return void res.status(404).json(NOT_FOUND);
3529
- const found = await customerChannel(req, { requireEnabled: true });
3530
- const config = found ? tryParseConfig(found.row.config) : null;
3531
- if (!found || !config || !canEnableChannel(found.agent).ok) return void res.status(404).json(NOT_FOUND);
3579
+ const found = await customerChannel(req);
3580
+ const config = found ? linkableConfig(found.agent, found.row) : null;
3581
+ if (!found || !config) return void res.status(404).json(NOT_FOUND);
3532
3582
  const { db, agent, row } = found;
3533
3583
  const allowed = await channelAccessAllowed({
3534
3584
  db,
@@ -3573,7 +3623,7 @@ var registerChannelApi = (app, deps) => {
3573
3623
  if (!user) return;
3574
3624
  const linkId = String(req.params.linkId ?? "");
3575
3625
  if (!UUID_RE2.test(linkId)) return void res.status(404).json(NOT_FOUND);
3576
- const found = await customerChannel(req, { requireEnabled: false });
3626
+ const found = await customerChannel(req);
3577
3627
  if (!found) return void res.status(404).json(NOT_FOUND);
3578
3628
  const { db, row } = found;
3579
3629
  const link = await db("channel_links").where({ id: linkId, channel: row.id, user: user.id }).first();
@@ -8087,7 +8137,7 @@ var createDecideDeps = (p) => {
8087
8137
  now: env.now ?? (() => /* @__PURE__ */ new Date()),
8088
8138
  config,
8089
8139
  // lazily: a missing URL variable must only affect the link reply, never linked users
8090
- linkUrl: () => linkPageUrl(row.agent),
8140
+ linkUrl: () => linkPageUrl(row.agent, config.locale),
8091
8141
  links: createLinkStore(db),
8092
8142
  consumeCode: (code) => consumeCode(store, code),
8093
8143
  codeAttemptsExceeded: (identity) => codeAttemptsExceeded(store, row.id, identity),
@@ -19463,6 +19513,20 @@ See docs/superpowers/specs/2026-05-31-in-chat-image-generation-design.md for the
19463
19513
  // src/exulu/routes.ts
19464
19514
  import { resolve as resolvePath } from "path";
19465
19515
 
19516
+ // src/exulu/session-access.ts
19517
+ var SESSION_RBAC_ENTITY = "agent_session";
19518
+ async function hasSessionAccess(db, session, rights, user) {
19519
+ const rbac = await RBACResolver(
19520
+ db,
19521
+ SESSION_RBAC_ENTITY,
19522
+ session.id,
19523
+ session.rights_mode || "private"
19524
+ );
19525
+ const record = { ...session, RBAC: rbac };
19526
+ if (await checkRecordAccess(record, rights, user)) return true;
19527
+ return rights === "read" ? checkRecordAccess(record, "write", user) : false;
19528
+ }
19529
+
19466
19530
  // src/exulu/litellm/passthrough-allowlist.ts
19467
19531
  var isLiteLLMPassthroughPathAllowed = (path) => path.startsWith("/v1/") || path === "/model/info";
19468
19532
 
@@ -21480,17 +21544,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21480
21544
  res.status(404).json({ detail: `Session ${sessionId} not found.` });
21481
21545
  return null;
21482
21546
  }
21483
- const sessionRbac = await RBACResolver(
21484
- db,
21485
- "agent_sessions",
21486
- session.id,
21487
- session.rights_mode || "private"
21488
- );
21489
- const allowed = await checkRecordAccess(
21490
- { ...session, RBAC: sessionRbac },
21491
- rights,
21492
- authResult.user
21493
- );
21547
+ const allowed = await hasSessionAccess(db, session, rights, authResult.user);
21494
21548
  if (!allowed) {
21495
21549
  res.status(403).json({ detail: `You don't have ${rights} access to this session.` });
21496
21550
  return null;
@@ -21518,7 +21572,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21518
21572
  }
21519
21573
  const rbac = await RBACResolver(
21520
21574
  db,
21521
- "platform_configurations",
21575
+ "platform_configuration",
21522
21576
  row.id,
21523
21577
  row.rights_mode || "private"
21524
21578
  );
@@ -25602,7 +25656,7 @@ var loadAvailableStyles = async (user) => {
25602
25656
  for (const row of rows) {
25603
25657
  const rbac = await RBACResolver(
25604
25658
  db,
25605
- "platform_configurations",
25659
+ "platform_configuration",
25606
25660
  row.id,
25607
25661
  row.rights_mode || "private"
25608
25662
  );
@@ -1,4 +1,10 @@
1
- import { fuzzyPrefilter, exactTokenPrefilter, resolveIdentifierPins, clearPrefilterCaches } from "./prefilter";
1
+ import {
2
+ fuzzyPrefilter,
3
+ exactTokenPrefilter,
4
+ resolveIdentifierPins,
5
+ clearPrefilterCaches,
6
+ identifiersInQuestion,
7
+ } from "./prefilter";
2
8
 
3
9
  jest.mock("ai", () => ({
4
10
  ...jest.requireActual("ai"),
@@ -247,3 +253,94 @@ describe("resolveIdentifierPins", () => {
247
253
  expect([...(r.exactPinsByContext.get("docs") ?? [])]).toContain("3");
248
254
  });
249
255
  });
256
+
257
+ describe("identifiersInQuestion", () => {
258
+ const keep = (matches: string[], question: string) => identifiersInQuestion(matches, question);
259
+
260
+ it("drops identifiers the question does not contain (the instruction's own example echoed back)", () => {
261
+ expect(keep(["FST", "FST-3"], "Ziehl-Abegg 4C Frequenzumrichter Fehler E 533")).toEqual([]);
262
+ expect(keep(["FST", "FST-2XT"], "Ziehl-Abegg 4C Frequenzumrichter Fehler E 533")).toEqual([]);
263
+ });
264
+
265
+ it("keeps the stem and the full form of an identifier that is in the question", () => {
266
+ expect(keep(["FST", "FST-2XT"], "Wie stelle ich die Türzeiten an der FST-2XT ein?")).toEqual(["FST", "FST-2XT"]);
267
+ expect(keep(["ZADyn", "ZADyn 4CA"], "Kann ich den Umrichter ZADyn 4CA mit 3x230V betreiben?")).toEqual([
268
+ "ZADyn",
269
+ "ZADyn 4CA",
270
+ ]);
271
+ expect(keep(["L1000A", "L1000"], "Fehler E 201 am Yaskawa L1000A")).toEqual(["L1000A", "L1000"]);
272
+ });
273
+
274
+ it("ignores case and how the parts are separated", () => {
275
+ expect(keep(["FST-2XT"], "türzeiten fst2xt")).toEqual(["FST-2XT"]);
276
+ expect(keep(["FST-2XT"], "Türzeiten FST 2 XT")).toEqual(["FST-2XT"]);
277
+ expect(keep(["TFT3-CAN"], "tft3 can anschließen")).toEqual(["TFT3-CAN"]);
278
+ });
279
+
280
+ it("keeps partial forms of a multi-part identifier", () => {
281
+ expect(keep(["8100-1", "8100-2", "ISO 8100-1-2"], "Was regelt die ISO 8100-1-2?")).toEqual([
282
+ "8100-1",
283
+ "8100-2",
284
+ "ISO 8100-1-2",
285
+ ]);
286
+ });
287
+
288
+ it("keeps the identifiers that are there when others are not", () => {
289
+ expect(keep(["CBM", "CBM-2", "FST"], "Bremsentest beim CBM-2")).toEqual(["CBM", "CBM-2"]);
290
+ });
291
+
292
+ it("keeps an identifier the model corrected from a typo in the question", () => {
293
+ expect(keep(["FST", "FST-2XT"], "Wie stelle ich die Türzeiten an der FTS-2XT ein?")).toEqual(["FST", "FST-2XT"]);
294
+ expect(keep(["FST", "FST"], "Fehler 131 an der FTS")).toEqual(["FST", "FST"]);
295
+ expect(keep(["CBM", "CBM-2"], "Bremsentest CMB-2")).toEqual(["CBM", "CBM-2"]);
296
+ expect(keep(["ZADyn", "ZADyn 4CA"], "Umrichter ZAdin 4CA an 3x230V")).toEqual(["ZADyn", "ZADyn 4CA"]);
297
+ expect(keep(["ELEVISION"], "Wie melde ich mich in Elevison an?")).toEqual(["ELEVISION"]);
298
+ });
299
+
300
+ it("does not take an ordinary word one letter away from a short name for a typo", () => {
301
+ expect(keep(["FST"], "Was ist der Fehler E 533?")).toEqual([]);
302
+ expect(keep(["ECO"], "Welches Eck ist gemeint?")).toEqual([]);
303
+ expect(keep(["PAM"], "Wie viel Platz am Schacht?")).toEqual([]);
304
+ });
305
+
306
+ it("does not let letters from neighbouring words stand in for a name", () => {
307
+ expect(keep(["ECO"], "wie code ich das")).toEqual([]);
308
+ });
309
+
310
+ it("drops empty and single-character matches", () => {
311
+ expect(keep(["", " ", "-", "S"], "S 2 Box")).toEqual([]);
312
+ });
313
+ });
314
+
315
+ describe("resolveIdentifierPins grounding", () => {
316
+ const set = { name: "Product names", description: "", examples: ["FST"], strategy: "fuzzy" as const, contexts: ["docs"] };
317
+
318
+ it("pins nothing, and says so, when the extraction names a product the question lacks", async () => {
319
+ (generateText as jest.Mock).mockResolvedValue({ output: { hasMatches: true, matches: ["FST", "FST-2XT"] } });
320
+ const c = ctx("docs");
321
+ const r = await resolveIdentifierPins({
322
+ question: "Ziehl-Abegg 4C Frequenzumrichter Fehler E 533",
323
+ identifierSets: [set],
324
+ contextsById: new Map([["docs", c]]),
325
+ kbKindById: new Map([["docs", "documents"]]),
326
+ model: {},
327
+ });
328
+ expect(r.pinsByContext.size).toBe(0);
329
+ expect(c.getItems).not.toHaveBeenCalled();
330
+ expect(r.steps.map((s) => s.text).join("\n")).not.toMatch(/Detected|Limiting/);
331
+ expect(r.steps.map((s) => s.text).join("\n")).toMatch(/Ignored.*FST, FST-2XT/);
332
+ });
333
+
334
+ it("pins from the identifiers that are in the question only", async () => {
335
+ (generateText as jest.Mock).mockResolvedValue({ output: { hasMatches: true, matches: ["ECO", "FST", "FST-2XT"] } });
336
+ const r = await resolveIdentifierPins({
337
+ question: "Wie sperre ich die Tür beim FST-2XT?",
338
+ identifierSets: [set],
339
+ contextsById: new Map([["docs", ctx("docs")]]),
340
+ kbKindById: new Map([["docs", "documents"]]),
341
+ model: {},
342
+ });
343
+ expect([...(r.pinsByContext.get("docs") ?? [])]).toEqual(["1"]);
344
+ expect(r.steps[0].text).toBe("Detected Product names in the question: FST, FST-2XT");
345
+ });
346
+ });
@@ -403,6 +403,61 @@ If the question references none, return hasMatches false and an empty array.`;
403
403
  // Config-driven identifier-pin resolution
404
404
  // ---------------------------------------------------------------------------
405
405
 
406
+ const alnumRuns = (text: string): string[] =>
407
+ text.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
408
+
409
+ /**
410
+ * The extracted identifiers that the question actually contains.
411
+ *
412
+ * The extraction model sometimes answers with an identifier from its own instruction
413
+ * (the configured examples) for a question that names none of them. Pins are a hard
414
+ * whitelist over file names, so one such answer hides every other document of the
415
+ * knowledge base. An identifier therefore only counts when its parts are in the question:
416
+ * each part of two or more characters inside one of the question's words, or — for
417
+ * identifiers written apart in the question ("FST 2 XT" for "FST-2XT") — the parts joined
418
+ * inside the question's words joined. Case and separators do not matter.
419
+ *
420
+ * The model also corrects typos ("FTS-2XT" → "FST-2XT"), and those corrections are wanted.
421
+ * A part therefore also counts when a word of the question is a typo of it (see isTypoOf).
422
+ */
423
+ export function identifiersInQuestion(matches: string[], question: string): string[] {
424
+ const words = alnumRuns(question);
425
+ const joinedWords = words.join("");
426
+ const inQuestion = (part: string) =>
427
+ words.some((word) => word.includes(part) || isTypoOf(word, part));
428
+ return matches.filter((match) => {
429
+ const parts = alnumRuns(match);
430
+ const long = parts.filter((part) => part.length >= 2);
431
+ if (long.length === 0) return false;
432
+ if (long.every(inQuestion)) return true;
433
+ return parts.length >= 2 && joinedWords.includes(parts.join(""));
434
+ });
435
+ }
436
+
437
+ /**
438
+ * Whether `word` is `part` with one typing slip. Short names are one substituted letter
439
+ * away from ordinary words ("FST" / "ist"), so below five characters only two swapped
440
+ * neighbouring letters count ("FTS"); from five on, any single slip does (one letter
441
+ * swapped with its neighbour, missing, extra or wrong).
442
+ */
443
+ function isTypoOf(word: string, part: string): boolean {
444
+ if (part.length < 3 || word === part) return false;
445
+ if (Math.abs(word.length - part.length) > 1) return false;
446
+ if (word.length === part.length) {
447
+ const diff: number[] = [];
448
+ for (let i = 0; i < part.length; i++) if (word[i] !== part[i]) diff.push(i);
449
+ if (diff.length === 2 && diff[1] === diff[0]! + 1) {
450
+ return word[diff[0]!] === part[diff[1]!] && word[diff[1]!] === part[diff[0]!];
451
+ }
452
+ return part.length >= 5 && diff.length === 1;
453
+ }
454
+ if (part.length < 5) return false;
455
+ const [short, longer] = word.length < part.length ? [word, part] : [part, word];
456
+ let i = 0;
457
+ while (i < short.length && short[i] === longer[i]) i++;
458
+ return short.slice(i) === longer.slice(i + 1);
459
+ }
460
+
406
461
  export async function resolveIdentifierPins({
407
462
  question,
408
463
  identifierSets,
@@ -442,7 +497,14 @@ export async function resolveIdentifierPins({
442
497
  }),
443
498
  });
444
499
  if (!output?.hasMatches || !output.matches?.length) return;
445
- steps.push({ text: `Detected ${set.name} in the question: ${output.matches.join(", ")}` });
500
+ const matches = identifiersInQuestion(output.matches, question);
501
+ if (!matches.length) {
502
+ steps.push({
503
+ text: `Ignored ${set.name} that are not in the question: ${output.matches.join(", ")}`,
504
+ });
505
+ return;
506
+ }
507
+ steps.push({ text: `Detected ${set.name} in the question: ${matches.join(", ")}` });
446
508
 
447
509
  await Promise.all(
448
510
  set.contexts.map(async (ctxId) => {
@@ -457,10 +519,10 @@ export async function resolveIdentifierPins({
457
519
  };
458
520
  const matched =
459
521
  set.strategy === "exact"
460
- ? await exactTokenPrefilter({ ...common, tokens: output.matches! })
522
+ ? await exactTokenPrefilter({ ...common, tokens: matches })
461
523
  : await fuzzyPrefilter({
462
524
  ...common,
463
- relevantKeywords: output.matches!,
525
+ relevantKeywords: matches,
464
526
  cutoff: DEFAULT_PREFILTER_CUTOFF,
465
527
  // Identifier pins are a hard id-whitelist over filenames,
466
528
  // which is exactly the case the supplement exists for.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.17.1",
4
+ "version": "5.18.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {