@peopl-health/nexus 5.76.3 → 5.76.5

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.
@@ -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 { contextReadLive, contextMirrorLive, contextVerifierLive } = require('./clinicalContextFlags');
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 contentItems = formatMessage(msg)
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,
@@ -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');
@@ -621,6 +622,7 @@ class BaseLLMProvider {
621
622
  ...config,
622
623
  threadId: conversationId,
623
624
  assistantId,
625
+ compactOlderTriage: true,
624
626
  }
625
627
  });
626
628
 
@@ -633,6 +635,7 @@ class BaseLLMProvider {
633
635
 
634
636
  logger.info('[executeRun] Context built', { conversationId, messageCount: context?.length || 0 });
635
637
 
638
+ const radiotherapyBlock = radiotherapyBlockFor(thread.code, Date.now());
636
639
  const override = config.clinicalData;
637
640
  const hasOverride = override && typeof override === 'object' && Object.keys(override).length > 0;
638
641
  const clinicalData = hasOverride ? override : await this.conversationManager.getClinicalData(thread.code);
@@ -656,8 +659,9 @@ class BaseLLMProvider {
656
659
  patientId: thread.code,
657
660
  legacyBlock: promptVariables.clinical_context,
658
661
  });
659
- promptVariables.clinical_context = withHospitalization(block, thread?.hospitalizedAt);
660
- assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source });
662
+ const rtBlock = await radiotherapyBlock;
663
+ promptVariables.clinical_context = withRadiotherapyBlock(withHospitalization(block, thread?.hospitalizedAt), rtBlock);
664
+ assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source, rtBlockPresent: Boolean(rtBlock) });
661
665
 
662
666
  const result = await this.runConversation({
663
667
  threadId: conversationId,
@@ -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
+ };
@@ -106,7 +106,7 @@ class EvalProvider {
106
106
  async _buildContext(numero, beforeCheckpoint) {
107
107
  const messages = await this.memoryManager.buildContext({
108
108
  thread: { code: numero },
109
- config: { beforeCheckpoint, beforeOperator: '$lt' },
109
+ config: { beforeCheckpoint, beforeOperator: '$lt', compactOlderTriage: true },
110
110
  });
111
111
 
112
112
  const lastUserMsg = [...messages].reverse().find(m => m.role === 'user');
package/lib/index.d.ts CHANGED
@@ -565,7 +565,7 @@ declare module '@peopl-health/nexus' {
565
565
  ultimaAplicacion: { fecha: string; ciclo?: number; sesion?: number; total?: number } | null;
566
566
  esquema: Array<{ farmaco: string; via?: string; tiempo?: string }>;
567
567
  inicioEsquema: { fecha: string; anteriorAlRegistro: boolean } | null;
568
- proximaSesion: { fecha: string; tipo: string; confirmada?: boolean } | null;
568
+ proximaSesion: { fecha: string; tipo: string; confirmada?: boolean; hora?: string | null } | null;
569
569
  esquemaPrevio: { farmacos: string[]; hasta: string } | null;
570
570
  [key: string]: any;
571
571
  }
@@ -57,6 +57,10 @@ const mexicoDay = (value) => {
57
57
  // whole days from one YYYY-MM-DD day to another
58
58
  const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
59
59
 
60
+ const addDays = (day, days) => new Date(Date.parse(`${day}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
61
+
62
+ const formatDmy = (day) => `${day.slice(8, 10)}/${day.slice(5, 7)}/${day.slice(0, 4)}`;
63
+
60
64
  const mexicoIsoWeek = (value) => {
61
65
  if (value === null || value === undefined || value === '') return null;
62
66
  const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
@@ -101,6 +105,7 @@ const addWorkingMinutes = (start, minutes, { timeZone, days, startHour, endHour
101
105
  };
102
106
 
103
107
  module.exports = {
108
+ addDays,
104
109
  addWorkingMinutes,
105
110
  getCurrentMexicoDateTime,
106
111
  getMexicoDayLabels,
@@ -110,6 +115,7 @@ module.exports = {
110
115
  ageInYears,
111
116
  isoDay,
112
117
  daysBetween,
118
+ formatDmy,
113
119
  mexicoDay,
114
120
  mexicoClock,
115
121
  mexicoIsoWeek,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.76.3",
3
+ "version": "5.76.5",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",