@peopl-health/nexus 5.76.1 → 5.76.2

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.
@@ -53,6 +53,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
53
53
  classifierWaitMs: { type: Number, default: null },
54
54
  deniedCardsDropped: { type: Number, default: null },
55
55
  deniedTargetsStripped: { type: Number, default: null },
56
+ cardsTruncated: { type: Number, default: null },
56
57
  adherenceRecorded: { type: Number, default: null },
57
58
  adherenceSkipped: { type: Number, default: null },
58
59
  adherenceNoTask: { type: Number, default: null },
@@ -21,7 +21,7 @@ const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
21
21
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
22
22
  const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
23
23
  const { isJsonBlob } = require('../../utils/formatUtils');
24
- const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
24
+ const { isPlainObject, safeParse, decodeLiteralUnicodeEscapes } = require('../../utils/jsonUtils');
25
25
  const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
26
26
 
27
27
  const EXCHANGE_LINE_LENGTH = 400;
@@ -859,7 +859,7 @@ class BaseLLMProvider {
859
859
  _bridgeFrom(calls) {
860
860
  const pick = (name, field) => {
861
861
  const value = calls.find(call => call.name === name)?.input?.[field];
862
- return typeof value === 'string' && value.trim() ? value : null;
862
+ return typeof value === 'string' && value.trim() ? decodeLiteralUnicodeEscapes(value) : null;
863
863
  };
864
864
  const extraction = calls.find(call => call.name === EXTRACTION_TOOL)?.input;
865
865
  if (pick(EXTRACTION_TOOL, 'non_clinical_request') && pick(EXTRACTION_TOOL, 'raw_message') && extraction?.detected_tags?.length === 0) {
@@ -1,7 +1,7 @@
1
1
  const { isToolFailure, toolFailureError } = require('../helpers/toolResultHelper');
2
2
 
3
3
  const { logger } = require('../../utils/logger');
4
- const { safeParse } = require('../../utils/jsonUtils');
4
+ const { safeParse, normalizeModelStrings } = require('../../utils/jsonUtils');
5
5
 
6
6
  const { hasTool, executeTool: registryExecuteTool } = require('../../services/toolRegistryService');
7
7
 
@@ -17,6 +17,11 @@ async function executeFunctionCall(assistant, call, phiProcessor) {
17
17
  } catch (e) {
18
18
  logger.warn('[executeFunctionCall] arg decode produced invalid JSON, falling back to original args', { name, errorType: e?.name || 'Error' });
19
19
  }
20
+ const normalizedArgs = normalizeModelStrings(decodedArgs);
21
+ if (JSON.stringify(normalizedArgs) !== JSON.stringify(decodedArgs)) {
22
+ logger.warn('[executeFunctionCall] decoded literal unicode escapes in tool arguments', { name, call_id: call.call_id });
23
+ decodedArgs = normalizedArgs;
24
+ }
20
25
 
21
26
  logger.info('[executeFunctionCall] Calling', { name, call_id: call.call_id });
22
27
 
@@ -74,6 +74,7 @@ const { prepareSupportAction } = require('./supportActionService');
74
74
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
75
75
  const GATE_MAX_ATTEMPTS = 2;
76
76
  const PLAN_MAX_ATTEMPTS = 2;
77
+ const MAX_TRIAGE_CARDS = 10;
77
78
  const PLAN_TRUNCATION_MAX_TOKENS = 16000;
78
79
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
79
80
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
@@ -619,6 +620,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
619
620
  settle.qualityWarnings = [...gateWarnings, ...qualityWarnings];
620
621
  settle.rankReordered = planOutcome.rankReordered;
621
622
  settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
623
+ settle.cardsTruncated = planOutcome.cardsTruncated;
622
624
  settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
623
625
 
624
626
  try {
@@ -878,6 +880,14 @@ function issuePaths(issues) {
878
880
  return [...new Set(issues.map((issue) => String(issue.path || '').replace(/\[[^\]]*\]/g, '[]')).filter(Boolean))];
879
881
  }
880
882
 
883
+ function truncateToCardLimit(elements, repairs) {
884
+ const excess = elements.length - MAX_TRIAGE_CARDS;
885
+ if (excess <= 0) return 0;
886
+ const cut = elements.splice(MAX_TRIAGE_CARDS);
887
+ repairs.push(`tarjetas recortadas al máximo del carrusel: ${MAX_TRIAGE_CARDS + excess} -> ${MAX_TRIAGE_CARDS} (rangos ${cut.map((e) => e.rank).join(',')})`);
888
+ return excess;
889
+ }
890
+
881
891
  async function runPlan({ provider, presetId, casoBase, gate, boundary = null, rankContext = {}, rid, code, payload }) {
882
892
  const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
883
893
  let lastIssues = [];
@@ -908,6 +918,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
908
918
  let rankReordered = 0;
909
919
  let deniedCardsDropped = 0;
910
920
  let deniedTargetsStripped = 0;
921
+ let cardsTruncated = 0;
911
922
  const budget = newTransientBudget();
912
923
  for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
913
924
  const content = attempt === 1 || !lastIssues.length
@@ -967,6 +978,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
967
978
  return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } });
968
979
  }
969
980
  rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
981
+ cardsTruncated = truncateToCardLimit(elements, repairs);
970
982
  const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
971
983
  const blocking = blockingIssues(issues);
972
984
  if (blocking.length) {
@@ -991,6 +1003,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
991
1003
  rankReordered,
992
1004
  deniedCardsDropped,
993
1005
  deniedTargetsStripped,
1006
+ cardsTruncated,
994
1007
  modelInput: content,
995
1008
  model: typeof result?.model === 'string' ? result.model : null,
996
1009
  });
@@ -83,6 +83,10 @@ const sendMessageController = async (req, res) => {
83
83
  return res.status(400).json({ success: false, error: 'code is required' });
84
84
  }
85
85
 
86
+ if (!message && !fileUrl && !contentSid) {
87
+ return res.status(400).json({ success: false, error: 'message, fileUrl or contentSid is required' });
88
+ }
89
+
86
90
  try {
87
91
  let contact = {};
88
92
  if (contactCode) {
@@ -1,3 +1,5 @@
1
+ const { decodeLiteralUnicodeEscapes } = require('../utils/jsonUtils');
2
+
1
3
  const PATIENT_MESSAGE_OPEN = '<patient_message>';
2
4
  const PATIENT_MESSAGE_CLOSE = '</patient_message>';
3
5
  const PATIENT_MESSAGE_BLOCK_RX = /<patient_message(?:\s[^>]*)?>\s*([\s\S]*?)\s*<\/patient_message\s*>/i;
@@ -58,7 +60,7 @@ function stripTurnMarkers(text) {
58
60
  function sanitizeOutput(text) {
59
61
  if (!text || typeof text !== 'string') return text;
60
62
 
61
- let sanitized = text;
63
+ let sanitized = decodeLiteralUnicodeEscapes(text);
62
64
  sanitized = stripTurnMarkers(sanitized);
63
65
  sanitized = removeBracketContent(sanitized);
64
66
  sanitized = formatForWhatsApp(sanitized);
@@ -9,6 +9,25 @@ function jsonStringifyWithUnicodeEscapes(obj) {
9
9
  });
10
10
  }
11
11
 
12
+ const LITERAL_ESCAPE_RUN = /(?<!\\)(?:\\u[0-9a-fA-F]{4})+/g;
13
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
14
+
15
+ // Models sometimes double-escape non-ASCII inside tool arguments, leaving a literal "\u00e9" after JSON.parse.
16
+ function decodeLiteralUnicodeEscapes(value) {
17
+ if (typeof value !== 'string' || !value.includes('\\u')) return value;
18
+ return value.replace(LITERAL_ESCAPE_RUN, (run) => {
19
+ const decoded = String.fromCharCode(...run.match(/[0-9a-fA-F]{4}/g).map((hex) => parseInt(hex, 16)));
20
+ return LONE_SURROGATE.test(decoded) ? run : decoded;
21
+ });
22
+ }
23
+
24
+ function normalizeModelStrings(value) {
25
+ if (typeof value === 'string') return decodeLiteralUnicodeEscapes(value);
26
+ if (Array.isArray(value)) return value.map(normalizeModelStrings);
27
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key, val]) => [key, normalizeModelStrings(val)]));
28
+ return value;
29
+ }
30
+
12
31
  function isPlainObject(value) {
13
32
  if (value === null || typeof value !== 'object') return false;
14
33
  const proto = Object.getPrototypeOf(value);
@@ -73,6 +92,8 @@ function stableStringify(value) {
73
92
 
74
93
  module.exports = {
75
94
  jsonStringifyWithUnicodeEscapes,
95
+ decodeLiteralUnicodeEscapes,
96
+ normalizeModelStrings,
76
97
  stableStringify,
77
98
  safeParse,
78
99
  safeParseArray,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.76.1",
3
+ "version": "5.76.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",