@peopl-health/nexus 5.75.4 → 5.75.6

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.
@@ -401,7 +401,9 @@ class BaseLLMProvider {
401
401
  };
402
402
  const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
403
403
  const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
404
+ const self = checkIn.reminderId ? `${checkIn.reminderId}${checkIn.dueAt ? `, programado para ${local(checkIn.dueAt)}` : ''}` : null;
404
405
  const pending = lines([
406
+ ['este check-in', self],
405
407
  ['lo que querías preguntarle', checkIn.question],
406
408
  ['por qué quedó abierto', checkIn.concern],
407
409
  ['qué dato esperabas', checkIn.awaiting],
@@ -416,7 +418,7 @@ class BaseLLMProvider {
416
418
  const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
417
419
  const parts = [
418
420
  '[CHECK-IN QUE VENCE (prioritario) para este turno]',
419
- '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.',
421
+ 'Venció el plazo para retomar algo pendiente con esta persona. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a escribirle o si ya no hace falta.',
420
422
  '', '## Qué quedó pendiente', ...pending,
421
423
  ];
422
424
  if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
@@ -424,14 +426,17 @@ class BaseLLMProvider {
424
426
  '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
425
427
  '',
426
428
  `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
429
+ '- Este check-in es el seguimiento que está venciendo ahora, aunque lo veas programado unos minutos más tarde: ya no está pendiente y no se puede actualizar. Si decides esperar, programa uno nuevo.',
427
430
  '- 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.',
428
- '- 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.',
431
+ '- Si tu último mensaje ya le hace esta pregunta o la cubre, y hoy estuvo en la conversación 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.',
429
432
  '- 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.',
430
- '- 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.',
433
+ '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que 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.',
431
434
  '- 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.',
432
435
  '- 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.',
433
- '- 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ó.',
434
- '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.',
436
+ '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que contó o acordó.',
437
+ 'Si escribes, le llega como un mensaje normal, no dentro de una plantilla. Si llevan horas sin hablar, ábrelo con un saludo breve y natural con su nombre, según la hora del día; luego di en pocas palabras qué retomas («te había preguntado por…») y pregunta lo que sigue faltando de lo que esperabas saber. Háblale directo a quien lleva la conversación, de tú o de usted como ahí; si es el propio paciente, nunca te refieras a él en tercera persona.',
438
+ 'No le comentes como novedad algo que no te dijo en el chat: sus respuestas del cuestionario las conoces tú, no son algo que te acaba de contar. No repitas lo que ya le dijiste (por ejemplo, que el equipo ya tiene el aviso) ni des por hecho detalles que no te dio.',
439
+ 'Breve, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
435
440
  );
436
441
  return [{ role: 'developer', content: parts.join('\n') }];
437
442
  }
@@ -43,9 +43,12 @@ async function recentCheckIns(code, now) {
43
43
 
44
44
  const originFilter = (fromMe) => (fromMe ? { $in: OWN_ORIGINS } : { $ne: 'instruction' });
45
45
 
46
+ // Templates (cards, forms) and automations (the triage ack) would hide the question the agent last asked.
47
+ const OWN_CONVERSATION = { $or: [{ origin: 'assistant' }, { origin: 'whatsapp_platform', content_sid: null, triggeredBy: null }] };
48
+
46
49
  async function lastMessage(code, now, fromMe) {
47
50
  const rows = await getMessages(
48
- { numero: code, from_me: fromMe, origin: originFilter(fromMe), createdAt: { $lt: now } },
51
+ { numero: code, from_me: fromMe, ...(fromMe ? OWN_CONVERSATION : { origin: originFilter(false) }), createdAt: { $lt: now } },
49
52
  { sort: { createdAt: -1 }, limit: LAST_MESSAGE_SCAN, select: 'createdAt plainBody body' },
50
53
  ) || [];
51
54
  const row = rows.find((candidate) => String(candidate.plainBody || candidate.body || '').trim());
@@ -96,6 +99,8 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
96
99
  if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused', planId };
97
100
  checkIn = {
98
101
  type,
102
+ reminderId,
103
+ dueAt: null,
99
104
  question: netQuestion,
100
105
  concern: net.carePlan.concern,
101
106
  awaiting: net.carePlan.awaitingCharacterization,
@@ -111,6 +116,8 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
111
116
  if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
112
117
  checkIn = {
113
118
  type,
119
+ reminderId,
120
+ dueAt: plan.fireAt || null,
114
121
  question: plan.message || question,
115
122
  concern: plan.windowReasoning,
116
123
  awaiting: null,
@@ -58,7 +58,7 @@ const definition = {
58
58
  },
59
59
  patient_followup_reminder: {
60
60
  type: 'object',
61
- description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, in the patient's voice and language, about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
61
+ description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, addressed directly to whoever is in the conversation, in second person and in their language — tú or usted as there; when that is the patient, never about them in third person — about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
62
62
  },
63
63
  },
64
64
  required: ['action'],
package/lib/index.d.ts CHANGED
@@ -468,7 +468,7 @@ declare module '@peopl-health/nexus' {
468
468
  lastInboundAt?: string | null;
469
469
  lastOutboundAt?: string | null;
470
470
  lastOutreach?: string | null;
471
- checkIn?: { type: string; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
471
+ checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
472
472
  recentCheckIns?: string[];
473
473
  exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number } | null;
474
474
  asOf?: string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.75.4",
3
+ "version": "5.75.6",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",