@peopl-health/nexus 5.58.0-dev.10248 → 5.58.0-dev.10495

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.
@@ -32,6 +32,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
32
32
  gateAttempts: { type: Number, default: null },
33
33
  gateLatencyMs: { type: Number, default: null },
34
34
  planLatencyMs: { type: Number, default: null },
35
+ planMaxOutputTokens: { type: Number, default: null },
35
36
  totalLatencyMs: { type: Number, default: null },
36
37
  triageStored: { type: Boolean, default: null },
37
38
  unmappedAnswerCount: { type: Number, default: null },
@@ -0,0 +1,473 @@
1
+ const FORMULARY_VERSION = '2026-09-28';
2
+
3
+ const MEDICAL_REVIEW = 'valoración médica';
4
+
5
+ const JUSTIFICATION_KINDS = Object.freeze(['prior_failure', 'contraindication', 'context']);
6
+
7
+ function deepFreeze(value) {
8
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
9
+ Object.freeze(value);
10
+ for (const nested of Object.values(value)) deepFreeze(nested);
11
+ }
12
+ return value;
13
+ }
14
+
15
+ const TREATMENT_FORMULARY = deepFreeze([
16
+ {
17
+ key: 'nausea_vomito',
18
+ label: 'Náusea y vómito',
19
+ drugs: [
20
+ {
21
+ drug: 'Ondansetrón', brand: 'AMAL', strength: '8 mg', position: '1L', tableLabel: '1L', class: 'antiemetico_5ht3',
22
+ instructions: '1 tableta cada 24 horas por 5 días',
23
+ contextNote: 'Náusea/vómito relacionado con QT; solo o dentro de esquema antiemético según riesgo',
24
+ },
25
+ {
26
+ drug: 'Olanzapina', strength: '5 mg', position: '1L', tableLabel: '1L en escenarios seleccionados', class: 'antipsicotico',
27
+ onlyWhen: ['cinv_alto_riesgo', 'nausea_persistente'],
28
+ contextNote: 'Profilaxis de esquemas altamente emetógenos y náusea persistente/breakthrough',
29
+ },
30
+ {
31
+ drug: 'Metoclopramida', strength: '10 mg', position: 'ALT', tableLabel: 'ALT / rescate', class: 'procinetico',
32
+ onlyWhen: ['rescate', 'gastroparesia'],
33
+ contextNote: 'Solo como rescate o si hay plenitud/gastroparesia; no como profilaxis principal de CINV moderada-alta',
34
+ },
35
+ {
36
+ drug: 'Cinarizina/dimenhidrinato', brand: 'ARLEVERT', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA CINV', class: 'antivertiginoso',
37
+ exceptWhen: ['componente_vestibular'],
38
+ contextNote: 'Solo si predomina componente vestibular/vértigo',
39
+ },
40
+ ],
41
+ },
42
+ {
43
+ key: 'reflujo',
44
+ label: 'Reflujo / dispepsia / gases',
45
+ drugs: [
46
+ {
47
+ drug: 'Esomeprazol', strength: '40 mg', position: '1L', tableLabel: '1L', class: 'ibp',
48
+ instructions: '1 cápsula cada 24 horas por 5 días',
49
+ contextNote: 'ERGE/dispepsia ácido-relacionada; escoger un solo IBP',
50
+ },
51
+ { drug: 'Pantoprazol', strength: '20 mg', position: '1L', tableLabel: '1L', class: 'ibp', contextNote: 'Escoger un solo IBP' },
52
+ { drug: 'Omeprazol', strength: '20 mg', position: '1L', tableLabel: '1L', class: 'ibp', contextNote: 'Escoger un solo IBP' },
53
+ {
54
+ drug: 'Famotidina', strength: '40 mg', position: 'ALT', tableLabel: 'ALT / 1L síntomas leves', class: 'antih2',
55
+ instructions: '1 tableta cada 24 horas por 5 días',
56
+ contextNote: 'ERGE intermitente/nocturna o si no se requiere IBP; alternativa si ya toma esomeprazol',
57
+ },
58
+ { drug: 'Magaldrato/dimeticona', brand: 'RIOPAN', strength: null, position: '1L', tableLabel: '1L PRN', class: 'antiacido', contextNote: 'Alivio inmediato de pirosis/dispepsia ocasional' },
59
+ {
60
+ drug: 'Simeticona/metoclopramida', brand: 'ESPAVEN MD', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'procinetico',
61
+ contextNote: 'Distensión + síntomas dispépticos/náusea; no convertir metoclopramida en tratamiento crónico rutinario',
62
+ },
63
+ { drug: 'Subsalicilato de bismuto', brand: 'PEPTO-BISMOL', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'bismuto', contextNote: 'Dispepsia, diarrea; no primera línea para ERGE' },
64
+ {
65
+ drug: 'Ácido hialurónico/condroitín sulfato', brand: 'ESOXX ONE', strength: null, position: 'ALT', tableLabel: 'Coadyuvante', class: 'barrera_esofagica',
66
+ contextNote: 'Barrera de mucosa en reflujo; no reemplaza IBP cuando éste está indicado',
67
+ },
68
+ ],
69
+ },
70
+ {
71
+ key: 'diarrea',
72
+ label: 'Diarrea',
73
+ algorithmModifiers: [
74
+ 'fiebre', 'neutropenia', 'sangre_en_heces', 'hipotension', 'deshidratacion', 'dolor_intenso', 'sospecha_colitis_inmunomediada',
75
+ ],
76
+ drugs: [
77
+ {
78
+ drug: 'Loperamida', strength: '2 mg', position: '1L', tableLabel: '1L', class: 'antidiarreico_opioide',
79
+ instructions: '2 tabletas (4 mg) al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
80
+ ruleOutFirst: ['causa infecciosa', 'causa obstructiva', 'intolerancia'],
81
+ contextNote: 'Diarrea no complicada asociada al tratamiento oncológico',
82
+ },
83
+ {
84
+ drug: 'Racecadotrilo', strength: '100 mg', position: 'ALT', tableLabel: 'ALT', class: 'antisecretor',
85
+ contextNote: 'Opción sintomática; alternativa en diarrea G1 por inmunoterapia',
86
+ },
87
+ ],
88
+ },
89
+ {
90
+ key: 'dolor_abdominal_colico',
91
+ label: 'Dolor abdominal tipo cólico',
92
+ drugs: [
93
+ {
94
+ drug: 'Butilhioscina/metamizol', brand: 'BUSCAPINA COMPUESTA', strength: '10/250 mg', position: 'ALT', tableLabel: 'Coadyuvante', class: 'antiespasmodico',
95
+ instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
96
+ contextNote: 'Coadyuvante para cólico, no tratamiento de la diarrea',
97
+ },
98
+ ],
99
+ },
100
+ {
101
+ key: 'estrenimiento',
102
+ label: 'Estreñimiento',
103
+ requiresWhen: [{ condition: 'uso_opioides', drug: 'Senósidos', note: 'Con opioides: senósido ± PEG desde el inicio' }],
104
+ drugs: [
105
+ { drug: 'Polietilenglicol 3350', brand: 'MIRALAX / NULYTELY', strength: null, position: '1L', tableLabel: '1L preferida', class: 'laxante_osmotico_peg' },
106
+ {
107
+ drug: 'Senósidos', brand: 'SENOKOT', strength: null, position: '1L', tableLabel: '1L, especialmente estreñimiento por opioides', class: 'laxante_estimulante',
108
+ instructions: '2 tabletas cada noche por 5 días',
109
+ },
110
+ { drug: 'Bisacodilo', strength: null, position: '1L', tableLabel: '1L / ALT, estimulante', class: 'laxante_estimulante' },
111
+ {
112
+ drug: 'Lactulosa', brand: 'LACTULAX', strength: null, position: '1L', tableLabel: '1L / ALT osmótica', class: 'laxante_osmotico',
113
+ instructions: '10 ml cada 8 horas hasta lograr evacuación, después suspender',
114
+ },
115
+ {
116
+ drug: 'Leche de magnesia', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'laxante_osmotico',
117
+ avoidWhen: ['insuficiencia_renal'],
118
+ contextNote: 'Evitar/cautela en insuficiencia renal',
119
+ },
120
+ ],
121
+ },
122
+ {
123
+ key: 'mucositis',
124
+ label: 'Mucositis',
125
+ drugs: [
126
+ {
127
+ drug: 'Colutorios alcalinos', strength: '½ L de agua con 1 cucharadita de sal y 2 cucharaditas de bicarbonato', position: '1L', tableLabel: '1L soporte básico', class: 'enjuague',
128
+ instructions: 'enjuagues y gárgaras de 1 minuto cada 6 horas por 5 días',
129
+ isPharmacological: false,
130
+ },
131
+ {
132
+ drug: 'Bencidamina', brand: 'VANTAL', strength: null, position: '1L', tableLabel: '1L en escenarios específicos', class: 'enjuague_analgesico',
133
+ onlyWhen: ['radioterapia_cabeza_cuello'],
134
+ contextNote: 'Especialmente mucositis por RT de cabeza/cuello',
135
+ },
136
+ { drug: 'Gel barrera oral', brand: 'GELBUX', strength: null, position: 'ALT', tableLabel: 'Coadyuvante', class: 'barrera_oral', contextNote: 'Barrera para úlceras/mucositis' },
137
+ { drug: 'Fórmula de Filadelfia', strength: null, position: 'ALT', tableLabel: 'ALT sintomática', class: 'enjuague_compuesto', contextNote: 'No estándar universal de primera línea' },
138
+ {
139
+ drug: 'Dexketoprofeno', brand: 'VELIAN', strength: '25 mg/10 ml en sobres', position: 'ALT', tableLabel: 'ALT analgésica', class: 'aine',
140
+ instructions: '1 sobre cada 8 horas, 30 minutos antes de los alimentos, y tragar, por 7 días',
141
+ contextNote: `Analgésico, no tratamiento específico de mucositis; si persiste, ${MEDICAL_REVIEW}`,
142
+ },
143
+ ],
144
+ },
145
+ {
146
+ key: 'candidiasis_oral',
147
+ label: 'Candidiasis oral',
148
+ drugs: [
149
+ { drug: 'Nistatina', strength: null, position: '1L', tableLabel: '1L/ALT en candidiasis oral leve', class: 'antifungico_topico', onlyWhen: ['candidiasis_leve'] },
150
+ { drug: 'Fluconazol', strength: '100 mg', position: '1L', tableLabel: '1L en candidiasis moderada-severa', class: 'antifungico_azol', onlyWhen: ['candidiasis_moderada_severa'] },
151
+ ],
152
+ },
153
+ {
154
+ key: 'dolor',
155
+ label: 'Dolor',
156
+ drugs: [
157
+ {
158
+ drug: 'Paracetamol', brand: 'TEMPRA / TYLENOL', strength: '500 mg', position: '1L', tableLabel: '1L dolor leve', class: 'analgesico_no_opioide',
159
+ instructions: 'VO cada 8 horas por razón necesaria, máximo 3 días',
160
+ },
161
+ {
162
+ drug: 'Ibuprofeno', strength: '400 mg', position: '1L', tableLabel: '1L/ALT dolor inflamatorio leve', class: 'aine',
163
+ instructions: 'VO cada 12 horas, máximo 3 días',
164
+ avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
165
+ },
166
+ { drug: 'Naproxeno', strength: null, position: '1L', tableLabel: '1L/ALT', class: 'aine', avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'] },
167
+ {
168
+ drug: 'Celecoxib', brand: 'CELEBREX', strength: '200 mg', position: 'ALT', tableLabel: 'ALT / escalamiento de AINE', class: 'aine',
169
+ instructions: 'VO cada 24 horas, máximo 3 días',
170
+ avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
171
+ },
172
+ { drug: 'Dexketoprofeno', strength: null, position: 'ALT', tableLabel: 'ALT corto plazo', class: 'aine', avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'] },
173
+ {
174
+ drug: 'Ketorolaco', strength: null, position: '2L+', tableLabel: 'Rescate corto plazo, no mantenimiento', class: 'aine',
175
+ avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
176
+ },
177
+ { drug: 'Tramadol', strength: '50 mg', position: '2L+', tableLabel: '2.º escalón, dolor leve-moderado no controlado', class: 'opioide_debil' },
178
+ { drug: 'Tramadol/paracetamol', strength: null, position: '2L+', tableLabel: '2.º escalón', class: 'opioide_debil' },
179
+ {
180
+ drug: 'Morfina oral', strength: null, position: '1L', tableLabel: '1L opioide para dolor oncológico moderado-severo', class: 'opioide_fuerte',
181
+ onlyWhen: ['dolor_moderado_severo'],
182
+ avoidWhen: ['insuficiencia_renal_avanzada'],
183
+ },
184
+ {
185
+ drug: 'Oxicodona', strength: null, position: 'ALT', tableLabel: 'ALT a morfina', class: 'opioide_fuerte',
186
+ onlyWhen: ['dolor_moderado_severo'],
187
+ avoidWhen: ['insuficiencia_renal_avanzada'],
188
+ },
189
+ {
190
+ drug: 'Oxicodona LP', brand: 'OXYCONTIN', strength: null, position: '2L+', tableLabel: 'Mantenimiento, no titulación inicial en opioid-naïve', class: 'opioide_fuerte',
191
+ avoidWhen: ['opioid_naive', 'insuficiencia_renal_avanzada'],
192
+ },
193
+ {
194
+ drug: 'Buprenorfina transdérmica', strength: '5–20 µg/h', position: 'ALT', tableLabel: 'ALT para dolor crónico estable', class: 'opioide_fuerte',
195
+ contextNote: 'Preferir si hay insuficiencia renal avanzada',
196
+ },
197
+ {
198
+ drug: 'Buprenorfina transdérmica', strength: '35–70 µg/h', position: 'ALT', tableLabel: 'ALT opioide para dolor crónico moderado-severo estable', class: 'opioide_fuerte',
199
+ contextNote: 'Preferir si hay insuficiencia renal avanzada',
200
+ },
201
+ ],
202
+ },
203
+ {
204
+ key: 'neuropatia',
205
+ label: 'Neuropatía inducida por quimioterapia',
206
+ alwaysEscalate: MEDICAL_REVIEW,
207
+ recognition: 'ardor, sensación de adormecimiento o piquetes; sigue el trayecto de un nervio, o aparece en manos y pies al mismo tiempo',
208
+ contextNote: 'Si afecta función durante tratamiento neurotóxico, considerar reducción, retraso o suspensión del fármaco causante',
209
+ drugs: [
210
+ { drug: 'Duloxetina', strength: '30 mg', position: '1L', tableLabel: '1L', class: 'irsn' },
211
+ { drug: 'Pregabalina', strength: '75 mg', position: 'ALT', tableLabel: 'ALT', class: 'gabapentinoide' },
212
+ { drug: 'Gabapentina', strength: '300 mg', position: 'ALT', tableLabel: 'ALT', class: 'gabapentinoide' },
213
+ { drug: 'Núcleo CM Forte', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA para CIPN', class: 'suplemento_nucleotidos' },
214
+ { drug: 'Tiaminal B12', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA, salvo deficiencia', class: 'vitamina_b', exceptWhen: ['deficiencia_documentada'] },
215
+ { drug: 'Tiaminal 50', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA, salvo deficiencia', class: 'vitamina_b', exceptWhen: ['deficiencia_documentada'] },
216
+ { drug: 'Ácido fólico', strength: '5 mg', position: 'NO_RUTINA', tableLabel: 'NO RUTINA, salvo deficiencia/indicación específica', class: 'folato', exceptWhen: ['deficiencia_documentada'] },
217
+ ],
218
+ },
219
+ {
220
+ key: 'rash',
221
+ label: 'Rash / dermatitis por tratamiento',
222
+ drugs: [
223
+ { drug: 'Doxiciclina', strength: '100 mg', position: '1L', tableLabel: '1L rash EGFR moderado o profilaxis', class: 'tetraciclina', onlyWhen: ['rash_egfr'] },
224
+ { drug: 'Minociclina', strength: '100 mg', position: '1L', tableLabel: '1L alternativa', class: 'tetraciclina', onlyWhen: ['rash_egfr'] },
225
+ { drug: 'Clindamicina tópica', strength: '1%', position: 'ALT', tableLabel: 'ALT, lesiones localizadas', class: 'antibiotico_topico' },
226
+ { drug: 'Hidrocortisona tópica', brand: 'LOCOID', strength: null, position: '1L', tableLabel: '1L en dermatitis/rash inflamatorio leve', class: 'corticoide_topico' },
227
+ ],
228
+ },
229
+ {
230
+ key: 'sindrome_mano_pie',
231
+ label: 'Xerosis / síndrome mano-pie',
232
+ drugs: [
233
+ {
234
+ drug: 'Urea', brand: 'NUTRAPLUS', strength: '10%', position: '1L', tableLabel: '1L, especialmente HFS/hiperqueratosis', class: 'queratolitico',
235
+ instructions: 'capa fina cada 12 horas de forma continua',
236
+ },
237
+ {
238
+ drug: 'Ceramidas', brand: 'CERAVE', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente',
239
+ instructions: '2 a 3 veces al día de forma continua', isPharmacological: false,
240
+ },
241
+ { drug: 'Emoliente', brand: 'EUCERIN', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
242
+ { drug: 'Vaselina/petrolato', strength: null, position: '1L', tableLabel: '1L barrera', class: 'barrera_cutanea', isPharmacological: false },
243
+ { drug: 'Emoliente', brand: 'LUBRIDERM', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
244
+ { drug: 'Emoliente', brand: 'JERGENS', strength: null, position: 'ALT', tableLabel: 'ALT cosmética/emoliente', class: 'emoliente', isPharmacological: false },
245
+ ],
246
+ },
247
+ {
248
+ key: 'tos',
249
+ label: 'Tos',
250
+ requiresRuledOut: ['infeccion', 'neumonitis', 'progresion_pulmonar', 'tep', 'derrame'],
251
+ drugs: [
252
+ { drug: 'Dextrometorfano', strength: null, position: '1L', tableLabel: '1L tos seca sintomática', class: 'antitusivo' },
253
+ { drug: 'Ambroxol', strength: null, position: 'ALT', tableLabel: 'ALT si hay secreciones', class: 'mucolitico', onlyWhen: ['secreciones'] },
254
+ { drug: 'Bromhexina', strength: null, position: 'ALT', tableLabel: 'ALT si hay secreciones', class: 'mucolitico', onlyWhen: ['secreciones'] },
255
+ { drug: 'Hedera helix', strength: null, position: 'ALT', tableLabel: 'ALT, menor evidencia', class: 'fitoterapico' },
256
+ {
257
+ drug: 'Bromhexina/codeína', brand: 'KODEL', strength: 'bromhexina 160 mg + codeína 200 mg por cada 100 mL', position: '2L+', tableLabel: '2L / rescate, tos intensa seleccionada', class: 'antitusivo',
258
+ contextNote: 'La concentración es por cada 100 mL, no por dosis',
259
+ },
260
+ ],
261
+ },
262
+ {
263
+ key: 'rinitis_alergia',
264
+ label: 'Rinitis / alergia',
265
+ drugs: [
266
+ {
267
+ drug: 'Cetirizina', brand: 'REACTINE', strength: '10 mg', position: '1L', tableLabel: '1L antihistamínico', class: 'antihistaminico',
268
+ instructions: '1 tableta cada 24 horas por 7 días',
269
+ },
270
+ { drug: 'Loratadina', strength: '10 mg', position: '1L', tableLabel: '1L', class: 'antihistaminico' },
271
+ { drug: 'Fexofenadina', strength: '180 mg', position: '1L', tableLabel: '1L', class: 'antihistaminico' },
272
+ { drug: 'Hidroxicina', strength: '25 mg', position: '2L+', tableLabel: '2L, por sedación/efecto anticolinérgico', class: 'antihistaminico' },
273
+ { drug: 'Montelukast/loratadina', strength: null, position: 'ALT', tableLabel: 'ALT, más útil si asma/componente leucotrieno', class: 'antihistaminico' },
274
+ {
275
+ drug: 'Loratadina/betametasona', strength: null, position: 'NO_RUTINA', tableLabel: 'No rutina como 1L; corticoide sistémico aumenta riesgos', class: 'antihistaminico',
276
+ },
277
+ ],
278
+ },
279
+ {
280
+ key: 'dermatitis_radioterapia',
281
+ label: 'Dermatitis por radioterapia',
282
+ drugs: [
283
+ { drug: 'Mometasona', strength: '0.1%', position: '1L', tableLabel: 'Corticoide de potencia media favorecido (MASCC 2026) en pacientes seleccionados', class: 'corticoide_topico' },
284
+ { drug: 'Desonida', brand: 'DESOWEN', strength: '0.05%', position: 'ALT', tableLabel: 'Corticoide tópico en dermatitis temprana', class: 'corticoide_topico' },
285
+ { drug: 'Xondrid', strength: null, position: 'NO_RUTINA', tableLabel: 'No estándar de primera línea sin confirmar formulación y evidencia', class: 'barrera_cutanea' },
286
+ ],
287
+ },
288
+ {
289
+ key: 'hta_tki',
290
+ label: 'HTA por VEGF/TKI',
291
+ excluded: [{ drugs: ['Diltiazem', 'Verapamilo'], reason: 'Evitar con TKI por interacciones' }],
292
+ drugs: [
293
+ { drug: 'Losartán', strength: '50 mg', position: '1L', tableLabel: '1L', class: 'ara2' },
294
+ { drug: 'Telmisartán', strength: '40 mg', position: '1L', tableLabel: '1L', class: 'ara2' },
295
+ { drug: 'Amlodipino', strength: '5 mg', position: '1L', tableLabel: '1L/añadido, si función VI normal', class: 'calcioantagonista_dhp' },
296
+ {
297
+ drug: 'Amlodipino/valsartán/HCTZ', strength: null, position: '2L+', tableLabel: '2L/escalamiento, HTA que requiere ≥2–3 fármacos', class: 'combinacion_antihipertensiva',
298
+ },
299
+ ],
300
+ },
301
+ {
302
+ key: 'caquexia',
303
+ label: 'Caquexia / anorexia',
304
+ drugs: [
305
+ { drug: 'Olanzapina', strength: '2.5 mg', position: '1L', tableLabel: '1L farmacológica', class: 'antipsicotico' },
306
+ { drug: 'Megestrol', strength: null, position: 'ALT', tableLabel: 'ALT / 2L', class: 'progestageno', contextNote: 'Riesgo de trombosis, edema y supresión adrenal' },
307
+ { drug: 'Dexametasona', strength: '4 mg', position: 'ALT', tableLabel: 'ALT corto plazo, particularmente contexto paliativo', class: 'corticoide_sistemico' },
308
+ {
309
+ drug: 'Metoclopramida', strength: null, position: 'ALT', tableLabel: 'Sólo si saciedad precoz/gastroparesia/náusea', class: 'procinetico',
310
+ onlyWhen: ['saciedad_precoz', 'gastroparesia', 'nausea'],
311
+ },
312
+ ],
313
+ },
314
+ {
315
+ key: 'insomnio',
316
+ label: 'Insomnio',
317
+ contextNote: 'En insomnio crónico la primera intervención es CBT-I',
318
+ drugs: [
319
+ {
320
+ drug: 'Melatonina', brand: 'MELATOL', strength: '3 mg', position: 'ALT', tableLabel: 'Puede probarse; sin evidencia fuerte en insomnio crónico', class: 'melatonina',
321
+ instructions: '1 tableta cada 24 horas por la noche por 14 días',
322
+ },
323
+ { drug: 'Zolpidem', strength: '10 mg', position: 'ALT', tableLabel: 'ALT farmacológica de corto plazo, no primera intervención global', class: 'hipnotico' },
324
+ ],
325
+ },
326
+ {
327
+ key: 'salud_vaginal',
328
+ label: 'Salud vaginal',
329
+ drugs: [
330
+ { drug: 'Lubricante base agua', strength: null, position: '1L', tableLabel: '1L, especialmente para actividad sexual', class: 'lubricante', isPharmacological: false },
331
+ { drug: 'Ácido hialurónico vaginal', brand: 'HIALOFEMME', strength: null, position: '1L', tableLabel: '1L hidratante vaginal no hormonal', class: 'hidratante_vaginal' },
332
+ { drug: 'Hidratante vaginal', brand: 'ISDIN WOMAN', strength: null, position: '1L', tableLabel: '1L no hormonal', class: 'hidratante_vaginal' },
333
+ {
334
+ drug: 'Estriol vaginal', brand: 'OVESTIN', strength: null, position: '2L+', tableLabel: '2L, si persiste atrofia/sequedad tras hidratantes', class: 'estrogeno_vaginal',
335
+ contextNote: 'Individualizar especialmente en cáncer hormonosensible',
336
+ },
337
+ { drug: 'Vagitrol-V', strength: null, position: 'NO_RUTINA', tableLabel: 'No empírico rutinario', class: 'antiinfeccioso_vaginal', exceptWhen: ['diagnostico_infeccioso'] },
338
+ { drug: 'Fluconazol/tinidazol', brand: 'AFUMIX', strength: null, position: 'NO_RUTINA', tableLabel: 'No empírico rutinario', class: 'antiinfeccioso_vaginal', exceptWhen: ['diagnostico_infeccioso'] },
339
+ ],
340
+ },
341
+ {
342
+ key: 'soporte_oseo',
343
+ label: 'Soporte óseo',
344
+ contextNote: 'Primera línea solo si cumple criterios de osteoporosis/riesgo de fractura; el esquema de ácido zoledrónico para osteoporosis no es el de metástasis óseas',
345
+ drugs: [
346
+ { drug: 'Denosumab', strength: '60 mg SC', position: '1L', tableLabel: '1L posible para osteoporosis', class: 'antirresortivo', onlyWhen: ['osteoporosis_o_riesgo_fractura'] },
347
+ { drug: 'Ácido zoledrónico', strength: null, position: '1L', tableLabel: '1L posible para osteoporosis', class: 'antirresortivo', onlyWhen: ['osteoporosis_o_riesgo_fractura'] },
348
+ { drug: 'Colecalciferol', strength: null, position: 'ALT', tableLabel: 'Soporte basal si ingesta/niveles lo requieren', class: 'vitamina_d', contextNote: 'Corregir déficit según 25-OH-D' },
349
+ { drug: 'Calcio + vitamina D', brand: 'CALTRATE 600 + D', strength: null, position: 'ALT', tableLabel: 'Soporte basal', class: 'calcio' },
350
+ ],
351
+ },
352
+ {
353
+ key: 'espasticidad_hipo',
354
+ label: 'Espasticidad / hipo persistente',
355
+ drugs: [
356
+ {
357
+ drug: 'Baclofeno', strength: '10 mg', position: '1L', tableLabel: '1L/ALT para espasticidad; hipo persistente/refractario', class: 'relajante_muscular',
358
+ onlyWhen: ['espasticidad', 'hipo_persistente'],
359
+ },
360
+ ],
361
+ },
362
+ ]);
363
+
364
+ const byKey = new Map(TREATMENT_FORMULARY.map((entry) => [entry.key, entry]));
365
+
366
+ const normalize = (value) => String(value ?? '').trim().toLowerCase();
367
+
368
+ const asSet = (values) => new Set((Array.isArray(values) ? values : []).map(normalize));
369
+
370
+ function formularyFor(symptomKey) {
371
+ return byKey.get(String(symptomKey ?? '').trim()) ?? null;
372
+ }
373
+
374
+ const compact = (value) => normalize(value).replace(/\s+/g, '');
375
+
376
+ function findDrug(entry, item) {
377
+ const drug = normalize(item?.drug);
378
+ const brand = normalize(item?.brand);
379
+ const strength = compact(item?.strength);
380
+ const candidates = entry.drugs.filter((candidate) => normalize(candidate.drug) === drug
381
+ && (!strength || !candidate.strength || compact(candidate.strength) === strength));
382
+ if (candidates.length <= 1) return candidates[0] ?? null;
383
+ return candidates.find((candidate) => (brand && normalize(candidate.brand) === brand) || (strength && compact(candidate.strength) === strength)) ?? null;
384
+ }
385
+
386
+ function moleculesOf(drug) {
387
+ return drug.drug.split('/').map((part) => normalize(part).split(' ')[0]).filter(Boolean);
388
+ }
389
+
390
+ function hasAny(set, keys = []) {
391
+ return keys.some((key) => set.has(normalize(key)));
392
+ }
393
+
394
+ function validateProposal(proposal, context = {}) {
395
+ const issues = [];
396
+ const entry = formularyFor(proposal?.symptom);
397
+ if (!entry) return { valid: false, issues: [`síntoma sin formulario: ${proposal?.symptom ?? '(vacío)'}`] };
398
+
399
+ const items = Array.isArray(proposal?.items) ? proposal.items : [];
400
+ const modifiers = asSet(context.modifiers);
401
+ const conditions = asSet(context.conditions);
402
+ const ruledOut = asSet(context.ruledOut);
403
+
404
+ const activeModifiers = (entry.algorithmModifiers ?? []).filter((key) => modifiers.has(key));
405
+ const pendingRuleOut = (entry.requiresRuledOut ?? []).filter((key) => !ruledOut.has(key));
406
+
407
+ if (activeModifiers.length && items.length) {
408
+ issues.push(`no proponer tratamiento sintomático con ${activeModifiers.join(', ')}: priorizar valoración`);
409
+ }
410
+ if (pendingRuleOut.length && items.length) {
411
+ issues.push(`no proponer tratamiento sintomático sin descartar ${pendingRuleOut.join(', ')}`);
412
+ }
413
+
414
+ const classes = new Map();
415
+ const molecules = new Map();
416
+ for (const item of items) {
417
+ const excluded = (entry.excluded ?? []).find((rule) => rule.drugs.some((name) => normalize(name) === normalize(item?.drug)));
418
+ if (excluded) {
419
+ issues.push(`${item.drug}: ${excluded.reason}`);
420
+ continue;
421
+ }
422
+
423
+ const drug = findDrug(entry, item);
424
+ if (!drug) {
425
+ issues.push(`${[item?.drug ?? '(sin fármaco)', item?.strength].filter(Boolean).join(' ')} no está en la tabla para ${entry.label}`);
426
+ continue;
427
+ }
428
+
429
+ for (const molecule of moleculesOf(drug)) {
430
+ if (molecules.has(molecule) && molecules.get(molecule) !== drug.drug) {
431
+ issues.push(`${molecule} aparece dos veces: ${molecules.get(molecule)} y ${drug.drug}`);
432
+ }
433
+ molecules.set(molecule, drug.drug);
434
+ }
435
+
436
+ if (classes.has(drug.class)) {
437
+ issues.push(`un solo fármaco por clase (${drug.class}): ${classes.get(drug.class)} y ${drug.drug}`);
438
+ } else {
439
+ classes.set(drug.class, drug.drug);
440
+ }
441
+
442
+ if (drug.position === 'NO_RUTINA' && !hasAny(conditions, drug.exceptWhen)) {
443
+ issues.push(`${drug.drug} es NO RUTINA y no se propone como tratamiento inicial`);
444
+ }
445
+ if (drug.onlyWhen && !hasAny(conditions, drug.onlyWhen)) {
446
+ issues.push(`${drug.drug} solo aplica con ${drug.onlyWhen.join(' / ')}`);
447
+ }
448
+ const avoided = (drug.avoidWhen ?? []).filter((key) => conditions.has(key));
449
+ if (avoided.length) {
450
+ issues.push(`${drug.drug} está excluido por ${avoided.join(', ')}`);
451
+ }
452
+
453
+ const justification = item?.justification;
454
+ const justified = JUSTIFICATION_KINDS.includes(justification?.kind) && String(justification?.text ?? '').trim().length > 0;
455
+ if ((drug.position === 'ALT' || drug.position === '2L+') && !justified) {
456
+ issues.push(`${drug.drug} es ${drug.tableLabel}: explicar por qué no se usa la 1L (fallo previo, contraindicación o contexto)`);
457
+ }
458
+ }
459
+
460
+ for (const rule of entry.requiresWhen ?? []) {
461
+ if (!conditions.has(normalize(rule.condition)) || !items.length) continue;
462
+ if (!items.some((item) => normalize(item?.drug) === normalize(rule.drug))) issues.push(rule.note);
463
+ }
464
+
465
+ return { valid: issues.length === 0, issues, activeModifiers, pendingRuleOut, alwaysEscalate: entry.alwaysEscalate ?? null };
466
+ }
467
+
468
+ module.exports = {
469
+ FORMULARY_VERSION,
470
+ TREATMENT_FORMULARY,
471
+ formularyFor,
472
+ validateProposal,
473
+ };
@@ -331,7 +331,7 @@ class AnthropicProvider extends BaseLLMProvider {
331
331
  return { response: this._normalizeResponse(finalResponse), toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
332
332
  }
333
333
 
334
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
334
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
335
335
  let modelConfig = {};
336
336
  let resolvedInstructions = instructions;
337
337
  if (promptId || presetId) {
@@ -344,7 +344,7 @@ class AnthropicProvider extends BaseLLMProvider {
344
344
 
345
345
  const apiConfig = {
346
346
  model: model || (modelConfig.model && modelConfig.model.replace(/^anthropic\//, '')) || this.defaults.structuredModel,
347
- max_tokens: modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
347
+ max_tokens: maxOutputTokens || modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
348
348
  };
349
349
  if (system) apiConfig.system = system;
350
350
 
@@ -195,7 +195,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
195
195
  return { response: finalResponse, toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
196
196
  }
197
197
 
198
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
198
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
199
199
  let modelConfig = null;
200
200
  let resolvedInstructions = instructions;
201
201
  if (promptId || presetId) {
@@ -205,7 +205,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
205
205
  }
206
206
 
207
207
  const apiConfig = {
208
- ...this._mapModelConfig(modelConfig || {}),
208
+ ...this._mapModelConfig({ ...(modelConfig || {}), ...(maxOutputTokens ? { max_output_tokens: maxOutputTokens } : {}) }),
209
209
  instructions: resolvedInstructions || '',
210
210
  };
211
211
  if (model) apiConfig.model = model;
@@ -1,6 +1,6 @@
1
1
  const { getEscalationDraft } = require('../config/subAgentsConfig');
2
2
 
3
- const { PROTOCOL_VERSION, SYMPTOM_RELIEF_PROTOCOL } = require('../protocols/symptomReliefProtocol');
3
+ const { FORMULARY_VERSION, TREATMENT_FORMULARY } = require('../protocols/treatmentFormulary');
4
4
 
5
5
  const { createLLMProvider } = require('../providers/createLLMProvider');
6
6
 
@@ -28,7 +28,7 @@ function buildDraftInput({ context, callLogs, protocol }) {
28
28
  : context?.triages ?? null;
29
29
 
30
30
  return {
31
- protocolVersion: PROTOCOL_VERSION,
31
+ protocolVersion: FORMULARY_VERSION,
32
32
  protocol,
33
33
  patient: {
34
34
  clinicalContext: context?.agentContext ?? null,
@@ -64,7 +64,7 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
64
64
  }
65
65
 
66
66
  const context = await getEscalationContext({ code, now });
67
- const input = buildDraftInput({ context, callLogs, protocol: SYMPTOM_RELIEF_PROTOCOL });
67
+ const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY });
68
68
 
69
69
  // Past this point a generation run was issued. Whether the request actually left the process is
70
70
  // not knowable here — the provider resolves the preset and validates the schema before it calls
@@ -104,7 +104,7 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
104
104
  attempted: true,
105
105
  doctorText,
106
106
  patientMessage,
107
- protocolVersion: PROTOCOL_VERSION,
107
+ protocolVersion: FORMULARY_VERSION,
108
108
  sectionsUnavailable: context.degradedSections ?? [],
109
109
  };
110
110
  }
@@ -70,6 +70,7 @@ const { prepareSupportAction } = require('./supportActionService');
70
70
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
71
71
  const GATE_MAX_ATTEMPTS = 2;
72
72
  const PLAN_MAX_ATTEMPTS = 2;
73
+ const PLAN_TRUNCATION_MAX_TOKENS = 16000;
73
74
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
74
75
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
75
76
  const DEFAULT_CLASSIFIER_WAIT_MS = [15000, 30000, 45000, 60000, 90000];
@@ -593,6 +594,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
593
594
  });
594
595
  settle.planLatencyMs = Date.now() - planStart;
595
596
  settle.attempts = planOutcome.attempts;
597
+ settle.planMaxOutputTokens = planOutcome.planMaxOutputTokens;
596
598
  if (planOutcome.safetyUncertain) settle.supportSafetyCleared = false;
597
599
  if (planOutcome.failure) return finish({ ...planOutcome.failure, autoRepairs: [...gateRepairs, ...(planOutcome.repairs || [])] });
598
600
  const { plan, planRepairs, qualityWarnings } = planOutcome;
@@ -850,7 +852,8 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
850
852
  const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
851
853
  let lastIssues = [];
852
854
  let safetyUncertain = false;
853
- const outcome = (result) => ({ ...result, safetyUncertain });
855
+ let maxOutputTokens = null;
856
+ const outcome = (result) => ({ ...result, safetyUncertain, planMaxOutputTokens: maxOutputTokens });
854
857
  const buildPlan = (takeaways, elements) => new RecommendationPlan({
855
858
  runId: rid,
856
859
  patientId: code,
@@ -883,6 +886,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
883
886
  presetId,
884
887
  input: [{ role: 'user', content }],
885
888
  metadata: { subAgent: 'triage-plan', runId: rid },
889
+ ...(maxOutputTokens ? { maxOutputTokens } : {}),
886
890
  }), { code, rid, stage: 'plan', attempt, budget });
887
891
  } catch {
888
892
  lastIssues = [];
@@ -893,6 +897,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
893
897
  lastIssues = [{ path: 'plan', problem: `respuesta incompleta del proveedor (status=${result.status})` }];
894
898
  firstEvidence = firstEvidence ?? rawEvidence(result);
895
899
  if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
900
+ if (hitTokenLimit(result)) maxOutputTokens = truncationBudget(result, maxOutputTokens);
896
901
  continue;
897
902
  }
898
903
  const parsed = safeParse(readStructuredText(result), null);
@@ -955,6 +960,17 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
955
960
  return outcome({ attempts: PLAN_MAX_ATTEMPTS, failure: { status: 'failed', stage: 'plan', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
956
961
  }
957
962
 
963
+ // Anthropic reports stop_reason; OpenAI Responses reports incomplete_details.reason.
964
+ function hitTokenLimit(result) {
965
+ return result?.stop_reason === 'max_tokens' || result?.incomplete_details?.reason === 'max_output_tokens';
966
+ }
967
+
968
+ function truncationBudget(result, current) {
969
+ const used = Number(result?.usage?.output_tokens);
970
+ const next = Number.isFinite(used) && used > 0 ? used * 2 : PLAN_TRUNCATION_MAX_TOKENS;
971
+ return Math.min(Math.max(next, current || 0), PLAN_TRUNCATION_MAX_TOKENS);
972
+ }
973
+
958
974
  function rawEvidence(result) {
959
975
  const text = str(readStructuredText(result)).trim();
960
976
  if (text) return text.slice(0, RAW_EXCERPT_MAX);
@@ -40,8 +40,10 @@ const getOfficeMessagesController = async (req, res) => {
40
40
 
41
41
  const sendOfficeMessageController = async (req, res) => {
42
42
  try {
43
- const { triggeredBy, text, clientMessageId } = req.body || {};
44
- const delivery = await sendOfficeMessage({ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId });
43
+ const { triggeredBy, text, clientMessageId, fileUrl, fileName } = req.body || {};
44
+ const delivery = await sendOfficeMessage({
45
+ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId, fileUrl, fileName,
46
+ });
45
47
  res.status(201).json({ success: true, ...delivery });
46
48
  } catch (error) {
47
49
  respondWithError(res, error, 'sending office message', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
@@ -46,11 +46,12 @@ function contentSignature(variables) {
46
46
  return crypto.createHash('sha1').update(source).digest('hex').slice(0, 12);
47
47
  }
48
48
 
49
- function buildSendClaimKey({ code, contentSid, variables, idempotencyKey } = {}) {
49
+ function buildSendClaimKey({ code, contactCode, contentSid, variables, idempotencyKey } = {}) {
50
50
  if (idempotencyKey) return `idem:${idempotencyKey}`;
51
51
  if (!code || !contentSid) return null;
52
52
  const signature = contentSignature(variables);
53
- return `tpl:${ensureWhatsAppFormat(code)}:${contentSid}${signature ? `:${signature}` : ''}`;
53
+ const recipient = contactCode ? `${ensureWhatsAppFormat(code)}>${ensureWhatsAppFormat(contactCode)}` : ensureWhatsAppFormat(code);
54
+ return `tpl:${recipient}:${contentSid}${signature ? `:${signature}` : ''}`;
54
55
  }
55
56
 
56
57
  async function isCompletedClaim(key) {
package/lib/index.d.ts CHANGED
@@ -188,6 +188,8 @@ declare module '@peopl-health/nexus' {
188
188
  media: any | null;
189
189
  type: 'message' | 'interactive' | 'media';
190
190
  raw?: { role?: string; replyRequested?: boolean };
191
+ contactCode?: string;
192
+ contactRole?: 'caregiver' | null;
191
193
  }
192
194
 
193
195
  export interface MessageStatusEventData {
@@ -312,7 +314,7 @@ declare module '@peopl-health/nexus' {
312
314
  getVariant(): string;
313
315
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
314
316
  runConversation(config?: any): Promise<any>;
315
- runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
317
+ runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
316
318
  }
317
319
 
318
320
  export interface LLMProvider {
@@ -320,7 +322,7 @@ declare module '@peopl-health/nexus' {
320
322
  getClient?(): any;
321
323
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
322
324
  runConversation(config?: any): Promise<any>;
323
- runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
325
+ runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
324
326
  transcribeAudio?(options?: any): Promise<any>;
325
327
  }
326
328
 
@@ -1,4 +1,5 @@
1
1
  const { Estado_General_ID, Monitoreo_ID } = require('../config/airtableConfig');
2
+ const runtimeConfig = require('../config/runtimeConfig');
2
3
 
3
4
  const { httpError, requiredText } = require('../utils/httpErrorUtils');
4
5
  const { inlineOf } = require('../utils/coercionUtils');
@@ -7,6 +8,7 @@ const { logger } = require('../utils/logger');
7
8
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
9
  const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
9
10
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
11
+ const { prepareMessageMedia } = require('../helpers/mediaHelper');
10
12
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
11
13
  const { sendMessage } = require('../core/NexusMessaging');
12
14
 
@@ -14,20 +16,23 @@ const { getRecordByFilter } = require('./airtableService');
14
16
  const { getMessages } = require('./messageService');
15
17
  const { getPatientInformation } = require('./patientService');
16
18
 
17
- const ASSISTANT_FIELDS = ['email', 'doctor_match', 'office_label', 'template_content_sid'];
18
19
  const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
19
20
  const HIDDEN_ORIGINS = ['system', 'instruction'];
20
21
  const DEFAULT_MESSAGE_LIMIT = 30;
21
22
  const MAX_MESSAGE_LIMIT = 50;
22
23
  const MAX_TEXT_LENGTH = 1500;
23
24
  const MAX_TEMPLATE_TEXT_LENGTH = 800;
25
+ const DOCUMENT_TEMPLATE_DEFAULT_TEXT = 'Le compartimos un documento.';
26
+ const DOCUMENT_FILE_TYPE = 'document';
24
27
 
25
28
  async function getOfficeAssistant(email) {
26
29
  const normalized = String(email ?? '').trim().toLowerCase();
27
30
  if (!normalized) return null;
28
31
 
29
32
  const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {active})`;
30
- const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, ASSISTANT_FIELDS, true) || [];
33
+ // No field list: Airtable rejects a listed column that does not exist yet, which would take the whole office view down
34
+ // until document_template_content_sid is added.
35
+ const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, undefined, true) || [];
31
36
  const doctor = inlineOf(assistant?.doctor_match);
32
37
  const label = inlineOf(assistant?.office_label);
33
38
  if (!doctor || !label) return null;
@@ -37,6 +42,7 @@ async function getOfficeAssistant(email) {
37
42
  doctor,
38
43
  label,
39
44
  templateContentSid: inlineOf(assistant.template_content_sid) || null,
45
+ documentTemplateContentSid: inlineOf(assistant.document_template_content_sid) || null,
40
46
  };
41
47
  }
42
48
 
@@ -100,34 +106,78 @@ async function readOfficeMessages({ requestedBy, code, limit }) {
100
106
  };
101
107
  }
102
108
 
103
- function officeMessage({ assistant, patientCode, text, inWindow }) {
109
+ function officeDocumentUrl(fileUrl) {
110
+ if (!fileUrl) return null;
111
+ const bucketName = runtimeConfig.get('AWS_S3_BUCKET_NAME');
112
+ let url = null;
113
+ try {
114
+ url = new URL(String(fileUrl));
115
+ } catch {
116
+ url = null;
117
+ }
118
+ // The approved document template pins the S3 host and takes the rest of the URL as a variable. A bucket name
119
+ // with dots (whatsapp.prod) is presigned path-style, so the bucket is then the first path segment.
120
+ const bucket = escapeRegExp(bucketName ?? '');
121
+ const isVirtualHosted = new RegExp(`^${bucket}\\.s3(\\.[a-z0-9-]+)?\\.amazonaws\\.com$`).test(url?.hostname ?? '');
122
+ const isPathStyle = /^s3(\.[a-z0-9-]+)?\.amazonaws\.com$/.test(url?.hostname ?? '')
123
+ && url.pathname.startsWith(`/${bucketName}/`);
124
+ if (!bucketName || url?.protocol !== 'https:' || !(isVirtualHosted || isPathStyle)) {
125
+ throw httpError(400, 'The document must be uploaded before it is sent');
126
+ }
127
+ return url;
128
+ }
129
+
130
+ // Twilio needs the file type in a template's media URL, and uploads are stored without an
131
+ // extension, so the template gets the copy prepareMessageMedia stores with one.
132
+ async function templateDocumentOf(document, patientCode) {
133
+ const { mediaUrl } = await prepareMessageMedia({
134
+ code: patientCode, fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name,
135
+ });
136
+ // prepareMessageMedia answers with the original URL when the copy fails, and that one has no file type.
137
+ if (!mediaUrl || mediaUrl === document.url.href) throw httpError(502, 'The document could not be prepared for the template');
138
+ return { ...document, url: officeDocumentUrl(mediaUrl) };
139
+ }
140
+
141
+ function officeMessage({ assistant, patientCode, text, inWindow, document }) {
142
+ const attachment = document ? { fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name } : {};
104
143
  if (inWindow) {
105
144
  if (text.length > MAX_TEXT_LENGTH) throw httpError(422, `The message exceeds ${MAX_TEXT_LENGTH} characters`);
106
- return { code: patientCode, body: `${assistant.label}: ${text}` };
145
+ return { code: patientCode, body: text ? `${assistant.label}: ${text}` : assistant.label, ...attachment };
107
146
  }
108
147
 
109
- const templateText = text.replace(/\s+/g, ' ').trim();
148
+ const templateText = text.replace(/\s+/g, ' ').trim() || DOCUMENT_TEMPLATE_DEFAULT_TEXT;
110
149
  if (templateText.length > MAX_TEMPLATE_TEXT_LENGTH) {
111
150
  throw httpError(422, `Outside the 24-hour window the message is sent as a template and cannot exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters`);
112
151
  }
113
- if (!assistant.templateContentSid) throw httpError(503, 'The office template is not configured; the patient is outside the 24-hour window');
152
+ const contentSid = document ? assistant.documentTemplateContentSid : assistant.templateContentSid;
153
+ if (!contentSid) {
154
+ const template = document ? 'office document template' : 'office template';
155
+ throw httpError(503, `The ${template} is not configured; the patient is outside the 24-hour window`);
156
+ }
114
157
  return {
115
158
  code: patientCode,
116
159
  body: `${assistant.label}: ${templateText}`,
117
- contentSid: assistant.templateContentSid,
118
- variables: { 1: templateText },
160
+ contentSid,
161
+ variables: document
162
+ ? { 1: templateText, 2: `${document.url.pathname.slice(1)}${document.url.search}` }
163
+ : { 1: templateText },
164
+ ...attachment,
119
165
  };
120
166
  }
121
167
 
122
- async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
168
+ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId, fileUrl, fileName }) {
123
169
  const assistant = await requireOfficeAssistant(requestedBy);
124
170
  const patientCode = await officePatientCode(assistant, code);
125
- const messageText = requiredText(text, 'text');
171
+ const url = officeDocumentUrl(fileUrl);
172
+ const document = url ? { url, name: fileName } : null;
173
+ const messageText = document ? String(text ?? '').trim() : requiredText(text, 'text');
126
174
  const messageKey = requiredText(clientMessageId, 'clientMessageId');
127
175
 
128
176
  const inWindow = await isWithin24HourWindow(patientCode);
177
+ const isDocumentTemplate = Boolean(document && !inWindow && assistant.documentTemplateContentSid);
178
+ const sentDocument = isDocumentTemplate ? await templateDocumentOf(document, patientCode) : document;
129
179
  const message = {
130
- ...officeMessage({ assistant, patientCode, text: messageText, inWindow }),
180
+ ...officeMessage({ assistant, patientCode, text: messageText, inWindow, document: sentDocument }),
131
181
  triggeredBy: assistant.email,
132
182
  idempotencyKey: `office:${patientCode}:${messageKey}`,
133
183
  };
@@ -143,6 +193,7 @@ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
143
193
  assistant: assistant.email,
144
194
  code: redactDirectIdentifiers(patientCode),
145
195
  transport,
196
+ hasDocument: Boolean(document),
146
197
  duplicate: result?.duplicate === true,
147
198
  });
148
199
  return { transport, messageId: result?.messageId || null, duplicate: result?.duplicate === true };
@@ -95,6 +95,7 @@ class MongoStorage {
95
95
  fromMe: doc.from_me,
96
96
  triggeredBy: doc.triggeredBy,
97
97
  ...(doc.origin === 'system' && doc.raw ? { raw: doc.raw } : {}),
98
+ ...(doc.contact_code && { contactCode: doc.contact_code, contactRole: doc.contact_role }),
98
99
  status,
99
100
  ...(frontendId && { frontendId })
100
101
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.58.0-dev.10248",
3
+ "version": "5.58.0-dev.10495",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,216 +0,0 @@
1
- const PROTOCOL_VERSION = '2026-09-18';
2
-
3
- const MEDICAL_REVIEW = 'valoración médica';
4
-
5
- function deepFreeze(value) {
6
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
7
- Object.freeze(value);
8
- for (const nested of Object.values(value)) deepFreeze(nested);
9
- }
10
- return value;
11
- }
12
-
13
- const SYMPTOM_RELIEF_PROTOCOL = deepFreeze([
14
- {
15
- key: 'nausea_vomito',
16
- label: 'Náusea y vómito',
17
- options: [
18
- { grade: 1, brand: 'AMAL', drug: 'Ondansetrón', strength: '8 mg', instructions: '1 tableta cada 24 horas por 5 días' },
19
- ],
20
- },
21
- {
22
- key: 'reflujo',
23
- label: 'Reflujo',
24
- options: [
25
- {
26
- grade: 1,
27
- brand: null,
28
- drug: 'Esomeprazol',
29
- strength: '40 mg',
30
- instructions: '1 cápsula cada 24 horas por 5 días',
31
- alternative: {
32
- when: 'la paciente ya está tomando esomeprazol',
33
- brand: null,
34
- drug: 'Famotidina',
35
- strength: '40 mg',
36
- instructions: '1 tableta cada 24 horas por 5 días',
37
- },
38
- },
39
- ],
40
- },
41
- {
42
- key: 'diarrea',
43
- label: 'Diarrea',
44
- options: [
45
- {
46
- grade: 1,
47
- brand: null,
48
- drug: 'Loperamida',
49
- strength: '4 mg',
50
- instructions: '4 mg al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
51
- consider: true,
52
- },
53
- {
54
- grade: 2,
55
- brand: null,
56
- drug: 'Loperamida',
57
- strength: '4 mg',
58
- instructions: '4 mg al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
59
- ruleOutFirst: ['causa infecciosa', 'causa obstructiva', 'intolerancia'],
60
- },
61
- ],
62
- },
63
- {
64
- key: 'dolor_abdominal_colico',
65
- label: 'Dolor abdominal tipo cólico',
66
- options: [
67
- {
68
- grade: 1,
69
- brand: 'BUSCAPINA COMPUESTA',
70
- drug: 'Butilhioscina/Metamizol',
71
- strength: '10/250 mg',
72
- instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
73
- },
74
- ],
75
- },
76
- {
77
- key: 'estrenimiento',
78
- label: 'Estreñimiento',
79
- options: [
80
- { grade: 1, brand: 'SENOKOT', drug: 'Senósidos', strength: null, instructions: '2 tabletas cada noche por 5 días' },
81
- {
82
- grade: 2,
83
- brand: 'LACTULAX',
84
- drug: 'Lactulosa',
85
- strength: null,
86
- instructions: '10 ml cada 8 horas hasta lograr evacuación, después suspender',
87
- },
88
- ],
89
- },
90
- {
91
- key: 'mucositis',
92
- label: 'Mucositis',
93
- options: [
94
- {
95
- grade: 1,
96
- brand: null,
97
- drug: 'Colutorios alcalinos',
98
- strength: '½ L de agua con 1 cucharadita de sal y 2 cucharaditas de bicarbonato',
99
- instructions: 'enjuagues y gárgaras de 1 minuto cada 6 horas por 5 días',
100
- isPharmacological: false,
101
- },
102
- {
103
- grade: 2,
104
- brand: 'VELIAN',
105
- drug: 'Dexketoprofeno',
106
- strength: '25 mg/10 ml en sobres',
107
- instructions: '1 sobre cada 8 horas, 30 minutos antes de los alimentos, y tragar, por 7 días',
108
- escalateIf: `si persiste, ${MEDICAL_REVIEW}`,
109
- },
110
- ],
111
- },
112
- {
113
- key: 'dolor',
114
- label: 'Dolor',
115
- options: [
116
- {
117
- grade: 1,
118
- brand: 'TEMPRA / TYLENOL',
119
- drug: 'Paracetamol',
120
- strength: '750 mg',
121
- instructions: '1 a 2 tabletas cada 8 horas por razón necesaria, por 5 días',
122
- },
123
- {
124
- grade: 2,
125
- brand: 'CELEBREX',
126
- drug: 'Celecoxib',
127
- strength: '200 mg',
128
- instructions: '1 cápsula cada 24 horas con alimentos por 5 días',
129
- steppedUpFromGrade: 1,
130
- escalateIf: `siempre, ${MEDICAL_REVIEW}`,
131
- },
132
- ],
133
- },
134
- {
135
- key: 'neuropatia',
136
- label: 'Neuropatía',
137
- alwaysEscalate: MEDICAL_REVIEW,
138
- recognition: 'ardor, sensación de adormecimiento o piquetes; sigue el trayecto de un nervio, o aparece en manos y pies al mismo tiempo',
139
- options: [],
140
- },
141
- {
142
- key: 'sindrome_mano_pie',
143
- label: 'Síndrome mano-pie',
144
- options: [
145
- {
146
- grade: 1,
147
- brand: 'CERAVE',
148
- drug: 'Ceramidas',
149
- strength: null,
150
- instructions: '2 a 3 veces al día de forma continua',
151
- isPharmacological: false,
152
- },
153
- {
154
- grade: 2,
155
- brand: 'NUTRAPLUS',
156
- drug: 'Urea',
157
- strength: '10%',
158
- instructions: 'capa fina cada 12 horas de forma continua',
159
- },
160
- ],
161
- },
162
- {
163
- key: 'rinitis_alergia',
164
- label: 'Rinitis o alergia',
165
- options: [
166
- { grade: 1, brand: 'REACTINE', drug: 'Cetirizina', strength: '10 mg', instructions: '1 tableta cada 24 horas por 7 días' },
167
- { grade: 2, brand: 'REACTINE', drug: 'Cetirizina', strength: '10 mg', instructions: '1 tableta cada 24 horas por 7 días' },
168
- ],
169
- },
170
- {
171
- key: 'insomnio',
172
- label: 'Insomnio',
173
- options: [
174
- { grade: 1, brand: 'MELATOL', drug: 'Melatonina', strength: '3 mg', instructions: '1 tableta cada 24 horas por la noche por 14 días' },
175
- { grade: 2, brand: 'MELATOL', drug: 'Melatonina', strength: '3 mg', instructions: '1 tableta cada 24 horas por la noche por 14 días' },
176
- ],
177
- },
178
- ]);
179
-
180
- const byKey = new Map(SYMPTOM_RELIEF_PROTOCOL.map((entry) => [entry.key, entry]));
181
-
182
- function protocolFor(symptomKey, grade) {
183
- const entry = byKey.get(String(symptomKey ?? '').trim());
184
- if (!entry) return null;
185
-
186
- const option = entry.options.find((candidate) => candidate.grade === grade) ?? null;
187
- return {
188
- key: entry.key,
189
- label: entry.label,
190
- grade,
191
- option,
192
- alwaysEscalate: entry.alwaysEscalate ?? null,
193
- recognition: entry.recognition ?? null,
194
- hasNoOptionForGrade: option === null,
195
- };
196
- }
197
-
198
- function protocolExcerpt(symptoms = []) {
199
- const seen = new Set();
200
- const excerpt = [];
201
- for (const { key, grade } of symptoms) {
202
- const id = `${key}:${grade}`;
203
- if (seen.has(id)) continue;
204
- seen.add(id);
205
- const entry = protocolFor(key, grade);
206
- if (entry) excerpt.push(entry);
207
- }
208
- return excerpt;
209
- }
210
-
211
- module.exports = {
212
- PROTOCOL_VERSION,
213
- SYMPTOM_RELIEF_PROTOCOL,
214
- protocolFor,
215
- protocolExcerpt,
216
- };