@peopl-health/nexus 5.74.0-dev.15344 → 5.74.0-dev.15346

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.
@@ -19,7 +19,6 @@ const { TAIL_PLACEMENT, CURRENT_TURN } = require('../promptPlacement');
19
19
  const { logger } = require('../../utils/logger');
20
20
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
21
21
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
22
- const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
23
22
  const { isJsonBlob } = require('../../utils/formatUtils');
24
23
  const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
25
24
  const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
@@ -356,8 +355,6 @@ class BaseLLMProvider {
356
355
  })
357
356
  .filter(Boolean);
358
357
 
359
- if (outreachBrief.checkIn) return this._buildCheckInDueMessage(outreachBrief, lines);
360
-
361
358
  const why = lines([
362
359
  ['último triaje contestado', outreachBrief.lastTriageAt],
363
360
  ['grado máximo en ese triaje', outreachBrief.maxGrade],
@@ -391,49 +388,6 @@ class BaseLLMProvider {
391
388
  return [{ role: 'developer', content: parts.join('\n') }];
392
389
  }
393
390
 
394
- _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, asOf = null }, lines) {
395
- const ago = (at) => {
396
- const minutes = asOf ? Math.round((new Date(asOf) - new Date(at)) / 60000) : NaN;
397
- if (!Number.isFinite(minutes) || minutes < 0) return '';
398
- return minutes < 60 ? ` (hace ${minutes} min)` : ` (hace ${Math.floor(minutes / 60)} h ${minutes % 60} min)`;
399
- };
400
- const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
401
- const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
402
- const pending = lines([
403
- ['lo que querías preguntarle', checkIn.question],
404
- ['por qué quedó abierto', checkIn.concern],
405
- ['qué dato esperabas', checkIn.awaiting],
406
- ['desde', local(checkIn.armedAt)],
407
- ['nivel de la escalación', checkIn.urgency],
408
- ]);
409
- const conversation = lines([
410
- ['su último mensaje', said(exchange?.patient)],
411
- ['tu último mensaje (tuyo o del equipo)', said(exchange?.own)],
412
- ['mensajes tuyos o del equipo hoy', exchange ? String(exchange.ownMessagesToday) : null],
413
- ]);
414
- const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
415
- const parts = [
416
- '[CHECK-IN QUE VENCE (prioritario) para este turno]',
417
- 'Venció el plazo para retomar algo pendiente con ella. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a buscarla o si ya no hace falta.',
418
- '', '## Qué quedó pendiente', ...pending,
419
- ];
420
- if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
421
- parts.push(
422
- '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
423
- '',
424
- `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
425
- '- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
426
- '- Si tu último mensaje ya le hace esta pregunta o la cubre, y ella estuvo activa hoy y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
427
- '- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
428
- '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ella ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
429
- '- Si la red viene de una escalación, su urgencia marca el plazo del equipo para revisarla, no una razón para volver a escribirle.',
430
- '- 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.',
431
- '- 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 ella contó o acordó.',
432
- 'Si escribes: breve, sin saludar ni escribir su nombre, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
433
- );
434
- return [{ role: 'developer', content: parts.join('\n') }];
435
- }
436
-
437
391
  _buildSkillCatalogMessage(skillCatalog) {
438
392
  const described = (Array.isArray(skillCatalog) ? skillCatalog : []).filter((skill) => skill?.name && skill?.description);
439
393
  if (!described.length) return [];
@@ -552,34 +552,6 @@ async function markReminderSent({ code, reminderId, trace = null }) {
552
552
  });
553
553
  }
554
554
 
555
- async function settleCheckInRow({ code, reminderId, sent = false, reason = null, requireActive = false, onlyIfDispatched = false, trace = null }) {
556
- if (!code || !reminderId) return false;
557
- return auditedWrite({
558
- trace,
559
- code,
560
- table: 'reminder',
561
- meta: { reminderId, lifecycle: sent ? 'sent' : 'stood_down' },
562
- write: async () => {
563
- const fields = sent ? { is_active: false, is_sent: true } : { is_active: false, stand_down_reason: reason };
564
- const updated = await airtableService.updateRecordByFilter(
565
- Monitoreo_ID,
566
- 'reminder',
567
- `AND(${[
568
- fieldEquals('whatsapp_id', code),
569
- fieldEquals('schedule_id', reminderId),
570
- 'IF({is_sent}, "true", "false") = "false"',
571
- requireActive ? 'IF({is_active}, "true", "false") = "true"' : null,
572
- onlyIfDispatched ? fieldEquals('stand_down_reason', 'dispatched') : null,
573
- ].filter(Boolean).join(', ')})`,
574
- fields,
575
- code,
576
- );
577
- if (!updated?.length) throw new Error(`check-in ${reminderId} was not settled`);
578
- return updated;
579
- },
580
- });
581
- }
582
-
583
555
  async function recordContingencyEscalation({ code, trace, planId, dueAtUtc, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern, message, actionRequested, priority = null, isLive = null }) {
584
556
  return auditedWrite({
585
557
  trace,
@@ -726,7 +698,6 @@ module.exports = {
726
698
  cancelFollowUp,
727
699
  hasCheckInNear,
728
700
  markReminderSent,
729
- settleCheckInRow,
730
701
  recordContingencyEscalation,
731
702
  cancelContingencyRows,
732
703
  standDownAllPendingRows,
@@ -278,12 +278,6 @@ const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireCeiling
278
278
  patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
279
279
  });
280
280
 
281
- function escalationUrgencyOf(net) {
282
- if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
283
- const silence = net?.patientReminder?.firesAfterSilenceMinutes;
284
- return Object.keys(ESCALATION_SILENCE_MINUTES).find((level) => ESCALATION_SILENCE_MINUTES[level] === silence) || null;
285
- }
286
-
287
281
  async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
288
282
  const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
289
283
  if (!silence) return { armed: false, reason: 'urgency_not_covered' };
@@ -468,4 +462,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
468
462
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
469
463
  }
470
464
 
471
- module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
465
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
@@ -8,13 +8,11 @@ const DECISIONS = ['write', 'hold'];
8
8
 
9
9
  const HOLD_REASONS = [
10
10
  'already_wrote_today',
11
- 'answered_since_armed',
12
11
  'case_closed_nothing_pending',
13
12
  'contingency_already_armed',
14
13
  'no_change_since_last_outreach',
15
14
  'no_utility_anchor',
16
15
  'recent_patient_activity',
17
- 'rescheduled_for_cadence',
18
16
  'unanswered_outreach_limit',
19
17
  'other',
20
18
  ];
@@ -16,7 +16,6 @@ const ARCHIVE_FIELDS = Object.freeze({
16
16
  PREVIOUS_SYMPTOMS: 'flduGxzHejCy7FfTr',
17
17
  PHYSICIAN_REPORT: 'fld3w7Zfuc8BChDOL',
18
18
  EXTRACTION_ANALYSIS: 'fldcrm4xZuG2hHzW2',
19
- FIRST_MESSAGE: 'fld3GmmdKLCnJuKzL',
20
19
  PATIENT: 'fldMIxWgaGiF7IvYr',
21
20
  WHATSAPP: 'fld5XXqDfLgT8JQS4',
22
21
  CREATED: 'fld1rLI32ITUtgfdJ',
@@ -74,7 +73,7 @@ const BACKWARD_LINKS = Object.freeze({
74
73
 
75
74
  // Links to non-catalog tables that are never archived: a linked group stays in Airtable.
76
75
  const EXTERNAL_LINKS = Object.freeze({
77
- [TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.PHYSICIAN_REPORT, FIELD.QUESTIONNAIRE.EXTRACTION_ANALYSIS, FIELD.QUESTIONNAIRE.FIRST_MESSAGE],
76
+ [TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.PHYSICIAN_REPORT, FIELD.QUESTIONNAIRE.EXTRACTION_ANALYSIS],
78
77
  [TABLE.TRIAGES]: [FIELD.TRIAGE.PAIN_FOLLOW_UP],
79
78
  [TABLE.SYMPTOMS]: [FIELD.SYMPTOM.PHYSICIAN_REPORT],
80
79
  });
@@ -8,8 +8,7 @@ const { AssistantMessageError, injectAssistantMessages } = require('../services/
8
8
  const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
9
9
 
10
10
  const { getRecordByFilter } = require('../services/airtableService');
11
- const { sendMessage, processInstruction, processSystemMessage, processCheckInDue, isDraining } = require('../core/NexusMessaging');
12
- const { CHECK_IN_TYPES } = require('../clinical/config/checkInConfig');
11
+ const { sendMessage, processInstruction, processSystemMessage } = require('../core/NexusMessaging');
13
12
  const { createAssistant, switchAssistant } = require('../clinical');
14
13
  const { cancelPendingFollowUps } = require('../clinical/services/clinicalAirtableService');
15
14
 
@@ -71,18 +70,6 @@ const addInsAssistantController = async (req, res) => {
71
70
  }
72
71
  };
73
72
 
74
- const checkInDueController = async (req, res) => {
75
- const { code, reminder_id: reminderId, type, description, first_name: firstName } = req.body || {};
76
- if (!code || !reminderId) return res.status(400).json({ success: false, error: 'code and reminder_id are required' });
77
- if (!CHECK_IN_TYPES.includes(type)) return res.status(400).json({ success: false, error: `type must be one of ${CHECK_IN_TYPES.join(' | ')}` });
78
- if (isDraining()) return res.status(503).json({ success: false, error: 'draining' });
79
-
80
- processCheckInDue(code, { reminderId, type, question: description || '', firstName: firstName || null })
81
- .then((result) => logger.info('[AssistantController] Check-in settled', { code, reminderId, ...result }))
82
- .catch((error) => logger.error('[AssistantController] Check-in failed', { error: error.message, code, reminderId }));
83
- return res.status(202).json({ success: true, accepted: true });
84
- };
85
-
86
73
  const addMsgAssistantController = async (req, res) => {
87
74
  try {
88
75
  await injectAssistantMessages(req.body, processSystemMessage);
@@ -161,7 +148,6 @@ const switchAssistantController = async (req, res) => {
161
148
 
162
149
  module.exports = {
163
150
  addInsAssistantController,
164
- checkInDueController,
165
151
  addMsgAssistantController,
166
152
  createAssistantController,
167
153
  doNotAlertController,
@@ -45,12 +45,10 @@ const {
45
45
  readPendingReminderForPatient,
46
46
  cancelPendingFollowUps,
47
47
  markReminderSent,
48
- settleCheckInRow,
49
48
  cancelFollowUp,
50
49
  hasCheckInNear,
51
50
  } = require('../clinical/services/clinicalAirtableService');
52
- const { cancelContingencies, applyContingencyEvent } = require('../clinical/services/contingencyDispatchService');
53
- const { checkInTriggeredBy, planCheckInDue } = require('../clinical/services/checkInDueService');
51
+ const { cancelContingencies } = require('../clinical/services/contingencyDispatchService');
54
52
  const { isContingencyCancelOnReplyLive } = require('../clinical/flags/contingencyFlags');
55
53
  const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
56
54
 
@@ -486,7 +484,7 @@ class NexusMessaging {
486
484
 
487
485
  async sendAssistantReply(messageData) {
488
486
  if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
489
- if (!messageData.contactCode && (messageData.outreachCarrier?.replyToContact || (!messageData.preemptiveWindowRoute && !messageData.outreachStartedAt))) {
487
+ if (!messageData.contactCode && !messageData.preemptiveWindowRoute && !messageData.outreachStartedAt) {
490
488
  const contact = await replyContactFor(messageData.code);
491
489
  if (contact) messageData = { ...messageData, ...contact };
492
490
  }
@@ -514,7 +512,7 @@ class NexusMessaging {
514
512
  // Proactive outreach lands days after the patient last wrote, so the session is usually closed.
515
513
  // Waiting for Twilio 63016 to bounce would delay every message in the batch by a round-trip.
516
514
  if (messageData.preemptiveWindowRoute && this._needsTemplateRoute(messageData)
517
- && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
515
+ && !(await isWithin24HourWindow(messageData.code))) {
518
516
  try {
519
517
  messageData = await buildOutreachCarrier(messageData, {
520
518
  provider: this.provider,
@@ -1002,7 +1000,6 @@ class NexusMessaging {
1002
1000
  firstName = null,
1003
1001
  reminderType = 'seguimiento',
1004
1002
  reminderPrefix = null,
1005
- replyToContact = false,
1006
1003
  dryRun = false,
1007
1004
  } = {}) {
1008
1005
  const outreachStartedAt = new Date().toISOString();
@@ -1033,7 +1030,7 @@ class NexusMessaging {
1033
1030
  turnKind: TURN_KIND.PROACTIVE_OUTREACH,
1034
1031
  outreachBrief: brief,
1035
1032
  preemptiveWindowRoute: true,
1036
- outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
1033
+ outreachCarrier: { reminderType, reminderPrefix, firstName },
1037
1034
  outreachStartedAt,
1038
1035
  // Stamped on the outbound so a delivered message joins back to the row that surfaced her.
1039
1036
  triggeredBy: triggeredBy || null,
@@ -1122,62 +1119,6 @@ class NexusMessaging {
1122
1119
  };
1123
1120
  }
1124
1121
 
1125
- async processCheckInDue(code, { reminderId, type, question = '', firstName = null } = {}) {
1126
- if (!code || !reminderId) throw new Error('code and reminderId are required');
1127
- const claim = await acquireSendClaim({ idempotencyKey: `checkin-due:${reminderId}`, code });
1128
- if (!claim.acquired) return { decision: 'skipped', holdReason: 'duplicate', sent: false };
1129
-
1130
- let plan = null;
1131
- let dispatched = false;
1132
- try {
1133
- plan = await planCheckInDue({ code, reminderId, type, question, firstName });
1134
- if (plan.mode === 'stale') {
1135
- await settleCheckInRow({ code, reminderId, reason: plan.reason });
1136
- await completeSendClaim(claim.claimId);
1137
- return { decision: 'skipped', holdReason: plan.reason, sent: false };
1138
- }
1139
- dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1140
- if (!dispatched) {
1141
- await completeSendClaim(claim.claimId);
1142
- return { decision: 'skipped', holdReason: 'row_not_active', sent: false };
1143
- }
1144
- await this._fireCheckInNet(code, plan.planId, reminderId);
1145
-
1146
- const triggeredBy = checkInTriggeredBy(reminderId);
1147
- let result;
1148
- if (plan.mode === 'mandatory') {
1149
- const { outcome } = await this.processInstruction(code, plan.instruction, 'developer', { triggeredBy });
1150
- const sent = outcome === 'sent' || outcome === 'unknown';
1151
- result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
1152
- } else {
1153
- const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName, replyToContact: true });
1154
- result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
1155
- }
1156
-
1157
- const settled = result.sent
1158
- ? await settleCheckInRow({ code, reminderId, sent: true, onlyIfDispatched: true })
1159
- : await settleCheckInRow({ code, reminderId, reason: result.holdReason === 'turn_not_run' ? 'failed' : `held_${result.holdReason || result.decision}`, onlyIfDispatched: true });
1160
- if (!settled) logger.warn('[processCheckInDue] check-in row was not settled after the turn', { reminderId, sent: result.sent });
1161
- await completeSendClaim(claim.claimId);
1162
- return result;
1163
- } catch (error) {
1164
- logger.error('[processCheckInDue] check-in turn failed', { reminderId, error: error.message });
1165
- if (dispatched) await settleCheckInRow({ code, reminderId, reason: 'failed', onlyIfDispatched: true });
1166
- await releaseSendClaim(claim.claimId);
1167
- throw error;
1168
- }
1169
- }
1170
-
1171
- async _fireCheckInNet(code, planId, reminderId) {
1172
- if (!planId) return;
1173
- try {
1174
- const fired = await applyContingencyEvent({ patientCode: code, planId, stage: 'patient', event: 'fired' });
1175
- if (!fired?.applied) logger.info('[processCheckInDue] net was not fired', { reminderId, planId, reason: fired?.reason || null });
1176
- } catch (error) {
1177
- logger.error('[processCheckInDue] net fire failed; team stage not armed', { reminderId, planId, teamStageArmed: false, error: error.message });
1178
- }
1179
- }
1180
-
1181
1122
  async _retireSkippedFollowUp(code, reminderId, holdReason) {
1182
1123
  const retired = await cancelFollowUp({ code, reminderId, reason: `skipped_${holdReason}` });
1183
1124
  if (!retired) logger.warn('[processScheduledFollowUp] skipped follow-up was not stood down', { reminderId, holdReason });
@@ -1407,10 +1348,6 @@ const processOutreach = async (code, options) => {
1407
1348
  return await requireDefaultInstance().processOutreach(code, options);
1408
1349
  };
1409
1350
 
1410
- const processCheckInDue = async (code, options) => {
1411
- return await requireDefaultInstance().processCheckInDue(code, options);
1412
- };
1413
-
1414
1351
  const processScheduledFollowUp = async (code, options) => {
1415
1352
  return await requireDefaultInstance().processScheduledFollowUp(code, options);
1416
1353
  };
@@ -1419,8 +1356,6 @@ const processSystemMessage = async (code, messages, role, options) => {
1419
1356
  return await requireDefaultInstance().processSystemMessage(code, messages, role, options);
1420
1357
  };
1421
1358
 
1422
- const isDraining = () => Boolean(getDefaultInstance()?.getBatchingManager()?.isDraining());
1423
-
1424
1359
  const getEventBus = () => getDefaultInstance()?.getEventBus();
1425
1360
 
1426
1361
  const getPhiProcessor = () => getDefaultInstance()?.getPhiProcessor();
@@ -1434,10 +1369,8 @@ module.exports = {
1434
1369
  scheduleTemplateApproval,
1435
1370
  processInstruction,
1436
1371
  processOutreach,
1437
- processCheckInDue,
1438
1372
  processScheduledFollowUp,
1439
1373
  processSystemMessage,
1440
- isDraining,
1441
1374
  setDefaultInstance,
1442
1375
  getDefaultInstance,
1443
1376
  requireDefaultInstance,
package/lib/index.d.ts CHANGED
@@ -275,7 +275,6 @@ declare module '@peopl-health/nexus' {
275
275
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
276
276
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
277
277
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
278
- processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
279
278
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
280
279
  isConnected(): boolean;
281
280
  shutdown(options?: ShutdownOptions): Promise<DrainResult>;
@@ -468,15 +467,6 @@ declare module '@peopl-health/nexus' {
468
467
  lastInboundAt?: string | null;
469
468
  lastOutboundAt?: string | null;
470
469
  lastOutreach?: string | null;
471
- checkIn?: { type: string; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null } | null;
472
- recentCheckIns?: string[];
473
- }
474
-
475
- export interface CheckInDueResult {
476
- decision: 'write' | 'hold' | 'skipped';
477
- holdReason: string | null;
478
- nextCheckAt?: string | null;
479
- sent: boolean;
480
470
  }
481
471
 
482
472
  export interface OutreachDecision {
@@ -2,7 +2,6 @@ const express = require('express');
2
2
 
3
3
  const assistantRouteDefinitions = {
4
4
  'POST /add-instruction': 'addInsAssistantController',
5
- 'POST /check-in-due': 'checkInDueController',
6
5
  'POST /add-msg': 'addMsgAssistantController',
7
6
  'POST /create': 'createAssistantController',
8
7
  'POST /info': 'getInfoAssistantController',
@@ -196,7 +195,6 @@ const officeAssistantController = require('../controllers/officeAssistantControl
196
195
  const builtInControllers = {
197
196
  // Assistant controllers
198
197
  addInsAssistantController: assistantController.addInsAssistantController,
199
- checkInDueController: assistantController.checkInDueController,
200
198
  addMsgAssistantController: assistantController.addMsgAssistantController,
201
199
  createAssistantController: assistantController.createAssistantController,
202
200
  getInfoAssistantController: assistantController.getInfoAssistantController,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.74.0-dev.15344",
3
+ "version": "5.74.0-dev.15346",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,3 +0,0 @@
1
- const CHECK_IN_TYPES = ['contingencia', 'seguimiento'];
2
-
3
- module.exports = { CHECK_IN_TYPES };
@@ -1,93 +0,0 @@
1
- const moment = require('moment-timezone');
2
-
3
- const { getMessages } = require('../../services/messageService');
4
- const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
5
- const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
6
- const { readPendingReminderForPatient } = require('./clinicalAirtableService');
7
-
8
- const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
9
- const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
10
- const TRIGGERED_BY_PREFIX = 'send_reminder:';
11
- const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
12
- const EXCERPT_LENGTH = 160;
13
-
14
- const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
15
-
16
- function mandatoryInstruction(firstName, question) {
17
- return `${firstName || 'La paciente'} no ha vuelto a escribir y quedó un tema abierto que querías retomar. Esto es lo que decidiste preguntarle: "${question}".
18
-
19
- Antes de escribir, revisa la conversación desde que decidiste preguntarlo. Si ya lo respondió — a ti o al equipo —, no se lo vuelvas a preguntar: retoma desde lo que dijo y pregunta solo lo que siga faltando; si ya no falta nada, cierra en una línea breve y cálida. No le preguntes si el equipo ya la contactó o ya le dio indicaciones: eso no te toca a ti; si tu pregunta lo incluía, quita esa parte.
20
-
21
- Escríbele tú, de forma breve y natural, en tu tono de siempre, como quien retoma algo pendiente de una conversación. NO digas que pidió un recordatorio ni que se lo prometiste — no lo hizo. No menciones alertas, planes, seguimientos programados ni nada del sistema. No repitas un mensaje que ya le enviaste. Si contesta, sigue la conversación con normalidad.`;
22
- }
23
-
24
- async function recentCheckIns(code, now) {
25
- const rows = await getMessages(
26
- {
27
- numero: code,
28
- from_me: true,
29
- createdAt: { $gte: new Date(now.getTime() - RECENT_CHECK_IN_WINDOW_MS) },
30
- $or: [
31
- { origin: 'assistant', triggeredBy: { $regex: `^(?:${TRIGGERED_BY_PREFIX}|seguimiento:|followup_)` } },
32
- { origin: 'instruction', triggeredBy: null, message_id: { $regex: '^instruction_' }, 'raw.gated': { $ne: true }, plainBody: { $regex: NET_INSTRUCTION_MARKER } },
33
- ],
34
- },
35
- { sort: { createdAt: 1 }, select: 'createdAt' },
36
- );
37
- return (rows || []).map((row) => new Date(row.createdAt).toISOString());
38
- }
39
-
40
- async function lastMessage(code, now, fromMe) {
41
- const [row] = await getMessages(
42
- { numero: code, from_me: fromMe, origin: { $ne: 'instruction' }, createdAt: { $lt: now } },
43
- { sort: { createdAt: -1 }, limit: 1, select: 'createdAt plainBody body' },
44
- ) || [];
45
- if (!row) return null;
46
- const text = String(row.plainBody || row.body || '').trim();
47
- return { at: new Date(row.createdAt).toISOString(), text: text.length > EXCERPT_LENGTH ? `…${text.slice(-EXCERPT_LENGTH)}` : text };
48
- }
49
-
50
- async function recentExchange(code, now) {
51
- const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
52
- const [patient, own, ownToday] = await Promise.all([
53
- lastMessage(code, now, false),
54
- lastMessage(code, now, true),
55
- getMessages({ numero: code, from_me: true, origin: { $ne: 'instruction' }, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
56
- ]);
57
- return { patient, own, ownMessagesToday: (ownToday || []).length };
58
- }
59
-
60
- async function briefFor(code, now, checkIn) {
61
- const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
62
- return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
63
- }
64
-
65
- async function planCheckInDue({ code, reminderId, type, question = '', firstName = null, now = new Date() }) {
66
- let checkIn;
67
- if (type === 'contingencia') {
68
- const planId = String(reminderId).replace(/-patient$/, '');
69
- const net = (await readActiveNets(code)).find((candidate) => candidate.carePlan.planId === planId);
70
- if (!net) return { mode: 'stale', reason: 'net_not_active' };
71
- const urgency = escalationUrgencyOf(net);
72
- const netQuestion = net.patientReminder?.message || question;
73
- if (MANDATORY_URGENCIES.has(urgency)) {
74
- return { mode: 'mandatory', planId, instruction: mandatoryInstruction(firstName, netQuestion) };
75
- }
76
- checkIn = {
77
- type,
78
- question: netQuestion,
79
- concern: net.carePlan.concern,
80
- awaiting: net.carePlan.awaitingCharacterization,
81
- armedAt: net.carePlan.createdAt,
82
- urgency,
83
- };
84
- return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
85
- }
86
-
87
- const plan = await readPendingReminderForPatient({ code, reminderId });
88
- if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
89
- checkIn = { type, question: plan.message || question, concern: plan.windowReasoning, awaiting: null, armedAt: null, urgency: null };
90
- return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
91
- }
92
-
93
- module.exports = { checkInTriggeredBy, planCheckInDue };