@peopl-health/nexus 5.74.0-dev.15345 → 5.74.0-dev.15347

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 };
@@ -2,13 +2,12 @@ const moment = require('moment-timezone');
2
2
 
3
3
  const { isShadowRun } = require('../helpers/shadowHelper');
4
4
  const { dispatchReminder } = require('../services/reminderDispatchService');
5
- const { recordReminder, readPendingFollowUpsForPatient, cancelFollowUp, cancelPendingFollowUps } = require('../services/clinicalAirtableService');
5
+ const { recordReminder, readPendingFollowUpsForPatient, cancelFollowUp } = require('../services/clinicalAirtableService');
6
6
  const { isWithinTriageProtectionWindow } = require('../services/outreachSweepService');
7
7
  const { UTILITY_BASES, sanitizeVariable } = require('../services/outreachCarrierService');
8
8
  const { logger } = require('../../utils/logger');
9
9
  const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
10
10
  const { botIsPaused } = require('../../helpers/pausedThreadHelper');
11
- const { setCheckInsPausedUntil, checkInsPausedUntil } = require('../../services/threadService');
12
11
 
13
12
  const definition = {
14
13
  name: 'schedulePatientReminder',
@@ -32,8 +31,8 @@ const definition = {
32
31
  },
33
32
  reminder_action_type: {
34
33
  type: 'string',
35
- enum: ['create', 'update', 'cancel', 'pause_checkins'],
36
- description: '\'create\' = new reminder. \'update\' = modify an existing reminder (change date/time/description) — pass its id in `reminder_id`. \'cancel\' = retire a pending seguimiento that the conversation already answered or made unnecessary — pass its id in `reminder_id`; the date and description are ignored. \'pause_checkins\' = the patient asked to receive fewer messages: no seguimiento or contingency check-in reaches the patient until `reminder_date` (at most 30 days ahead; 14 days if the patient gave no date), pending seguimientos are retired, and the patient can still write at any time; put the request in `reminder_description`. stat/asap escalation check-ins and the patient\'s own medication, appointment or exam reminders are not paused.',
34
+ enum: ['create', 'update', 'cancel'],
35
+ description: '\'create\' = new reminder. \'update\' = modify an existing reminder (change date/time/description) — pass its id in `reminder_id`. \'cancel\' = retire a pending seguimiento that the conversation already answered or made unnecessary — pass its id in `reminder_id`; the date and description are ignored.',
37
36
  },
38
37
  reminder_id: {
39
38
  type: ['string', 'null'],
@@ -54,8 +53,6 @@ const REMINDER_TYPES = definition.parameters.properties.reminder_type.enum;
54
53
  const ACTION_TYPES = definition.parameters.properties.reminder_action_type.enum;
55
54
 
56
55
  const MAX_FOLLOW_UP_LEAD_HOURS = 48;
57
- const DEFAULT_PAUSE_DAYS = 14;
58
- const MAX_PAUSE_DAYS = 30;
59
56
  const ROUTINE_OUTREACH_START_HOUR = 11;
60
57
  const ROUTINE_OUTREACH_END_HOUR = 21;
61
58
  const PAUSED_ERROR = 'thread_paused — do not schedule a seguimiento in this turn.';
@@ -87,7 +84,6 @@ async function handler(args = {}, context = {}) {
87
84
 
88
85
  const requestedAction = (args?.reminder_action_type || '').toLowerCase();
89
86
  if (requestedAction === 'cancel') return await cancelSeguimiento(args, runtime);
90
- if (requestedAction === 'pause_checkins') return await pauseCheckIns(args, runtime);
91
87
 
92
88
  const reminderDate = (args?.reminder_date || '').trim();
93
89
  const description = sanitizeVariable(args?.reminder_description || '');
@@ -139,12 +135,6 @@ async function handler(args = {}, context = {}) {
139
135
  if (isRoutineOutreach && !isWithinHourWindow(fireMoment.toDate(), { timeZone, startHour: ROUTINE_OUTREACH_START_HOUR, endHour: ROUTINE_OUTREACH_END_HOUR })) {
140
136
  return JSON.stringify({ success: false, error: `routine outreach must go out between ${ROUTINE_OUTREACH_START_HOUR}:00 and ${ROUTINE_OUTREACH_END_HOUR}:00 patient time; choose a time in that range.`, data: {} });
141
137
  }
142
- if (isRoutineOutreach && runtime.patientCode) {
143
- const pausedUntil = await checkInsPausedUntil(runtime.patientCode);
144
- if (pausedUntil && fireMoment.toDate() < pausedUntil) {
145
- return JSON.stringify({ success: false, error: 'checkins_paused — the patient asked for fewer messages; do not schedule a seguimiento before the pause ends.', data: { paused_until: moment(pausedUntil).tz(timeZone).format('YYYY-MM-DDTHH:mm') } });
146
- }
147
- }
148
138
  if (isRoutineOutreach && actionType === 'create' && runtime.patientCode) {
149
139
  if (await botIsPaused(runtime.patientCode, { label: '[schedulePatientReminder]' })) {
150
140
  return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
@@ -236,30 +226,6 @@ async function handler(args = {}, context = {}) {
236
226
  }
237
227
  }
238
228
 
239
- async function pauseCheckIns(args, runtime) {
240
- const { patientCode, trace } = runtime;
241
- const now = moment.tz(DEFAULT_TIMEZONE);
242
- const rawDate = String(args?.reminder_date || '').trim();
243
- const until = rawDate
244
- ? moment.tz(rawDate, ['YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DD'], true, DEFAULT_TIMEZONE)
245
- : now.clone().add(DEFAULT_PAUSE_DAYS, 'days');
246
- if (!until.isValid() || !until.isAfter(now)) {
247
- return JSON.stringify({ success: false, error: 'pause_checkins reminder_date must be a future patient-local date (YYYY-MM-DDTHH:mm), or empty for 14 days.', data: {} });
248
- }
249
- if (until.isAfter(now.clone().add(MAX_PAUSE_DAYS, 'days'))) {
250
- return JSON.stringify({ success: false, error: `pause_checkins reminder_date must be at most ${MAX_PAUSE_DAYS} days ahead.`, data: {} });
251
- }
252
- if (patientCode && !isShadowRun()) {
253
- await setCheckInsPausedUntil(patientCode, until.toDate());
254
- if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused' })) {
255
- logger.warn('[schedulePatientReminder] pending seguimientos were not retired on pause', { patientCode });
256
- }
257
- }
258
- const existing = Array.isArray(trace.signals?.reminderIntents) ? trace.signals.reminderIntents : [];
259
- trace.setSignals({ reminderIntents: [...existing, { reminderId: null, reminderType: 'seguimiento', actionType: 'pause_checkins', pausedUntil: until.toISOString(), channel: 'whatsapp' }] });
260
- return JSON.stringify({ success: true, data: { action_type: 'pause_checkins', paused_until: until.format('YYYY-MM-DDTHH:mm'), time_zone: DEFAULT_TIMEZONE } });
261
- }
262
-
263
229
  async function cancelSeguimiento(args, runtime) {
264
230
  const reminderId = typeof args?.reminder_id === 'string' ? args.reminder_id.trim() : '';
265
231
  if (!reminderId) {
@@ -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
  });
@@ -118,6 +117,7 @@ const COMPUTED_FIELD_TYPES = Object.freeze([
118
117
  'createdTime', 'createdBy', 'autoNumber', 'button', 'aiText',
119
118
  ]);
120
119
  const ARCHIVE_LEASE_MS = 15 * 60 * 1000;
120
+ const ARCHIVE_LEASE_RENEW_MS = 60 * 1000;
121
121
  const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
122
122
 
123
123
  module.exports = {
@@ -126,6 +126,7 @@ module.exports = {
126
126
  MIN_ARCHIVE_AGE_DAYS,
127
127
  ARCHIVE_BATCH_SIZE,
128
128
  ARCHIVE_LEASE_MS,
129
+ ARCHIVE_LEASE_RENEW_MS,
129
130
  ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
130
131
  COMPUTED_FIELD_TYPES,
131
132
  GROUP_LINKS,
@@ -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,63 +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 this._fireCheckInNet(code, plan.planId, reminderId);
1137
- await completeSendClaim(claim.claimId);
1138
- return { decision: 'skipped', holdReason: plan.reason, sent: false };
1139
- }
1140
- dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1141
- if (!dispatched) {
1142
- await completeSendClaim(claim.claimId);
1143
- return { decision: 'skipped', holdReason: 'row_not_active', sent: false };
1144
- }
1145
- await this._fireCheckInNet(code, plan.planId, reminderId);
1146
-
1147
- const triggeredBy = checkInTriggeredBy(reminderId);
1148
- let result;
1149
- if (plan.mode === 'mandatory') {
1150
- const { outcome } = await this.processInstruction(code, plan.instruction, 'developer', { triggeredBy });
1151
- const sent = outcome === 'sent' || outcome === 'unknown';
1152
- result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
1153
- } else {
1154
- const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName, replyToContact: true });
1155
- result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
1156
- }
1157
-
1158
- const settled = result.sent
1159
- ? await settleCheckInRow({ code, reminderId, sent: true, onlyIfDispatched: true })
1160
- : await settleCheckInRow({ code, reminderId, reason: result.holdReason === 'turn_not_run' ? 'failed' : `held_${result.holdReason || result.decision}`, onlyIfDispatched: true });
1161
- if (!settled) logger.warn('[processCheckInDue] check-in row was not settled after the turn', { reminderId, sent: result.sent });
1162
- await completeSendClaim(claim.claimId);
1163
- return result;
1164
- } catch (error) {
1165
- logger.error('[processCheckInDue] check-in turn failed', { reminderId, error: error.message });
1166
- if (dispatched) await settleCheckInRow({ code, reminderId, reason: 'failed', onlyIfDispatched: true });
1167
- await releaseSendClaim(claim.claimId);
1168
- throw error;
1169
- }
1170
- }
1171
-
1172
- async _fireCheckInNet(code, planId, reminderId) {
1173
- if (!planId) return;
1174
- try {
1175
- const fired = await applyContingencyEvent({ patientCode: code, planId, stage: 'patient', event: 'fired' });
1176
- if (!fired?.applied) logger.info('[processCheckInDue] net was not fired', { reminderId, planId, reason: fired?.reason || null });
1177
- } catch (error) {
1178
- logger.error('[processCheckInDue] net fire failed; team stage not armed', { reminderId, planId, teamStageArmed: false, error: error.message });
1179
- }
1180
- }
1181
-
1182
1122
  async _retireSkippedFollowUp(code, reminderId, holdReason) {
1183
1123
  const retired = await cancelFollowUp({ code, reminderId, reason: `skipped_${holdReason}` });
1184
1124
  if (!retired) logger.warn('[processScheduledFollowUp] skipped follow-up was not stood down', { reminderId, holdReason });
@@ -1408,10 +1348,6 @@ const processOutreach = async (code, options) => {
1408
1348
  return await requireDefaultInstance().processOutreach(code, options);
1409
1349
  };
1410
1350
 
1411
- const processCheckInDue = async (code, options) => {
1412
- return await requireDefaultInstance().processCheckInDue(code, options);
1413
- };
1414
-
1415
1351
  const processScheduledFollowUp = async (code, options) => {
1416
1352
  return await requireDefaultInstance().processScheduledFollowUp(code, options);
1417
1353
  };
@@ -1420,8 +1356,6 @@ const processSystemMessage = async (code, messages, role, options) => {
1420
1356
  return await requireDefaultInstance().processSystemMessage(code, messages, role, options);
1421
1357
  };
1422
1358
 
1423
- const isDraining = () => Boolean(getDefaultInstance()?.getBatchingManager()?.isDraining());
1424
-
1425
1359
  const getEventBus = () => getDefaultInstance()?.getEventBus();
1426
1360
 
1427
1361
  const getPhiProcessor = () => getDefaultInstance()?.getPhiProcessor();
@@ -1435,10 +1369,8 @@ module.exports = {
1435
1369
  scheduleTemplateApproval,
1436
1370
  processInstruction,
1437
1371
  processOutreach,
1438
- processCheckInDue,
1439
1372
  processScheduledFollowUp,
1440
1373
  processSystemMessage,
1441
- isDraining,
1442
1374
  setDefaultInstance,
1443
1375
  getDefaultInstance,
1444
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 {
@@ -11,7 +11,6 @@ const threadSchema = new mongoose.Schema({
11
11
  nombre: { type: String, default: null },
12
12
  stopped: { type: Boolean, default: false },
13
13
  outreachOptOut: { type: Boolean, default: false },
14
- checkInsPausedUntil: { type: Date, default: null },
15
14
  pausedAt: { type: Date, default: null },
16
15
  deceasedAt: { type: Date, default: null },
17
16
  programStatusBeforeDeath: { type: String, default: null },
@@ -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,
@@ -4,7 +4,7 @@ const { v4: uuidv4 } = require('uuid');
4
4
  const runtimeConfig = require('../config/runtimeConfig');
5
5
  const { uploadBufferToS3 } = require('../config/awsConfig');
6
6
  const {
7
- ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
7
+ ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ARCHIVE_LEASE_RENEW_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_FIELDS,
8
8
  } = require('../config/airtableArchiveConfig');
9
9
  const { logger } = require('../utils/logger');
10
10
  const { stableStringify } = require('../utils/jsonUtils');
@@ -15,7 +15,7 @@ const {
15
15
  const { createdBefore, createdSince } = require('../helpers/airtableFormulaHelper');
16
16
  const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
17
17
 
18
- const { getRecordsWithMetadata, getBaseSchema } = require('./airtableService');
18
+ const { scanRecordPages, getBaseSchema } = require('./airtableService');
19
19
  const { planArchive, resolveArchiveSchema } = require('./airtableArchivePlanService');
20
20
 
21
21
  const DUPLICATE_KEY_ERROR = 11000;
@@ -38,7 +38,7 @@ async function readArchiveSchema(baseId) {
38
38
  return schema;
39
39
  }
40
40
 
41
- // Records come back keyed by name, so a rename during the scans would hide links from the planner.
41
+ // A deleted or retyped field during the scans would read as empty links to the planner.
42
42
  async function assertSchemaUnchanged(baseId, schema) {
43
43
  const current = await readArchiveSchema(baseId);
44
44
  const changed = schema.snapshot.filter((table, i) => stableStringify(table) !== stableStringify(current.snapshot[i])).map((table) => table.id);
@@ -48,23 +48,49 @@ async function assertSchemaUnchanged(baseId, schema) {
48
48
  }
49
49
  }
50
50
 
51
- async function scanOldRecords(baseId, cutoff, runId, schema) {
51
+ // Records are read by field id and named from the run's snapshot, so a rename mid-scan cannot change what the planner sees.
52
+ async function scanTable({ baseId, tableId, filterByFormula, fieldIds, schema, lease }) {
53
+ const names = new Map(schema.snapshot.find((table) => table.id === tableId).fields.map((field) => [field.id, field.name]));
54
+ const records = [];
55
+ await scanRecordPages(baseId, tableId, {
56
+ filterByFormula,
57
+ fieldIds,
58
+ onPage: async (page) => {
59
+ for (const record of page) {
60
+ const fields = {};
61
+ for (const [fieldId, value] of Object.entries(record.fields)) {
62
+ if (!names.has(fieldId)) {
63
+ logger.error('[airtableArchive] Scanned a field missing from the run schema', { baseId, tableId, fieldId });
64
+ throw archiveError('archive_schema_mismatch');
65
+ }
66
+ fields[names.get(fieldId)] = value;
67
+ }
68
+ records.push({ id: record.id, createdTime: record.createdTime, fields });
69
+ }
70
+ await lease.renewIfDue();
71
+ },
72
+ onRestart: () => { records.length = 0; },
73
+ });
74
+ await lease.renew();
75
+ return records;
76
+ }
77
+
78
+ async function scanOldRecords(baseId, cutoff, schema, lease) {
52
79
  const recordsByTable = {};
53
80
  for (const [key, tableId] of Object.entries(ARCHIVE_TABLES)) {
54
- recordsByTable[schema.tables[key]] = await getRecordsWithMetadata(baseId, tableId, createdBefore(cutoff));
55
- await renewLease(runId);
81
+ recordsByTable[schema.tables[key]] = await scanTable({ baseId, tableId, filterByFormula: createdBefore(cutoff), schema, lease });
56
82
  }
57
83
  return recordsByTable;
58
84
  }
59
85
 
60
- async function scanPatientsWithRecent(baseId, cutoff, runId, schema) {
86
+ async function scanPatientsWithRecent(baseId, cutoff, schema, lease) {
61
87
  const patientsWithRecent = {};
62
88
  for (const key of ['QUESTIONNAIRES', 'TRIAGES']) {
63
89
  const table = schema.tables[key];
64
90
  const patientField = schema.patientFields[table];
65
- const records = await getRecordsWithMetadata(baseId, ARCHIVE_TABLES[key], createdSince(cutoff), [patientField]);
66
- patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields?.[patientField] || []));
67
- await renewLease(runId);
91
+ const tableId = ARCHIVE_TABLES[key];
92
+ const records = await scanTable({ baseId, tableId, filterByFormula: createdSince(cutoff), fieldIds: [PATIENT_FIELDS[tableId]], schema, lease });
93
+ patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields[patientField] || []));
68
94
  }
69
95
  return patientsWithRecent;
70
96
  }
@@ -118,6 +144,21 @@ async function renewLease(runId) {
118
144
  if (!result?.matchedCount) throw archiveError('archive_lease_lost');
119
145
  }
120
146
 
147
+ // Renews at most once per interval, so a scan of hundreds of pages costs a handful of writes.
148
+ function leaseFor(runId) {
149
+ let renewedAt = Date.now();
150
+ const renew = async () => {
151
+ await renewLease(runId);
152
+ renewedAt = Date.now();
153
+ };
154
+ return {
155
+ renew,
156
+ renewIfDue: async () => {
157
+ if (Date.now() - renewedAt >= ARCHIVE_LEASE_RENEW_MS) await renew();
158
+ },
159
+ };
160
+ }
161
+
121
162
  async function rehostAttachments({ baseId, tableId, recordId, attachments, alreadyHosted }) {
122
163
  if (!attachments.length) return [];
123
164
  const bucket = runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET');
@@ -241,8 +282,9 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
241
282
  try {
242
283
  const schema = await readArchiveSchema(baseId);
243
284
  counts = Object.fromEntries(Object.values(schema.tables).map((table) => [table, emptyCounts()]));
244
- const recordsByTable = await scanOldRecords(baseId, cutoff, runId, schema);
245
- const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, runId, schema);
285
+ const lease = leaseFor(runId);
286
+ const recordsByTable = await scanOldRecords(baseId, cutoff, schema, lease);
287
+ const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, schema, lease);
246
288
  await assertSchemaUnchanged(baseId, schema);
247
289
  const plan = planArchive({ recordsByTable, patientsWithRecent, schema });
248
290
 
@@ -271,7 +313,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
271
313
  logger.info('[airtableArchive] Run finished', summary);
272
314
  return summary;
273
315
  } catch (error) {
274
- const errorCode = error?.code && typeof error.code === 'string' ? error.code : 'UNKNOWN';
316
+ const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
275
317
  await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
276
318
  logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
277
319
  throw error;
@@ -14,6 +14,10 @@ const MAX_ATTEMPTS = 3;
14
14
  const AIRTABLE_API_URL = 'https://api.airtable.com/v0';
15
15
  const AXIOS_TIMEOUT_CODE = 'ECONNABORTED';
16
16
  const RETRY_BASE_DELAY_MS = 1000;
17
+ const SCAN_PAGE_SIZE = 100;
18
+ const SCAN_PAGE_INTERVAL_MS = 400;
19
+ const ITERATOR_EXPIRED = 'LIST_RECORDS_ITERATOR_NOT_AVAILABLE';
20
+ const MAX_SCAN_RESTARTS = 1;
17
21
 
18
22
  function isPermanentAirtableError(error) {
19
23
  const status = error?.statusCode;
@@ -127,28 +131,14 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
127
131
  }
128
132
  }
129
133
 
130
- async function getRecordsWithMetadata(baseID, tableName, filter, fields) {
131
- try {
132
- const selectOptions = { filterByFormula: filter };
133
- if (fields && fields.length) selectOptions.fields = fields;
134
- return await withAirtableRetry(
135
- () => collectRecords(getBase(baseID)(tableName).select(selectOptions), (r) => ({ id: r.id, createdTime: r._rawJson?.createdTime, fields: r.fields })),
136
- 'getRecordsWithMetadata'
137
- );
138
- } catch (error) {
139
- logger.error('[getRecordsWithMetadata] Failed', safeAirtableFailure(error));
140
- throw error;
141
- }
142
- }
143
-
144
- // Needs the schema.bases:read scope; returns [{ id, name, fields: [{ id, name, type }] }] per table.
145
- async function getBaseSchema(baseID) {
134
+ async function airtableRequest(method, path, body, label) {
146
135
  const apiKey = getApiKey();
147
136
  if (!apiKey) throw new Error('Airtable not configured. Set AIRTABLE_API_KEY');
148
137
  try {
149
- const data = await withAirtableRetry(async () => {
138
+ return await withAirtableRetry(async () => {
150
139
  try {
151
- const response = await axios.get(`${AIRTABLE_API_URL}/meta/bases/${baseID}/tables`, {
140
+ const response = await axios.request({
141
+ method, url: `${AIRTABLE_API_URL}/${path}`, data: body,
152
142
  headers: { Authorization: `Bearer ${apiKey}` },
153
143
  timeout: getRequestTimeoutMs(),
154
144
  });
@@ -156,14 +146,47 @@ async function getBaseSchema(baseID) {
156
146
  } catch (error) {
157
147
  throw toAirtableHttpError(error);
158
148
  }
159
- }, 'getBaseSchema');
160
- return data.tables;
149
+ }, label);
161
150
  } catch (error) {
162
- logger.error('[getBaseSchema] Failed', safeAirtableFailure(error));
151
+ logger.error(`[${label}] Failed`, { ...safeAirtableFailure(error), airtableError: error.error });
163
152
  throw error;
164
153
  }
165
154
  }
166
155
 
156
+ // Records keyed by field id. A failure retries its page, not the scan; an expired iterator restarts it after onRestart.
157
+ async function scanRecordPages(baseID, tableId, { filterByFormula, fieldIds, onPage, onRestart }) {
158
+ let offset;
159
+ let restarts = 0;
160
+ for (;;) {
161
+ const started = Date.now();
162
+ let data;
163
+ try {
164
+ data = await airtableRequest('post', `${baseID}/${tableId}/listRecords`, {
165
+ filterByFormula, pageSize: SCAN_PAGE_SIZE, returnFieldsByFieldId: true,
166
+ ...(fieldIds?.length ? { fields: fieldIds } : {}), ...(offset ? { offset } : {}),
167
+ }, 'scanRecordPages');
168
+ } catch (error) {
169
+ if (error.error !== ITERATOR_EXPIRED || !offset || restarts >= MAX_SCAN_RESTARTS) throw error;
170
+ restarts += 1;
171
+ offset = undefined;
172
+ logger.warn('[scanRecordPages] Iterator expired, restarting the scan', { baseID, tableId });
173
+ await onRestart();
174
+ continue;
175
+ }
176
+ await onPage((data.records || []).map((r) => ({ id: r.id, createdTime: r.createdTime, fields: r.fields || {} })));
177
+ offset = data.offset;
178
+ if (!offset) return;
179
+ const wait = SCAN_PAGE_INTERVAL_MS - (Date.now() - started);
180
+ if (wait > 0) await delay(wait);
181
+ }
182
+ }
183
+
184
+ // Needs the schema.bases:read scope; returns [{ id, name, fields: [{ id, name, type }] }] per table.
185
+ async function getBaseSchema(baseID) {
186
+ const data = await airtableRequest('get', `meta/bases/${baseID}/tables`, undefined, 'getBaseSchema');
187
+ return data.tables;
188
+ }
189
+
167
190
  async function updateRecordByFilter(baseID, tableName, filter, updateFields, context = null) {
168
191
  if (isShadowRun() || isBenchMode(context)) {
169
192
  logger.info(`[updateRecordByFilter:${isShadowRun() ? 'shadow' : 'bench'}] Suppressed`, { tableName, filter, code: context });
@@ -297,7 +320,7 @@ module.exports = {
297
320
  addRecord,
298
321
  getRecords,
299
322
  getRecordByFilter,
300
- getRecordsWithMetadata,
323
+ scanRecordPages,
301
324
  getBaseSchema,
302
325
  updateRecordByFilter,
303
326
  addLinkedRecord,
@@ -51,13 +51,6 @@ const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } =
51
51
 
52
52
  const setThreadDoNotAlert = async (code, doNotAlert, through = null) => Thread.updateMany({ code }, { $set: { doNotAlertThrough: doNotAlert ? (through || new Date()) : null } });
53
53
 
54
- const setCheckInsPausedUntil = async (code, until) => Thread.updateMany({ code }, { $set: { checkInsPausedUntil: until } });
55
-
56
- const checkInsPausedUntil = async (code, now = new Date()) => {
57
- const thread = await Thread.findOne({ code, checkInsPausedUntil: { $gt: now } }).select('checkInsPausedUntil').lean();
58
- return thread?.checkInsPausedUntil || null;
59
- };
60
-
61
54
  const setThreadPromptId = async (code, promptId) => {
62
55
  const updateFields = {};
63
56
  Thread.setAssistantId(updateFields, promptId);
@@ -117,7 +110,5 @@ module.exports = {
117
110
  ensureThreadExists,
118
111
  switchThreadStoppedStatus,
119
112
  setThreadDoNotAlert,
120
- setThreadPromptId,
121
- setCheckInsPausedUntil,
122
- checkInsPausedUntil
113
+ setThreadPromptId
123
114
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.74.0-dev.15345",
3
+ "version": "5.74.0-dev.15347",
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,96 +0,0 @@
1
- const moment = require('moment-timezone');
2
-
3
- const { getMessages } = require('../../services/messageService');
4
- const { checkInsPausedUntil } = require('../../services/threadService');
5
- const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
6
- const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
7
- const { readPendingReminderForPatient } = require('./clinicalAirtableService');
8
-
9
- const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
10
- const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
11
- const TRIGGERED_BY_PREFIX = 'send_reminder:';
12
- const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
13
- const EXCERPT_LENGTH = 160;
14
-
15
- const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
16
-
17
- function mandatoryInstruction(firstName, question) {
18
- 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}".
19
-
20
- 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.
21
-
22
- 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.`;
23
- }
24
-
25
- async function recentCheckIns(code, now) {
26
- const rows = await getMessages(
27
- {
28
- numero: code,
29
- from_me: true,
30
- createdAt: { $gte: new Date(now.getTime() - RECENT_CHECK_IN_WINDOW_MS) },
31
- $or: [
32
- { origin: 'assistant', triggeredBy: { $regex: `^(?:${TRIGGERED_BY_PREFIX}|seguimiento:|followup_)` } },
33
- { origin: 'instruction', triggeredBy: null, message_id: { $regex: '^instruction_' }, 'raw.gated': { $ne: true }, plainBody: { $regex: NET_INSTRUCTION_MARKER } },
34
- ],
35
- },
36
- { sort: { createdAt: 1 }, select: 'createdAt' },
37
- );
38
- return (rows || []).map((row) => new Date(row.createdAt).toISOString());
39
- }
40
-
41
- async function lastMessage(code, now, fromMe) {
42
- const [row] = await getMessages(
43
- { numero: code, from_me: fromMe, origin: { $ne: 'instruction' }, createdAt: { $lt: now } },
44
- { sort: { createdAt: -1 }, limit: 1, select: 'createdAt plainBody body' },
45
- ) || [];
46
- if (!row) return null;
47
- const text = String(row.plainBody || row.body || '').trim();
48
- return { at: new Date(row.createdAt).toISOString(), text: text.length > EXCERPT_LENGTH ? `…${text.slice(-EXCERPT_LENGTH)}` : text };
49
- }
50
-
51
- async function recentExchange(code, now) {
52
- const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
53
- const [patient, own, ownToday] = await Promise.all([
54
- lastMessage(code, now, false),
55
- lastMessage(code, now, true),
56
- getMessages({ numero: code, from_me: true, origin: { $ne: 'instruction' }, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
57
- ]);
58
- return { patient, own, ownMessagesToday: (ownToday || []).length };
59
- }
60
-
61
- async function briefFor(code, now, checkIn) {
62
- const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
63
- return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
64
- }
65
-
66
- async function planCheckInDue({ code, reminderId, type, question = '', firstName = null, now = new Date() }) {
67
- let checkIn;
68
- if (type === 'contingencia') {
69
- const planId = String(reminderId).replace(/-patient$/, '');
70
- const net = (await readActiveNets(code)).find((candidate) => candidate.carePlan.planId === planId);
71
- if (!net) return { mode: 'stale', reason: 'net_not_active' };
72
- const urgency = escalationUrgencyOf(net);
73
- const netQuestion = net.patientReminder?.message || question;
74
- if (MANDATORY_URGENCIES.has(urgency)) {
75
- return { mode: 'mandatory', planId, instruction: mandatoryInstruction(firstName, netQuestion) };
76
- }
77
- if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused', planId };
78
- checkIn = {
79
- type,
80
- question: netQuestion,
81
- concern: net.carePlan.concern,
82
- awaiting: net.carePlan.awaitingCharacterization,
83
- armedAt: net.carePlan.createdAt,
84
- urgency,
85
- };
86
- return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
87
- }
88
-
89
- const plan = await readPendingReminderForPatient({ code, reminderId });
90
- if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
91
- if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
92
- checkIn = { type, question: plan.message || question, concern: plan.windowReasoning, awaiting: null, armedAt: null, urgency: null };
93
- return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
94
- }
95
-
96
- module.exports = { checkInTriggeredBy, planCheckInDue };