@peopl-health/nexus 6.0.0-dev.15840 → 6.0.0-dev.16228
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/flags/clinicalContextFlags.js +5 -0
- package/lib/clinical/flags/flagSnapshot.js +4 -1
- package/lib/clinical/helpers/chemoContextHelper.js +2 -1
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +4 -1
- package/lib/clinical/models/triageRecommendationEventModel.js +1 -0
- package/lib/clinical/providers/BaseLLMProvider.js +19 -10
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +6 -1
- package/lib/clinical/services/checkInDueService.js +2 -0
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/triageRecommendationService.js +13 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +11 -5
- package/lib/clinical/tools/schedulePatientReminderTool.js +1 -1
- package/lib/controllers/messageController.js +4 -0
- package/lib/controllers/patientController.js +21 -13
- package/lib/eval/EvalProvider.js +1 -1
- package/lib/helpers/airtableArchiveHelper.js +7 -1
- package/lib/helpers/patientMessageHelper.js +3 -1
- package/lib/index.d.ts +2 -2
- package/lib/models/airtableArchiveModel.js +1 -0
- package/lib/services/airtableArchivePlanService.js +12 -5
- package/lib/services/airtableArchiveReadService.js +31 -6
- package/lib/services/airtableArchiveService.js +4 -4
- package/lib/services/escalationReviewService.js +45 -4
- package/lib/services/recommendationCarouselService.js +58 -20
- package/lib/services/teamAlertService.js +13 -7
- package/lib/services/triageHistoryService.js +25 -4
- package/lib/utils/dateUtils.js +6 -0
- package/lib/utils/jsonUtils.js +21 -0
- package/package.json +1 -1
|
@@ -14,6 +14,10 @@ function chemoContextLive() {
|
|
|
14
14
|
return flagOn('CHEMO_CONTEXT_LIVE');
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
function rtContextBlockLive() {
|
|
18
|
+
return flagOn('RT_CONTEXT_BLOCK');
|
|
19
|
+
}
|
|
20
|
+
|
|
17
21
|
function profileFromMongo() {
|
|
18
22
|
return flagOn('PATIENT_PROFILE_FROM_MONGO');
|
|
19
23
|
}
|
|
@@ -38,4 +42,5 @@ module.exports = {
|
|
|
38
42
|
profileFromMongo,
|
|
39
43
|
profileSyncOn,
|
|
40
44
|
regimenCloserLive,
|
|
45
|
+
rtContextBlockLive,
|
|
41
46
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
const { isCohortEnabled } = require('../config/cohortConfig');
|
|
2
2
|
const { isBridgeEnabled } = require('./bridgeConfig');
|
|
3
|
-
const {
|
|
3
|
+
const {
|
|
4
|
+
contextReadLive, contextMirrorLive, contextVerifierLive, rtContextBlockLive,
|
|
5
|
+
} = require('./clinicalContextFlags');
|
|
4
6
|
const { isComposerEnabled, isAgentSelfRenderEnabled } = require('./composerFlags');
|
|
5
7
|
const { isContingencyCancelOnReplyLive, isArmOnOpenCeilingLive, isContingencyRuleBlockLive } = require('./contingencyFlags');
|
|
6
8
|
const { escalationAssessmentLive, escalationUpdateModeLive } = require('./escalationFlags');
|
|
@@ -20,6 +22,7 @@ const FLAG_READERS = {
|
|
|
20
22
|
contextRead: contextReadLive,
|
|
21
23
|
contextMirror: contextMirrorLive,
|
|
22
24
|
contextVerifier: contextVerifierLive,
|
|
25
|
+
rtContextBlock: rtContextBlockLive,
|
|
23
26
|
composer: isComposerEnabled,
|
|
24
27
|
agentSelfRender: isAgentSelfRenderEnabled,
|
|
25
28
|
contingencyCancelOnReply: isContingencyCancelOnReplyLive,
|
|
@@ -8,6 +8,7 @@ const ACTIVE_DAYS = 35;
|
|
|
8
8
|
const DEFAULT_CYTOTOXIC_WINDOW_DAYS = 42;
|
|
9
9
|
const HEADER = 'Quimioterapia (registro de la unidad de quimioterapia; úsalo para contextualizar y priorizar síntomas, nunca para bajar la urgencia; no comuniques dosis ni ajustes de tratamiento; si el paciente dice algo distinto, créele: si es otra fecha de cita, que el paciente la confirme con el área de tratamiento, sin avisar al equipo; si es un dato clínico, o una sesión suspendida o cambiada por un motivo clínico, avisa al equipo)';
|
|
10
10
|
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
11
|
+
const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
11
12
|
const NO_ALLERGY = /^(ninguna?s?|no|negadas?|desconocidas?|(niega|no refiere|sin|no tiene|no presenta) alergias?( conocidas| a medicamentos)?)$/;
|
|
12
13
|
const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
|
|
13
14
|
|
|
@@ -131,7 +132,7 @@ function chemoLines(context, today) {
|
|
|
131
132
|
}
|
|
132
133
|
if (context.proximaSesion && context.proximaSesion.fecha >= today) {
|
|
133
134
|
lines.push(context.proximaSesion.tipo === 'agendada'
|
|
134
|
-
? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
|
|
135
|
+
? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)}${CLOCK.test(context.proximaSesion.hora) ? ` a las ${context.proximaSesion.hora}` : ''} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
|
|
135
136
|
: `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
|
|
136
137
|
}
|
|
137
138
|
const support = context.proximaVisitaSoporte;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const TRIAGE_RESULT_MARKER = 'acaba de completar el triaje de síntomas PRO-CTCAE';
|
|
2
|
+
|
|
3
|
+
const SCALE_HEADER = 'Escala CTCAE de este síntoma. El grado de arriba es una APROXIMACIÓN calculada a partir del PRO-CTCAE, no una lectura de estas cláusulas: contrasta lo que el paciente describe contra ellas antes de darlo por confirmado. Si la evidencia sostiene otra cláusula, ese es el grado.';
|
|
4
|
+
const DEFINITION_PREFIX = 'Definición del síntoma - ';
|
|
5
|
+
const SCALE_CLAUSE_RX = /^\s+G\d:/;
|
|
6
|
+
|
|
7
|
+
const isTriageResultMessage = (body) => typeof body === 'string' && body.includes(TRIAGE_RESULT_MARKER);
|
|
8
|
+
|
|
9
|
+
const isReferenceLine = (line, next) => line === SCALE_HEADER
|
|
10
|
+
|| (line.startsWith(DEFINITION_PREFIX) && next === SCALE_HEADER);
|
|
11
|
+
|
|
12
|
+
// Drops only fixed CTCAE reference text (the scale header leaves with its clauses); every patient-specific line stays verbatim.
|
|
13
|
+
function compactTriageResult(body) {
|
|
14
|
+
if (!isTriageResultMessage(body)) return body;
|
|
15
|
+
const lines = body.split('\n');
|
|
16
|
+
const kept = [];
|
|
17
|
+
let inScale = false;
|
|
18
|
+
let dropped = false;
|
|
19
|
+
lines.forEach((line, i) => {
|
|
20
|
+
if (inScale && SCALE_CLAUSE_RX.test(line)) { dropped = true; return; }
|
|
21
|
+
inScale = line === SCALE_HEADER;
|
|
22
|
+
if (isReferenceLine(line, lines[i + 1])) { dropped = true; return; }
|
|
23
|
+
const isBlank = !line.trim();
|
|
24
|
+
if (isBlank && kept.length && !kept[kept.length - 1].trim()) return;
|
|
25
|
+
kept.push(line);
|
|
26
|
+
});
|
|
27
|
+
return dropped ? kept.join('\n') : body;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = { TRIAGE_RESULT_MARKER, compactTriageResult, isTriageResultMessage };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const { pairTriageSymptoms } = require('../helpers/triageSymptomsHelper');
|
|
2
|
+
const { compactTriageResult, isTriageResultMessage } = require('../helpers/triageResultMessageHelper');
|
|
2
3
|
const { parseChemoContext, renderChemoContext, withChemoContext } = require('../helpers/chemoContextHelper');
|
|
3
4
|
const { handlePendingFunctionCalls: handlePendingFunctionCallsUtil } = require('../providers/OpenAIResponsesProviderTools');
|
|
4
5
|
|
|
@@ -99,13 +100,15 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
99
100
|
|
|
100
101
|
const skipTools = new Set(getTurnScopedToolNames());
|
|
101
102
|
const replayArgs = getReplayArgsByTool();
|
|
103
|
+
const latestTriage = config.compactOlderTriage ? ordered.findLastIndex(msg => isTriageResultMessage(msg.body)) : -1;
|
|
102
104
|
|
|
103
105
|
const context = ordered.flatMap((msg, index) => {
|
|
104
106
|
const toolItems = getMessageTools(msg, { skipTools, replayArgs });
|
|
105
107
|
if (index >= turnStart) return toolItems;
|
|
106
108
|
const role = this._resolveContextRole(msg);
|
|
107
109
|
const prefix = this._speakerPrefix(msg, role);
|
|
108
|
-
const
|
|
110
|
+
const shown = index < latestTriage ? { ...msg, body: compactTriageResult(msg.body) } : msg;
|
|
111
|
+
const contentItems = formatMessage(shown)
|
|
109
112
|
.filter(Boolean)
|
|
110
113
|
.map(content => ({
|
|
111
114
|
role,
|
|
@@ -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 },
|
|
@@ -10,6 +10,7 @@ const { composePrompt, resolveTools } = require('../services/promptComposerServi
|
|
|
10
10
|
const { resolveSkillCatalog } = require('../services/skillService');
|
|
11
11
|
const { RISK_HEADLINE_MARKER } = require('../services/riskHeadlineService');
|
|
12
12
|
const { resolveClinicalContext } = require('../services/clinicalContextReadService');
|
|
13
|
+
const { radiotherapyBlockFor, withRadiotherapyBlock } = require('../services/radiotherapyContextService');
|
|
13
14
|
const { isContingencyRuleBlockLive } = require('../flags/contingencyFlags');
|
|
14
15
|
const { snapshotClinicalFlags } = require('../flags/flagSnapshot');
|
|
15
16
|
const { TURN_KIND } = require('../context/turnContext');
|
|
@@ -21,7 +22,7 @@ const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
|
|
|
21
22
|
const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
|
|
22
23
|
const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
|
|
23
24
|
const { isJsonBlob } = require('../../utils/formatUtils');
|
|
24
|
-
const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
|
|
25
|
+
const { isPlainObject, safeParse, decodeLiteralUnicodeEscapes } = require('../../utils/jsonUtils');
|
|
25
26
|
const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
|
|
26
27
|
|
|
27
28
|
const EXCHANGE_LINE_LENGTH = 400;
|
|
@@ -321,7 +322,7 @@ class BaseLLMProvider {
|
|
|
321
322
|
...this._buildFollowUpPolicyMessage(toolIds),
|
|
322
323
|
...this._buildFollowUpMessage(promptVariables),
|
|
323
324
|
...this._buildFollowUpCheckMessage(toolIds),
|
|
324
|
-
...this._buildContingencyCheckMessage(promptVariables, toolIds),
|
|
325
|
+
...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
|
|
325
326
|
...this._buildClockMessage(promptVariables, interpolatedVariables),
|
|
326
327
|
...messages,
|
|
327
328
|
...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
|
|
@@ -404,6 +405,7 @@ class BaseLLMProvider {
|
|
|
404
405
|
const self = checkIn.reminderId ? `${checkIn.reminderId}${checkIn.dueAt ? `, programado para ${local(checkIn.dueAt)}` : ''}` : null;
|
|
405
406
|
const pending = lines([
|
|
406
407
|
['este check-in', self],
|
|
408
|
+
['tipo', checkIn.type === 'contingencia' ? 'red de contingencia' : 'seguimiento que programaste: esta pregunta todavía no le ha llegado'],
|
|
407
409
|
['lo que querías preguntarle', checkIn.question],
|
|
408
410
|
['por qué quedó abierto', checkIn.concern],
|
|
409
411
|
['qué dato esperabas', checkIn.awaiting],
|
|
@@ -435,9 +437,9 @@ class BaseLLMProvider {
|
|
|
435
437
|
'- 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
438
|
'- 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
439
|
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
|
|
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
|
|
440
|
-
'
|
|
440
|
+
? '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.'
|
|
441
|
+
: '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.',
|
|
442
|
+
'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
443
|
'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
444
|
'Breve, sin listas de señales de alarma y sin mencionar recordatorios, planes ni seguimientos programados.',
|
|
443
445
|
);
|
|
@@ -493,12 +495,16 @@ class BaseLLMProvider {
|
|
|
493
495
|
// Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
|
|
494
496
|
// because an unresolved net later asks the patient a question they had already answered.
|
|
495
497
|
// Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
|
|
496
|
-
|
|
498
|
+
// A net is marked fired before its own check-in turn runs, so during that turn its check-in has not reached the patient yet.
|
|
499
|
+
_buildContingencyCheckMessage(promptVariables, toolIds = [], outreachBrief = null) {
|
|
497
500
|
if (!(toolIds || []).includes('setContingencyPlan')) return [];
|
|
498
501
|
const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
|
|
499
502
|
if (!active.length) return [];
|
|
503
|
+
const dueNet = outreachBrief?.checkIn?.planId || null;
|
|
500
504
|
const waiting = active.map(({ carePlan: plan = {} } = {}) => {
|
|
501
|
-
|
|
505
|
+
let fired = '';
|
|
506
|
+
if (dueNet && plan.planId === dueNet) fired = ' Su check-in es el de este turno: todavía no le ha llegado.';
|
|
507
|
+
else if (plan.status === 'fired_reminder') fired = ' Su check-in ya se envió.';
|
|
502
508
|
return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
|
|
503
509
|
});
|
|
504
510
|
return [{
|
|
@@ -620,6 +626,7 @@ class BaseLLMProvider {
|
|
|
620
626
|
...config,
|
|
621
627
|
threadId: conversationId,
|
|
622
628
|
assistantId,
|
|
629
|
+
compactOlderTriage: true,
|
|
623
630
|
}
|
|
624
631
|
});
|
|
625
632
|
|
|
@@ -632,6 +639,7 @@ class BaseLLMProvider {
|
|
|
632
639
|
|
|
633
640
|
logger.info('[executeRun] Context built', { conversationId, messageCount: context?.length || 0 });
|
|
634
641
|
|
|
642
|
+
const radiotherapyBlock = radiotherapyBlockFor(thread.code, Date.now());
|
|
635
643
|
const override = config.clinicalData;
|
|
636
644
|
const hasOverride = override && typeof override === 'object' && Object.keys(override).length > 0;
|
|
637
645
|
const clinicalData = hasOverride ? override : await this.conversationManager.getClinicalData(thread.code);
|
|
@@ -655,8 +663,9 @@ class BaseLLMProvider {
|
|
|
655
663
|
patientId: thread.code,
|
|
656
664
|
legacyBlock: promptVariables.clinical_context,
|
|
657
665
|
});
|
|
658
|
-
|
|
659
|
-
|
|
666
|
+
const rtBlock = await radiotherapyBlock;
|
|
667
|
+
promptVariables.clinical_context = withRadiotherapyBlock(withHospitalization(block, thread?.hospitalizedAt), rtBlock);
|
|
668
|
+
assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source, rtBlockPresent: Boolean(rtBlock) });
|
|
660
669
|
|
|
661
670
|
const result = await this.runConversation({
|
|
662
671
|
threadId: conversationId,
|
|
@@ -858,7 +867,7 @@ class BaseLLMProvider {
|
|
|
858
867
|
_bridgeFrom(calls) {
|
|
859
868
|
const pick = (name, field) => {
|
|
860
869
|
const value = calls.find(call => call.name === name)?.input?.[field];
|
|
861
|
-
return typeof value === 'string' && value.trim() ? value : null;
|
|
870
|
+
return typeof value === 'string' && value.trim() ? decodeLiteralUnicodeEscapes(value) : null;
|
|
862
871
|
};
|
|
863
872
|
const extraction = calls.find(call => call.name === EXTRACTION_TOOL)?.input;
|
|
864
873
|
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
|
|
|
@@ -101,6 +101,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
|
|
|
101
101
|
checkIn = {
|
|
102
102
|
type,
|
|
103
103
|
reminderId,
|
|
104
|
+
planId,
|
|
104
105
|
dueAt: null,
|
|
105
106
|
question: netQuestion,
|
|
106
107
|
concern: net.carePlan.concern,
|
|
@@ -118,6 +119,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
|
|
|
118
119
|
checkIn = {
|
|
119
120
|
type,
|
|
120
121
|
reminderId,
|
|
122
|
+
planId: null,
|
|
121
123
|
dueAt: plan.fireAt || null,
|
|
122
124
|
question: plan.message || question,
|
|
123
125
|
concern: plan.windowReasoning,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const { rtContextBlockLive } = require('../flags/clinicalContextFlags');
|
|
2
|
+
const { Estado_General_ID, Symptoms_ID } = require('../../config/airtableConfig');
|
|
3
|
+
const { escapeFormulaValue, fieldEquals } = require('../../helpers/airtableFormulaHelper');
|
|
4
|
+
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
|
+
const { logger } = require('../../utils/logger');
|
|
6
|
+
const { withTimeout } = require('../../utils/timeoutUtils');
|
|
7
|
+
const { latestCourse, renderRadiotherapyBlock } = require('./radiotherapyPhaseService');
|
|
8
|
+
|
|
9
|
+
const ZONE_FIELDS = ['rt_zona', 'rt_zona_confirmada'];
|
|
10
|
+
const FACT_FIELDS = ['value_text', 'normalized_value', 'report_date'];
|
|
11
|
+
const READ_TIMEOUT_MS = 2000;
|
|
12
|
+
|
|
13
|
+
const courseFacts = (code) => getRecordByFilter(
|
|
14
|
+
Estado_General_ID,
|
|
15
|
+
'facts',
|
|
16
|
+
`AND({variable}='radiotherapy_summary', ARRAYJOIN({whatsapp_id (from patient)})='${escapeFormulaValue(code)}')`,
|
|
17
|
+
null,
|
|
18
|
+
FACT_FIELDS,
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
async function radiotherapyBlockFor(code, now) {
|
|
22
|
+
try {
|
|
23
|
+
if (!rtContextBlockLive() || !code) return '';
|
|
24
|
+
const [zones, facts] = await withTimeout(Promise.all([
|
|
25
|
+
getRecordByFilter(Symptoms_ID, 'estado_general', fieldEquals('whatsapp_id', code), 'Grid view', ZONE_FIELDS),
|
|
26
|
+
courseFacts(code),
|
|
27
|
+
]), READ_TIMEOUT_MS, 'radiotherapy context read');
|
|
28
|
+
const row = zones?.[0] || {};
|
|
29
|
+
return renderRadiotherapyBlock({
|
|
30
|
+
zona: row.rt_zona || null, confirmada: Boolean(row.rt_zona_confirmada), curso: latestCourse(facts), now,
|
|
31
|
+
});
|
|
32
|
+
} catch (error) {
|
|
33
|
+
logger.warn('[radiotherapyContext] block left out', { error: error?.message });
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const withRadiotherapyBlock = (block, rtBlock) => (rtBlock ? [block, rtBlock].filter(Boolean).join('\n\n') : block);
|
|
39
|
+
|
|
40
|
+
module.exports = { radiotherapyBlockFor, withRadiotherapyBlock };
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
const {
|
|
2
|
+
addDays, daysBetween, formatDmy, mexicoDay,
|
|
3
|
+
} = require('../../utils/dateUtils');
|
|
4
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
5
|
+
const { safeParse } = require('../../utils/jsonUtils');
|
|
6
|
+
|
|
7
|
+
const SKIN = 'enrojecimiento que se extiende fuera de la zona tratada, calor o pus';
|
|
8
|
+
const PELVIC_NEVER = Object.freeze(['no poder orinar', SKIN]);
|
|
9
|
+
const PELVIC_LATE = Object.freeze(['dolor nuevo de cadera, ingle o sacro al caminar']);
|
|
10
|
+
|
|
11
|
+
// Recomendaciones aprobadas el 22-oct-2026 (propuesta para firma de radioterapia); pendiente el visto bueno del servicio
|
|
12
|
+
const RT_DRAFT = Object.freeze({
|
|
13
|
+
ACUTE_DAYS: 90,
|
|
14
|
+
STALE_DAYS: 10,
|
|
15
|
+
SRS_EARLY_DAYS: 7,
|
|
16
|
+
SRS_MAX_FRACTIONS: 5,
|
|
17
|
+
GENERAL_EXPECTED: Object.freeze(['fatiga', 'falta de apetito', 'dolor o molestia en la zona tratada']),
|
|
18
|
+
NEVER_EXPECTED: Object.freeze(['fiebre de 38.0 °C o más', 'síntoma neurológico nuevo (debilidad, convulsión, confusión, dolor de cabeza con vómito)']),
|
|
19
|
+
SEVERITY: 'Esperable describe la causa probable, no la gravedad: no poder beber o tragar, más de 7 evacuaciones al día sobre lo habitual, pérdida de 5 % del peso o piel abierta e infectada no son esperables en ninguna fase.',
|
|
20
|
+
SEQUELAE: 'Secuelas persistentes ya conocidas (boca seca, fibrosis, piel más oscura, linfedema ya conocido) pueden seguir presentes.',
|
|
21
|
+
IMMUNOTHERAPY: 'Si recibe inmunoterapia al mismo tiempo, tos, diarrea o erupción en la piel nuevas no se atribuyen a la radioterapia.',
|
|
22
|
+
PELVIC_BLEEDING: 'Sangrado rectal o en la orina: puede ser un efecto tardío conocido, pero la radioterapia no lo explica sin evaluación.',
|
|
23
|
+
ZONES: Object.freeze({
|
|
24
|
+
'pelvis femenina': {
|
|
25
|
+
expected: ['diarrea o evacuaciones blandas', 'cólicos o dolor abdominal', 'ardor o urgencia al orinar', 'flujo vaginal', 'irritación de la piel en pliegues de la zona'],
|
|
26
|
+
never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
|
|
27
|
+
},
|
|
28
|
+
'pelvis masculina': {
|
|
29
|
+
expected: ['diarrea o evacuaciones blandas', 'ardor o urgencia al orinar', 'chorro débil', 'urgencia para evacuar', 'irritación de la piel en pliegues de la zona'],
|
|
30
|
+
never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
|
|
31
|
+
},
|
|
32
|
+
pelvis: {
|
|
33
|
+
expected: ['diarrea o evacuaciones blandas', 'ardor o urgencia al orinar', 'urgencia para evacuar', 'irritación de la piel en pliegues de la zona'],
|
|
34
|
+
never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
|
|
35
|
+
},
|
|
36
|
+
mama: {
|
|
37
|
+
expected: ['reacción de la piel en la zona tratada (enrojecimiento, comezón, descamación)', 'oscurecimiento de la piel', 'hinchazón o sensibilidad de la mama'],
|
|
38
|
+
never: ['hinchazón súbita y dolorosa del brazo', 'si se irradiaron los ganglios: tos o falta de aire nuevas de 1 a 6 meses después del fin', SKIN],
|
|
39
|
+
},
|
|
40
|
+
'cabeza y cuello': {
|
|
41
|
+
expected: ['dolor al tragar', 'llagas en la boca', 'boca seca o saliva espesa y flema', 'cambios en el gusto', 'ronquera', 'reacción de la piel del cuello', 'pérdida leve de peso'],
|
|
42
|
+
never: ['sangrado por la boca, el cuello o la traqueostomía', 'ruido al respirar o falta de aire', 'no tolerar líquidos ni la alimentación por sonda',
|
|
43
|
+
'mareo al pararse u orina escasa (deshidratación)', SKIN],
|
|
44
|
+
},
|
|
45
|
+
torax: {
|
|
46
|
+
expected: ['dolor o ardor al tragar', 'acidez'],
|
|
47
|
+
activeOnly: ['tos leve'],
|
|
48
|
+
never: ['falta de aire en reposo', 'dolor en el pecho o tos con sangre', 'tos o falta de aire nuevas de 1 a 6 meses después del fin (hasta 12 meses con SBRT o inmunoterapia)'],
|
|
49
|
+
},
|
|
50
|
+
abdomen: { expected: ['náuseas', 'diarrea'], never: [] },
|
|
51
|
+
'cerebro holocraneal': {
|
|
52
|
+
expected: ['somnolencia', 'náuseas leves', 'caída del cabello'],
|
|
53
|
+
never: [],
|
|
54
|
+
lateEffects: 'Problemas de memoria o de concentración pueden ser un efecto tardío de la radioterapia al cerebro.',
|
|
55
|
+
},
|
|
56
|
+
radiocirugia: {
|
|
57
|
+
earlyExpected: ['dolor de cabeza leve y náuseas los primeros ~7 días'],
|
|
58
|
+
expected: [],
|
|
59
|
+
never: ['dolor de cabeza nuevo o que empeora después de los primeros ~7 días'],
|
|
60
|
+
},
|
|
61
|
+
'cerebro sin tecnica': { expected: [], never: [] },
|
|
62
|
+
'hueso u otra': {
|
|
63
|
+
expected: ['aumento pasajero del dolor en el sitio tratado los primeros días'],
|
|
64
|
+
never: ['debilidad en las piernas, pérdida de control de esfínteres o de sensibilidad (posible compresión medular)', 'fractura del hueso tratado', SKIN],
|
|
65
|
+
},
|
|
66
|
+
}),
|
|
67
|
+
ZONE_ALIASES: Object.freeze({
|
|
68
|
+
prostata: 'pelvis masculina',
|
|
69
|
+
recto: 'pelvis',
|
|
70
|
+
vejiga: 'pelvis',
|
|
71
|
+
cervix: 'pelvis femenina',
|
|
72
|
+
cervicouterino: 'pelvis femenina',
|
|
73
|
+
endometrio: 'pelvis femenina',
|
|
74
|
+
utero: 'pelvis femenina',
|
|
75
|
+
vulva: 'pelvis femenina',
|
|
76
|
+
vagina: 'pelvis femenina',
|
|
77
|
+
laringe: 'cabeza y cuello',
|
|
78
|
+
orofaringe: 'cabeza y cuello',
|
|
79
|
+
nasofaringe: 'cabeza y cuello',
|
|
80
|
+
'cavidad oral': 'cabeza y cuello',
|
|
81
|
+
esofago: 'torax',
|
|
82
|
+
pulmon: 'torax',
|
|
83
|
+
cerebro: 'cerebro holocraneal',
|
|
84
|
+
holocraneal: 'cerebro holocraneal',
|
|
85
|
+
}),
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const PHASE = Object.freeze({
|
|
89
|
+
PLANNED: 'planeada',
|
|
90
|
+
START_UNCONFIRMED: 'inicio_por_confirmar',
|
|
91
|
+
ACTIVE: 'en_curso',
|
|
92
|
+
RECENT: 'terminada',
|
|
93
|
+
HISTORY: 'antecedente',
|
|
94
|
+
UNCONFIRMED: 'por_confirmar',
|
|
95
|
+
UNKNOWN: 'sin_fechas',
|
|
96
|
+
});
|
|
97
|
+
const SERVICE_ORIGIN = 'servicio_radioterapia';
|
|
98
|
+
const WORKDAYS_PER_WEEK = 5;
|
|
99
|
+
const STATUS_ALIASES = Object.freeze({
|
|
100
|
+
completed: 'completed', completado: 'completed', terminada: 'completed',
|
|
101
|
+
active: 'active', ongoing: 'active', 'en curso': 'active',
|
|
102
|
+
planned: 'planned', planificado: 'planned', planeada: 'planned',
|
|
103
|
+
});
|
|
104
|
+
const SRS_TECHNIQUE = /radiocirug|\bsrs\b|\bsbrt\b|estereot/i;
|
|
105
|
+
const HEADER = 'Radioterapia';
|
|
106
|
+
const BRAIN_KIND = Object.freeze({
|
|
107
|
+
radiocirugia: ' (radiocirugía)',
|
|
108
|
+
'cerebro sin tecnica': ` (tipo de tratamiento no registrado; con ${RT_DRAFT.SRS_MAX_FRACTIONS} sesiones o menos puede ser radiocirugía u holocraneal)`,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const fold = (text) => foldAccents(text).trim().toLowerCase();
|
|
112
|
+
const isDay = (value) => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);
|
|
113
|
+
const isWorkday = (day) => ![0, 6].includes(new Date(`${day}T00:00:00Z`).getUTCDay());
|
|
114
|
+
|
|
115
|
+
function shiftWorkdays(day, count) {
|
|
116
|
+
const step = count < 0 ? -1 : 1;
|
|
117
|
+
let at = day;
|
|
118
|
+
for (let left = Math.abs(count); left > 0;) {
|
|
119
|
+
at = addDays(at, step);
|
|
120
|
+
if (isWorkday(at)) left -= 1;
|
|
121
|
+
}
|
|
122
|
+
return at;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function workdaysThrough(from, to) {
|
|
126
|
+
let count = 0;
|
|
127
|
+
for (let at = from; at <= to; at = addDays(at, 1)) if (isWorkday(at)) count += 1;
|
|
128
|
+
return count;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const normalizeStatus = (status) => STATUS_ALIASES[fold(status)] || null;
|
|
132
|
+
|
|
133
|
+
function courseFromEntry(entry) {
|
|
134
|
+
const sesiones = Number(entry.sessions_planned ?? entry.fractions_planned);
|
|
135
|
+
return {
|
|
136
|
+
inicio: isDay(entry.start_date) ? entry.start_date : null,
|
|
137
|
+
fin: isDay(entry.end_date) ? entry.end_date : null,
|
|
138
|
+
sesiones: Number.isInteger(sesiones) && sesiones > 0 ? sesiones : null,
|
|
139
|
+
estado: normalizeStatus(entry.status),
|
|
140
|
+
tecnica: typeof entry.technique === 'string' ? entry.technique : null,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function courseFromFact(fact) {
|
|
145
|
+
const normalized = safeParse(fact?.normalized_value) || {};
|
|
146
|
+
const entry = (Array.isArray(normalized.add) ? normalized.add : []).find((item) => item?.start_date || item?.end_date || item?.status);
|
|
147
|
+
return entry ? courseFromEntry(entry) : null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const originOf = (fact) => safeParse(fact?.normalized_value)?.origin || null;
|
|
151
|
+
|
|
152
|
+
// the unit's register wins over facts extracted from conversation; newest report first within each
|
|
153
|
+
function latestCourse(facts) {
|
|
154
|
+
const rows = (Array.isArray(facts) ? facts : []).filter(Boolean);
|
|
155
|
+
if (!rows.length) return null;
|
|
156
|
+
const newest = (a, b) => String(b.report_date ?? '').localeCompare(String(a.report_date ?? ''));
|
|
157
|
+
const service = rows.filter((fact) => originOf(fact) === SERVICE_ORIGIN).sort(newest);
|
|
158
|
+
return courseFromFact((service.length ? service : [...rows].sort(newest))[0]);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function zoneProfile(zona, curso) {
|
|
162
|
+
if (!zona) return null;
|
|
163
|
+
const key = fold(zona);
|
|
164
|
+
let canonical = RT_DRAFT.ZONES[key] ? key : RT_DRAFT.ZONE_ALIASES[key] || null;
|
|
165
|
+
if (canonical === 'cerebro holocraneal' && SRS_TECHNIQUE.test(curso?.tecnica || '')) canonical = 'radiocirugia';
|
|
166
|
+
else if (canonical === 'cerebro holocraneal' && curso?.sesiones && curso.sesiones <= RT_DRAFT.SRS_MAX_FRACTIONS) canonical = 'cerebro sin tecnica';
|
|
167
|
+
return canonical ? { key: canonical, ...RT_DRAFT.ZONES[canonical] } : { key: null, unrecognized: true };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function phaseOf(curso, today) {
|
|
171
|
+
const { sesiones, estado } = curso;
|
|
172
|
+
let { inicio } = curso;
|
|
173
|
+
const { fin } = curso;
|
|
174
|
+
if (!inicio && fin && sesiones) inicio = shiftWorkdays(fin, -(sesiones - 1));
|
|
175
|
+
if (inicio && today < inicio) return { phase: PHASE.PLANNED, inicio };
|
|
176
|
+
if (!inicio && !fin) return { phase: estado === 'planned' ? PHASE.PLANNED : PHASE.UNKNOWN };
|
|
177
|
+
if (estado === 'planned') return { phase: PHASE.START_UNCONFIRMED, inicio };
|
|
178
|
+
const finEstimado = !fin && inicio && sesiones ? shiftWorkdays(inicio, sesiones - 1) : null;
|
|
179
|
+
const end = fin || finEstimado;
|
|
180
|
+
if (!end) return { phase: PHASE.UNCONFIRMED, inicio, sinceStart: daysBetween(inicio, today) };
|
|
181
|
+
const estimated = Boolean(finEstimado);
|
|
182
|
+
const graceEnd = estimated && estado !== 'completed' ? addDays(end, RT_DRAFT.STALE_DAYS) : end;
|
|
183
|
+
if (today <= graceEnd) return { phase: PHASE.ACTIVE, inicio, end, estimated };
|
|
184
|
+
const days = daysBetween(end, today);
|
|
185
|
+
if (estimated && estado !== 'completed') return { phase: PHASE.UNCONFIRMED, end, days };
|
|
186
|
+
return { phase: days > RT_DRAFT.ACUTE_DAYS ? PHASE.HISTORY : PHASE.RECENT, end, days, estimated };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function phaseLine(state, sesiones) {
|
|
190
|
+
const estimated = state.estimated ? ' estimado (±1–2 semanas)' : '';
|
|
191
|
+
switch (state.phase) {
|
|
192
|
+
case PHASE.PLANNED:
|
|
193
|
+
return `Fase: planeada${state.inicio ? `, inicio previsto el ${formatDmy(state.inicio)}` : ''}. Aún no hay síntomas esperables por la radioterapia.`;
|
|
194
|
+
case PHASE.START_UNCONFIRMED:
|
|
195
|
+
return `Fase: inicio por confirmar: el inicio previsto (${formatDmy(state.inicio)}) ya pasó, pero no hay registro de que haya empezado. No se sabe si recibió radioterapia.`;
|
|
196
|
+
case PHASE.ACTIVE: {
|
|
197
|
+
const total = sesiones ? Math.ceil(sesiones / WORKDAYS_PER_WEEK) : null;
|
|
198
|
+
const elapsed = state.inicio ? Math.max(1, Math.ceil(workdaysThrough(state.inicio, state.today) / WORKDAYS_PER_WEEK)) : null;
|
|
199
|
+
const week = elapsed ? `, semana ~${total ? Math.min(elapsed, total) : elapsed}${total ? ` de ~${total}` : ''}` : '';
|
|
200
|
+
return `Fase: en curso${week}; fin${estimated} el ${formatDmy(state.end)}. ${week ? 'La sesión exacta no se conoce, solo la semana aproximada.' : 'No se conoce la semana del curso.'}`;
|
|
201
|
+
}
|
|
202
|
+
case PHASE.RECENT:
|
|
203
|
+
return `Fase: terminó hace ${state.days} días (fin${estimated} el ${formatDmy(state.end)}); ventana aguda hasta el ${formatDmy(addDays(state.end, RT_DRAFT.ACUTE_DAYS))} (fin + ${RT_DRAFT.ACUTE_DAYS} días). Ya no está en tratamiento de radioterapia.`;
|
|
204
|
+
case PHASE.HISTORY:
|
|
205
|
+
return `Fase: antecedente: terminó hace ${state.days} días (más de ${RT_DRAFT.ACUTE_DAYS}). ${RT_DRAFT.SEQUELAE} Un síntoma de la zona nuevo, que regresa o que empeora ya no se explica como efecto agudo: puede ser un efecto tardío o algo nuevo que el equipo no conoce.`;
|
|
206
|
+
case PHASE.UNCONFIRMED:
|
|
207
|
+
return state.end
|
|
208
|
+
? `Fase: estado por confirmar: el fin estimado (${formatDmy(state.end)}, ±1–2 semanas) pasó hace ${state.days} días sin registro de término. No se sabe si ya terminó.`
|
|
209
|
+
: `Fase: estado por confirmar: inició el ${formatDmy(state.inicio)}, sin fin ni número de sesiones registrados. No se sabe si sigue en curso ni cuándo terminó.`;
|
|
210
|
+
default:
|
|
211
|
+
return 'Fase: sin fechas del curso registradas.';
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function inAcuteWindow(state) {
|
|
216
|
+
if ([PHASE.ACTIVE, PHASE.RECENT].includes(state.phase)) return true;
|
|
217
|
+
if (state.phase !== PHASE.UNCONFIRMED) return false;
|
|
218
|
+
return state.end ? state.days <= RT_DRAFT.ACUTE_DAYS : state.sinceStart <= RT_DRAFT.ACUTE_DAYS;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const isSrsEarly = (state) => state.phase === PHASE.ACTIVE || (state.phase === PHASE.RECENT && state.days <= RT_DRAFT.SRS_EARLY_DAYS);
|
|
222
|
+
|
|
223
|
+
function courseLine(curso) {
|
|
224
|
+
const parts = [curso.tecnica, curso.sesiones && `${curso.sesiones} ${curso.sesiones === 1 ? 'sesión' : 'sesiones'}`,
|
|
225
|
+
curso.inicio && `inicio ${formatDmy(curso.inicio)}`, curso.fin && `fin ${formatDmy(curso.fin)}`].filter(Boolean);
|
|
226
|
+
return parts.length ? `Curso registrado: ${parts.join(', ')}.` : null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const UNKNOWN_ZONE = 'sin zona confirmada no se sabe qué síntomas explica la radioterapia.';
|
|
230
|
+
|
|
231
|
+
function zoneLine(zona, confirmada, profile) {
|
|
232
|
+
if (!zona) return `Zona tratada: no registrada; ${UNKNOWN_ZONE}`;
|
|
233
|
+
if (profile.unrecognized) return `Zona tratada: ${zona} (zona no reconocida); solo aplican los datos generales.`;
|
|
234
|
+
const kind = BRAIN_KIND[profile.key] || '';
|
|
235
|
+
return confirmada ? `Zona tratada: ${zona}${kind}.` : `Zona tratada: ${zona}${kind} (sin confirmar por el médico); ${UNKNOWN_ZONE}`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function expectedFor(profile, confirmada, state) {
|
|
239
|
+
const zone = confirmada && profile && !profile.unrecognized ? [
|
|
240
|
+
...(profile.expected || []),
|
|
241
|
+
...(state.phase === PHASE.ACTIVE ? profile.activeOnly || [] : []),
|
|
242
|
+
...(isSrsEarly(state) ? profile.earlyExpected || [] : []),
|
|
243
|
+
] : [];
|
|
244
|
+
return [...RT_DRAFT.GENERAL_EXPECTED, ...zone];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function renderRadiotherapyBlock({ zona = null, confirmada = false, curso = null, now = Date.now() } = {}) {
|
|
248
|
+
const zone = typeof zona === 'string' && zona.trim() ? zona.trim() : null;
|
|
249
|
+
if (!zone && !curso) return '';
|
|
250
|
+
const today = mexicoDay(new Date(now));
|
|
251
|
+
const profile = zoneProfile(zone, curso);
|
|
252
|
+
const state = { ...phaseOf(curso || {}, today), today };
|
|
253
|
+
const acute = inAcuteWindow(state);
|
|
254
|
+
const history = state.phase === PHASE.HISTORY;
|
|
255
|
+
const never = [...RT_DRAFT.NEVER_EXPECTED, ...(profile?.never || []), ...(history ? profile?.late || [] : [])];
|
|
256
|
+
const lines = [
|
|
257
|
+
zoneLine(zone, confirmada, profile || {}),
|
|
258
|
+
curso && courseLine(curso),
|
|
259
|
+
phaseLine(state, curso?.sesiones),
|
|
260
|
+
acute && `Esperables en esta fase: ${expectedFor(profile, confirmada, state).join(', ')}.`,
|
|
261
|
+
acute && RT_DRAFT.SEVERITY,
|
|
262
|
+
history && profile?.lateEffects,
|
|
263
|
+
`No se explican por la radioterapia: ${never.join('; ')}.`,
|
|
264
|
+
profile?.pelvic && RT_DRAFT.PELVIC_BLEEDING,
|
|
265
|
+
RT_DRAFT.IMMUNOTHERAPY,
|
|
266
|
+
].filter(Boolean);
|
|
267
|
+
return `${HEADER}:\n- ${lines.join('\n- ')}`;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
module.exports = {
|
|
271
|
+
latestCourse, renderRadiotherapyBlock,
|
|
272
|
+
};
|
|
@@ -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
|
});
|