@peopl-health/nexus 5.76.1 → 5.76.3
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/lib/clinical/models/triageRecommendationEventModel.js +1 -0
- package/lib/clinical/providers/BaseLLMProvider.js +2 -2
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +6 -1
- package/lib/clinical/services/triageRecommendationService.js +13 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +9 -3
- package/lib/controllers/messageController.js +4 -0
- package/lib/helpers/patientMessageHelper.js +3 -1
- package/lib/utils/jsonUtils.js +21 -0
- package/package.json +1 -1
|
@@ -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
|
});
|
|
@@ -155,11 +155,17 @@ const MODE_PROPERTY = {
|
|
|
155
155
|
|
|
156
156
|
const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
|
|
157
157
|
|
|
158
|
-
|
|
158
|
+
// with the timer the fever rule sends to urgencias only from `stat`, like every other case
|
|
159
|
+
const FEVER_SIGNS = 'Outside `stat` and the fever rule, no warning signs';
|
|
160
|
+
const FEVER_SIGNS_TIMER = 'Outside `stat`, no warning signs';
|
|
161
|
+
const FEVER_URGENCIAS = '(two exceptions: the fever rule, and chest pain';
|
|
162
|
+
const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
|
|
163
|
+
|
|
164
|
+
const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, malaise while on an antipyretic or steroid, or ≤36.0 °C with malaise, chills or shivering — is `asap` with `category: febrile_neutropenia`. A low reading (≤36.0 °C) on its own is not fever: ask for an oral re-measure before escalating; still ≤36.0 °C with no other symptom is `urgent`, confirmed ≤35.0 °C is `asap`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
|
|
159
165
|
|
|
160
166
|
const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
|
|
161
167
|
|
|
162
|
-
const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C o ≤36.0 °C en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
|
|
168
|
+
const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o ≤36.0 °C con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
|
|
163
169
|
|
|
164
170
|
const CLINICAL_ASSESSMENT_PROPERTY = nullable({
|
|
165
171
|
'type': 'object',
|
|
@@ -217,7 +223,7 @@ function liveDefinition() {
|
|
|
217
223
|
properties.details.required.push('clinical_assessment');
|
|
218
224
|
}
|
|
219
225
|
if (feverTimer) {
|
|
220
|
-
live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER);
|
|
226
|
+
live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER).replace(FEVER_SIGNS, FEVER_SIGNS_TIMER).replace(FEVER_URGENCIAS, FEVER_URGENCIAS_TIMER);
|
|
221
227
|
properties.urgency_level.description = properties.urgency_level.description
|
|
222
228
|
.replace(FEVER_RUBRIC_STAT, FEVER_RUBRIC_STAT_TIMER)
|
|
223
229
|
.replace(FEVER_RUBRIC_ASAP, FEVER_RUBRIC_ASAP_TIMER);
|
|
@@ -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);
|
package/lib/utils/jsonUtils.js
CHANGED
|
@@ -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,
|