@peopl-health/nexus 5.76.0 → 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;
@@ -404,6 +404,7 @@ class BaseLLMProvider {
404
404
  const self = checkIn.reminderId ? `${checkIn.reminderId}${checkIn.dueAt ? `, programado para ${local(checkIn.dueAt)}` : ''}` : null;
405
405
  const pending = lines([
406
406
  ['este check-in', self],
407
+ ['tipo', checkIn.type === 'contingencia' ? 'red de contingencia' : 'seguimiento que programaste: esta pregunta todavía no le ha llegado'],
407
408
  ['lo que querías preguntarle', checkIn.question],
408
409
  ['por qué quedó abierto', checkIn.concern],
409
410
  ['qué dato esperabas', checkIn.awaiting],
@@ -435,9 +436,9 @@ class BaseLLMProvider {
435
436
  '- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
436
437
  '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que contó o acordó.',
437
438
  exchange?.sessionOpen === false
438
- ? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo diciendo en pocas palabras qué retomas («te había preguntado por…»).'
439
- : 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego di en pocas palabras qué retomas («te había preguntado por…»).',
440
- 'Haz una sola pregunta por lo que sigue faltando de lo que esperabas saber. Háblale directo a quien lleva la conversación, de tú o de usted, como en la conversación; nunca hables en tercera persona de quien te está leyendo.',
439
+ ? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo a lo que quieres saber.'
440
+ : 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego entra a lo que quieres saber.',
441
+ 'En un seguimiento que programaste es la primera vez que se lo preguntas: no digas que ya se lo habías preguntado. En una red, si tu mensaje anterior ya se lo preguntó, dilo en pocas palabras («te había preguntado por…» o «le había preguntado por…», según cómo le hables). Esa única pregunta va por lo que sigue faltando de lo que esperabas saber; si lo que querías preguntarle trae varias, elige la que más importa hoy. Háblale directo a quien lleva la conversación, de tú o de usted, como en la conversación; nunca hables en tercera persona de quien te está leyendo.',
441
442
  'No le comentes como novedad algo que no te dijo en el chat: sus respuestas del cuestionario las conoces tú, no son algo que te acaba de contar. No repitas lo que ya le dijiste (por ejemplo, que el equipo ya tiene el aviso) ni des por hecho detalles que no te dio.',
442
443
  'Breve, sin listas de señales de alarma y sin mencionar recordatorios, planes ni seguimientos programados.',
443
444
  );
@@ -858,7 +859,7 @@ class BaseLLMProvider {
858
859
  _bridgeFrom(calls) {
859
860
  const pick = (name, field) => {
860
861
  const value = calls.find(call => call.name === name)?.input?.[field];
861
- return typeof value === 'string' && value.trim() ? value : null;
862
+ return typeof value === 'string' && value.trim() ? decodeLiteralUnicodeEscapes(value) : null;
862
863
  };
863
864
  const extraction = calls.find(call => call.name === EXTRACTION_TOOL)?.input;
864
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
  });
@@ -23,7 +23,7 @@ const definition = {
23
23
  },
24
24
  reminder_description: {
25
25
  type: 'string',
26
- description: 'Short description of what the reminder is for (e.g. \'tomar ondansetrón antes del desayuno\', \'preguntarle cómo amaneció del dolor de cabeza\'). This becomes the WhatsApp message body. For a Programme activity name the format — la charla, tu sesión colectiva, tu sesión individual — never a bare \'tu sesión\': the text stays in the conversation and is what a later turn reads to tell them apart.',
26
+ description: 'Short description of what the reminder is for (e.g. \'tomar ondansetrón antes del desayuno\', \'preguntarle cómo amaneció del dolor de cabeza\'). This becomes the WhatsApp message body. For seguimiento, one question only — the one that matters most on that date — written as asked for the first time (never «te había preguntado»). For a Programme activity name the format — la charla, tu sesión colectiva, tu sesión individual — never a bare \'tu sesión\': the text stays in the conversation and is what a later turn reads to tell them apart.',
27
27
  },
28
28
  reminder_type: {
29
29
  type: 'string',
@@ -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.0",
3
+ "version": "5.76.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",