@peopl-health/nexus 5.59.4 → 5.59.6
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/AssistantProcessor.js +1 -1
- package/lib/clinical/helpers/triageCaseBaseHelper.js +11 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +7 -6
- package/lib/clinical/services/recommendationRankService.js +2 -1
- package/lib/clinical/services/triageRecommendationService.js +23 -7
- package/lib/core/NexusMessaging.js +58 -19
- package/package.json +1 -1
|
@@ -139,6 +139,7 @@ function buildSymptomsMetadata({
|
|
|
139
139
|
declined = [],
|
|
140
140
|
additionalSymptoms = [],
|
|
141
141
|
freeTextDerivedSymptoms = [],
|
|
142
|
+
freeTextUnmatchedSymptoms = [],
|
|
142
143
|
nonIdentifiedSymptoms = null,
|
|
143
144
|
stage = 'gate',
|
|
144
145
|
catalog = null,
|
|
@@ -177,6 +178,14 @@ function buildSymptomsMetadata({
|
|
|
177
178
|
+ 'clasificador y puede no ser el correcto: verifícalo con el paciente antes de darlo por confirmado.',
|
|
178
179
|
);
|
|
179
180
|
}
|
|
181
|
+
if (freeTextUnmatchedSymptoms.length) {
|
|
182
|
+
parts.push(
|
|
183
|
+
'Síntomas que el paciente escribió en el TEXTO LIBRE y que no tienen ítem PRO-CTCAE: '
|
|
184
|
+
+ freeTextUnmatchedSymptoms.join(', ')
|
|
185
|
+
+ '. Están PRESENTES, sin grado, y son material válido de recomendación. No los traduzcas a un '
|
|
186
|
+
+ 'ítem PRO-CTCAE parecido: si les haces una tarjeta, pon exactamente esa etiqueta en targeted_ctcae_terms.',
|
|
187
|
+
);
|
|
188
|
+
}
|
|
180
189
|
if (denied.length) {
|
|
181
190
|
parts.push(
|
|
182
191
|
'Síntomas NEGADOS explícitamente en la ventana de reporte del triaje (respuesta grado 0 a preguntas del triaje): '
|
|
@@ -370,6 +379,7 @@ function buildCasoBase({
|
|
|
370
379
|
freeText = null,
|
|
371
380
|
additionalSymptoms = [],
|
|
372
381
|
freeTextDerivedSymptoms = [],
|
|
382
|
+
freeTextUnmatchedSymptoms = [],
|
|
373
383
|
nonIdentifiedSymptoms = null,
|
|
374
384
|
stage = 'gate',
|
|
375
385
|
catalog = null,
|
|
@@ -396,6 +406,7 @@ function buildCasoBase({
|
|
|
396
406
|
declined,
|
|
397
407
|
additionalSymptoms,
|
|
398
408
|
freeTextDerivedSymptoms,
|
|
409
|
+
freeTextUnmatchedSymptoms,
|
|
399
410
|
nonIdentifiedSymptoms,
|
|
400
411
|
stage,
|
|
401
412
|
catalog,
|
|
@@ -51,12 +51,13 @@ function canonicalCtcaeTerm(catalog, term) {
|
|
|
51
51
|
return resolved ? spellingOf(catalog.symptoms[resolved], resolved) || term : term;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
)
|
|
54
|
+
// A free-text complaint the classifier could not code keeps the patient's label: a fuzzy
|
|
55
|
+
// alias match would rename it to a catalog term she never reported, and drop the card.
|
|
56
|
+
function canonicaliseTerms(element, catalog, uncodedKeys = new Set()) {
|
|
57
|
+
const canonical = (term) => (uncodedKeys.has(keyOf(term)) ? term : canonicalCtcaeTerm(catalog, term));
|
|
58
|
+
element.targetedCtcaeTerms = [...new Set(element.targetedCtcaeTerms.map(canonical))];
|
|
58
59
|
for (const symptom of element.symptoms) {
|
|
59
|
-
symptom.ctcaeTerm =
|
|
60
|
+
symptom.ctcaeTerm = canonical(symptom.ctcaeTerm);
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
@@ -166,7 +167,7 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
|
|
|
166
167
|
let dropped = 0;
|
|
167
168
|
let stripped = 0;
|
|
168
169
|
for (const element of elements) {
|
|
169
|
-
canonicaliseTerms(element, boundary.catalog);
|
|
170
|
+
canonicaliseTerms(element, boundary.catalog, boundary.uncodedKeys);
|
|
170
171
|
const breach = breachOf(element, boundary);
|
|
171
172
|
if (!breach) {
|
|
172
173
|
kept.push(element);
|
|
@@ -89,7 +89,7 @@ function buildRankContext({ catalog, graded = [], reportedTerms = [], priorResol
|
|
|
89
89
|
|
|
90
90
|
function buildSymptomSignals({
|
|
91
91
|
catalog, graded = [], ungradedTerms = [], additionalSymptoms = [], freeTextDerivedSymptoms = [],
|
|
92
|
-
priorResolutions = [], openCases = [],
|
|
92
|
+
freeTextUnmatchedSymptoms = [], priorResolutions = [], openCases = [],
|
|
93
93
|
}) {
|
|
94
94
|
const gradeByKey = new Map();
|
|
95
95
|
for (const symptom of graded) keepHighest(gradeByKey, aliasKeysOf(catalog, symptom.term), symptom.grade);
|
|
@@ -109,6 +109,7 @@ function buildSymptomSignals({
|
|
|
109
109
|
ungradedTerms.forEach((term) => add(term, 'cuestionario'));
|
|
110
110
|
additionalSymptoms.forEach((symptom) => add(symptom.label, 'checkbox', symptom));
|
|
111
111
|
freeTextDerivedSymptoms.forEach((term) => add(term, 'texto libre'));
|
|
112
|
+
freeTextUnmatchedSymptoms.forEach((label) => add(label, 'texto libre'));
|
|
112
113
|
|
|
113
114
|
return signals.map(({ keys, ...signal }) => ({
|
|
114
115
|
...signal,
|
|
@@ -38,6 +38,7 @@ const {
|
|
|
38
38
|
const { gradeComposites, PAIN_TERM } = require('../../fhir/helpers/compositeHelper');
|
|
39
39
|
const { affirmative } = require('../../fhir/helpers/terminologyHelper');
|
|
40
40
|
const { buildTriageResponse } = require('../../fhir/helpers/triagePayloadHelper');
|
|
41
|
+
const { keyOf } = require('../../fhir/helpers/symptomAliasHelper');
|
|
41
42
|
const { getCatalog } = require('../../fhir/services/terminologyService');
|
|
42
43
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
43
44
|
const { RecommendationPlan } = require('../../shared/dtos/RecommendationPlan');
|
|
@@ -262,11 +263,12 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
262
263
|
return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
|
|
263
264
|
}
|
|
264
265
|
const freeTextDerivedSymptoms = classifier.terms;
|
|
266
|
+
const freeTextUnmatchedSymptoms = classifier.unmatched || [];
|
|
265
267
|
settle.classifierPending = classifier.pending;
|
|
266
268
|
settle.classifierOutcome = classifier.outcome;
|
|
267
269
|
settle.classifierWaitMs = classifier.waitMs;
|
|
268
270
|
|
|
269
|
-
let supportContext = { triage: triageResponse, freeTextDerivedSymptoms };
|
|
271
|
+
let supportContext = { triage: triageResponse, freeTextDerivedSymptoms, freeTextUnmatchedSymptoms };
|
|
270
272
|
let supportPromise;
|
|
271
273
|
let existingClinicalMirrorId = null;
|
|
272
274
|
const startSupport = () => {
|
|
@@ -527,6 +529,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
527
529
|
freeText: freeTextLabelled.join(' · ') || null,
|
|
528
530
|
additionalSymptoms,
|
|
529
531
|
freeTextDerivedSymptoms,
|
|
532
|
+
freeTextUnmatchedSymptoms,
|
|
530
533
|
nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
|
|
531
534
|
stage,
|
|
532
535
|
catalog,
|
|
@@ -539,6 +542,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
539
542
|
...reported.map((symptom) => symptom.term),
|
|
540
543
|
...additionalSymptoms.map((symptom) => symptom.term).filter(Boolean),
|
|
541
544
|
...freeTextDerivedSymptoms,
|
|
545
|
+
...freeTextUnmatchedSymptoms,
|
|
542
546
|
];
|
|
543
547
|
const reportedKeys = symptomKeySet(catalog, reportedTerms);
|
|
544
548
|
const floorConfig = await getRedFlagMinRoutes()
|
|
@@ -581,12 +585,14 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
581
585
|
gate,
|
|
582
586
|
deniedKeys,
|
|
583
587
|
reportedKeys,
|
|
588
|
+
uncodedKeys: new Set(freeTextUnmatchedSymptoms.map(keyOf).filter(Boolean)),
|
|
584
589
|
deniedAeKeys: deniedAeKeySet(catalog, gate),
|
|
585
590
|
reported: reportedSymptoms(catalog, reportedTerms),
|
|
586
591
|
};
|
|
587
592
|
const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
|
|
588
593
|
const symptomSignals = buildSymptomSignals({
|
|
589
|
-
catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms,
|
|
594
|
+
catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms, freeTextUnmatchedSymptoms,
|
|
595
|
+
priorResolutions, openCases,
|
|
590
596
|
});
|
|
591
597
|
const planOutcome = await runPlan({
|
|
592
598
|
provider, presetId: planPresetId, casoBase: casoBaseFor('plan', symptomSignals),
|
|
@@ -1022,18 +1028,19 @@ async function awaitFreeTextClassifier(triageRecordId, code, { hasFreeText }) {
|
|
|
1022
1028
|
|
|
1023
1029
|
function classifierSettled(read) {
|
|
1024
1030
|
if (read.pending !== false) return false;
|
|
1025
|
-
|
|
1031
|
+
// The classifier writes the complaints it could not code too, so an all-NO MATCH run is done, not empty.
|
|
1032
|
+
if (read.derived > 0 || read.unmatched.length > 0) return true;
|
|
1026
1033
|
const createdMs = Date.parse(read.createdAt || '');
|
|
1027
1034
|
return !Number.isFinite(createdMs) || Date.now() - createdMs >= CLASSIFIER_WINDOW_MS;
|
|
1028
1035
|
}
|
|
1029
1036
|
|
|
1030
1037
|
async function readFreeTextDerivedSymptoms(triageRecordId, code) {
|
|
1031
|
-
if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null, derived: 0, createdAt: null };
|
|
1038
|
+
if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], unmatched: [], pending: null, derived: 0, createdAt: null };
|
|
1032
1039
|
const rows = await getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `RECORD_ID()='${triageRecordId}'`);
|
|
1033
1040
|
const row = Array.isArray(rows) ? rows[0] : rows;
|
|
1034
1041
|
if (!row) {
|
|
1035
1042
|
logger.warn('[triageRecommendation] triage row unreadable; no classifier anchors', { code, triageRecordId });
|
|
1036
|
-
return { terms: [], pending: null, derived: 0, createdAt: null };
|
|
1043
|
+
return { terms: [], unmatched: [], pending: null, derived: 0, createdAt: null };
|
|
1037
1044
|
}
|
|
1038
1045
|
const owner = Array.isArray(row.whatsapp_id) ? row.whatsapp_id[0] : row.whatsapp_id;
|
|
1039
1046
|
if (owner && owner !== code) {
|
|
@@ -1043,8 +1050,9 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
|
|
|
1043
1050
|
// The classifier writes its rows ~96 s after the triage: an unfinished one is not an empty one.
|
|
1044
1051
|
const pending = row.symptoms_processed !== true;
|
|
1045
1052
|
const createdAt = row.Created || null;
|
|
1053
|
+
const unmatched = unmatchedMentionsOf(row.freetext_unmatched);
|
|
1046
1054
|
const ids = (Array.isArray(row.symptoms) ? row.symptoms : []).filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
|
|
1047
|
-
if (!ids.length) return { terms: [], pending, derived: 0, createdAt };
|
|
1055
|
+
if (!ids.length) return { terms: [], unmatched, pending, derived: 0, createdAt };
|
|
1048
1056
|
const formula = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
|
|
1049
1057
|
const symptoms = await getRecordByFilter(Symptoms_ID, 'symptoms', formula, null, FREE_TEXT_SYMPTOM_FIELDS, true);
|
|
1050
1058
|
const derived = (Array.isArray(symptoms) ? symptoms : []).filter((symptom) => symptom.freetext_derived === true);
|
|
@@ -1053,7 +1061,15 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
|
|
|
1053
1061
|
.map((symptom) => (Array.isArray(symptom.corresponding_CTCAE) ? symptom.corresponding_CTCAE[0] : symptom.corresponding_CTCAE))
|
|
1054
1062
|
.map((term) => String(term ?? '').trim())
|
|
1055
1063
|
.filter(Boolean);
|
|
1056
|
-
return { terms, pending, derived: derived.length, createdAt };
|
|
1064
|
+
return { terms, unmatched, pending, derived: derived.length, createdAt };
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// One complaint per line, `mención — "cita literal"`: only the mention names the symptom.
|
|
1068
|
+
function unmatchedMentionsOf(value) {
|
|
1069
|
+
const mentions = String(value || '').split('\n')
|
|
1070
|
+
.map((line) => line.split(' — ')[0].trim())
|
|
1071
|
+
.filter(Boolean);
|
|
1072
|
+
return [...new Set(mentions)];
|
|
1057
1073
|
}
|
|
1058
1074
|
|
|
1059
1075
|
async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
@@ -32,6 +32,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
|
|
|
32
32
|
const { BatchingManager } = require('../core/BatchingManager');
|
|
33
33
|
const { ProcessingPipeline } = require('../core/ProcessingPipeline');
|
|
34
34
|
const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
|
|
35
|
+
const { deliveryOutcome } = require('../clinical/AssistantProcessor');
|
|
35
36
|
const { UNASSIGNED, alertOpsForClaimedMessage, coverIfUnassigned, coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
|
|
36
37
|
const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
|
|
37
38
|
const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
|
|
@@ -52,6 +53,8 @@ const { invokeInteractiveRoute } = require('./interactiveRouteService');
|
|
|
52
53
|
|
|
53
54
|
const { PhiProcessor } = require('./PhiProcessor');
|
|
54
55
|
|
|
56
|
+
const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
|
|
57
|
+
|
|
55
58
|
const unbatchedRoutes = {
|
|
56
59
|
__proto__: null,
|
|
57
60
|
flow: 'handleFlow',
|
|
@@ -695,7 +698,7 @@ class NexusMessaging {
|
|
|
695
698
|
* PROCESSING PIPELINE
|
|
696
699
|
*/
|
|
697
700
|
|
|
698
|
-
async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true } = {}) {
|
|
701
|
+
async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSent = null } = {}) {
|
|
699
702
|
let capturedResult = null;
|
|
700
703
|
const discardResponseFn = async (result) => {
|
|
701
704
|
await this.assistantProcessor.discardResponse(chatId, result);
|
|
@@ -719,6 +722,7 @@ class NexusMessaging {
|
|
|
719
722
|
return;
|
|
720
723
|
}
|
|
721
724
|
await this.assistantProcessor.sendResponse(chatId, result);
|
|
725
|
+
if (onSent && result?.delivery && deliveryOutcome(result.delivery) !== 'known_not_sent') await onSent(result);
|
|
722
726
|
};
|
|
723
727
|
|
|
724
728
|
const admission = mode === 'queue'
|
|
@@ -823,32 +827,67 @@ class NexusMessaging {
|
|
|
823
827
|
messageData,
|
|
824
828
|
this._saveMessageFn,
|
|
825
829
|
async ({ body, _id }) => {
|
|
830
|
+
let answered = [];
|
|
826
831
|
const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
|
|
827
|
-
async (preProcessResult, shouldContinue, runId) =>
|
|
828
|
-
code,
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
toolChoice: 'none',
|
|
833
|
-
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
834
|
-
runId,
|
|
835
|
-
shouldContinue,
|
|
836
|
-
signal: this.batchingManager.getAbortSignal(runId),
|
|
832
|
+
async (preProcessResult, shouldContinue, runId) => {
|
|
833
|
+
const batch = await this._pendingInstructionBatch(code, _id, body);
|
|
834
|
+
if (!batch.length) {
|
|
835
|
+
logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
|
|
836
|
+
return null;
|
|
837
837
|
}
|
|
838
|
-
|
|
838
|
+
const result = await this.assistantProcessor.process({
|
|
839
|
+
code,
|
|
840
|
+
runOptions: {
|
|
841
|
+
prePromptResult: preProcessResult,
|
|
842
|
+
additionalInstructions: batch.map(m => m.body).join('\n\n'),
|
|
843
|
+
toolChoice: 'none',
|
|
844
|
+
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
845
|
+
runId,
|
|
846
|
+
shouldContinue,
|
|
847
|
+
signal: this.batchingManager.getAbortSignal(runId),
|
|
848
|
+
}
|
|
849
|
+
});
|
|
850
|
+
answered = batch.map(m => m._id).filter(Boolean);
|
|
851
|
+
return result;
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
onSent: async () => {
|
|
855
|
+
if (!answered.length) return;
|
|
856
|
+
try {
|
|
857
|
+
await updateMessage({ _id: { $in: answered } }, { $set: { processed: true } });
|
|
858
|
+
} catch (err) {
|
|
859
|
+
logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
},
|
|
839
863
|
);
|
|
840
|
-
if (_id) {
|
|
841
|
-
try {
|
|
842
|
-
await updateMessage({ _id }, { $set: { processed: true } });
|
|
843
|
-
} catch (err) {
|
|
844
|
-
logger.error('[processInstruction] Could not mark instruction processed', { error: err.message, code });
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
864
|
return runResult;
|
|
848
865
|
},
|
|
849
866
|
);
|
|
850
867
|
}
|
|
851
868
|
|
|
869
|
+
async _pendingInstructionBatch(code, ownId, ownBody) {
|
|
870
|
+
if (!ownId) return [{ _id: null, body: ownBody }];
|
|
871
|
+
try {
|
|
872
|
+
const rows = await getMessages(
|
|
873
|
+
{
|
|
874
|
+
numero: code,
|
|
875
|
+
origin: 'instruction',
|
|
876
|
+
message_id: /^instruction_/,
|
|
877
|
+
$or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(Date.now() - PENDING_INSTRUCTION_WINDOW_MS) } }],
|
|
878
|
+
},
|
|
879
|
+
{ sort: { _id: 1 }, select: '_id body processed' },
|
|
880
|
+
);
|
|
881
|
+
const own = rows.find(m => String(m._id) === String(ownId));
|
|
882
|
+
if (own?.processed) return [];
|
|
883
|
+
const batch = rows.filter(m => m === own || !m.processed).map(m => (m === own ? { _id: ownId, body: ownBody } : m));
|
|
884
|
+
return own ? batch : [...batch, { _id: ownId, body: ownBody }];
|
|
885
|
+
} catch (err) {
|
|
886
|
+
logger.error('[processInstruction] Could not read pending instructions', { error: err.message, code });
|
|
887
|
+
return [{ _id: ownId, body: ownBody }];
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
852
891
|
/*
|
|
853
892
|
* A turn nobody asked for: no inbound message, and no obligation to produce an outbound.
|
|
854
893
|
* Unlike processInstruction this keeps the full clinical toolset and lets the agent end in a hold,
|