@peopl-health/nexus 5.75.6 → 5.75.8

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.
@@ -434,9 +434,12 @@ class BaseLLMProvider {
434
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.',
435
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.',
436
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.',
437
+ exchange?.sessionOpen === false
438
+ ? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo diciendo en pocas palabras qué retomas («te había preguntado por…»).'
439
+ : 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego di en pocas palabras qué retomas («te había preguntado por…»).',
440
+ 'Haz una sola pregunta por lo que sigue faltando de lo que esperabas saber. Háblale directo a quien lleva la conversación, de tú o de usted, como en la conversación; nunca hables en tercera persona de quien te está leyendo.',
438
441
  '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.',
442
+ 'Breve, sin listas de señales de alarma y sin mencionar recordatorios, planes ni seguimientos programados.',
440
443
  );
441
444
  return [{ role: 'developer', content: parts.join('\n') }];
442
445
  }
@@ -1,6 +1,8 @@
1
1
  const moment = require('moment-timezone');
2
2
 
3
3
  const { getMessages } = require('../../services/messageService');
4
+ const { replyContactFor } = require('../../helpers/caregiverHelper');
5
+ const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
4
6
  const { checkInsPausedUntil } = require('../../services/threadService');
5
7
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
6
8
  const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
@@ -12,7 +14,6 @@ const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
12
14
  const TRIGGERED_BY_PREFIX = 'send_reminder:';
13
15
  const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
14
16
  const EXCERPT_LENGTH = 160;
15
- const OWN_ORIGINS = ['assistant', 'whatsapp_platform'];
16
17
  const LAST_MESSAGE_SCAN = 5;
17
18
 
18
19
  const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
@@ -41,14 +42,13 @@ async function recentCheckIns(code, now) {
41
42
  return (rows || []).map((row) => new Date(row.createdAt).toISOString());
42
43
  }
43
44
 
44
- const originFilter = (fromMe) => (fromMe ? { $in: OWN_ORIGINS } : { $ne: 'instruction' });
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 }] };
45
+ // Templates (cards, forms) and automations (the triage ack) would hide what the agent or the team last wrote; staff sign with their email.
46
+ const OWN_WRITTEN = { $or: [{ origin: 'assistant' }, { origin: 'whatsapp_platform', content_sid: null, triggeredBy: { $regex: '@' } }] };
47
+ const PATIENT_WRITTEN = { origin: { $ne: 'instruction' } };
48
48
 
49
49
  async function lastMessage(code, now, fromMe) {
50
50
  const rows = await getMessages(
51
- { numero: code, from_me: fromMe, ...(fromMe ? OWN_CONVERSATION : { origin: originFilter(false) }), createdAt: { $lt: now } },
51
+ { numero: code, from_me: fromMe, ...(fromMe ? OWN_WRITTEN : PATIENT_WRITTEN), createdAt: { $lt: now } },
52
52
  { sort: { createdAt: -1 }, limit: LAST_MESSAGE_SCAN, select: 'createdAt plainBody body' },
53
53
  ) || [];
54
54
  const row = rows.find((candidate) => String(candidate.plainBody || candidate.body || '').trim());
@@ -59,12 +59,13 @@ async function lastMessage(code, now, fromMe) {
59
59
 
60
60
  async function recentExchange(code, now) {
61
61
  const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
62
- const [patient, own, ownToday] = await Promise.all([
62
+ const [patient, own, ownToday, sessionOpen] = await Promise.all([
63
63
  lastMessage(code, now, false),
64
64
  lastMessage(code, now, true),
65
- getMessages({ numero: code, from_me: true, origin: originFilter(true), createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
65
+ getMessages({ numero: code, from_me: true, ...OWN_WRITTEN, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
66
+ replyContactFor(code).then((contact) => isWithin24HourWindow(code, { contactCode: contact?.contactCode || null })),
66
67
  ]);
67
- return { patient, own, ownMessagesToday: (ownToday || []).length };
68
+ return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
68
69
  }
69
70
 
70
71
  async function briefFor(code, now, checkIn) {
@@ -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, 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.`,
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 in the conversation; never about the reader 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
@@ -470,7 +470,7 @@ declare module '@peopl-health/nexus' {
470
470
  lastOutreach?: string | null;
471
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
- exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number } | null;
473
+ exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
474
474
  asOf?: string | null;
475
475
  }
476
476
 
@@ -171,13 +171,20 @@ function planArchive({ recordsByTable, patientsWithRecent = {}, schema }) {
171
171
  continue;
172
172
  }
173
173
  const patientEntry = records.map(({ id }) => entries.get(id)).find(patientOf);
174
+ const patient = {
175
+ recordId: patientEntry ? patientOf(patientEntry) : null,
176
+ whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
177
+ };
178
+ // A group can join two patients' records through a shared questionnaire; each record keeps its own patient.
179
+ const patientFor = (entry) => {
180
+ const own = patientOf(entry);
181
+ if (!own || own === patient.recordId) return patient;
182
+ return { recordId: own, whatsappId: firstString(entry.record.fields?.[schema.whatsappFields[entry.table]]) };
183
+ };
174
184
  eligible.push({
175
185
  groupId: groupIdOf(records.map(({ id }) => id)),
176
- patient: {
177
- recordId: patientEntry ? patientOf(patientEntry) : null,
178
- whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
179
- },
180
- records,
186
+ patient,
187
+ records: records.map((record) => ({ ...record, patient: patientFor(entries.get(record.id)) })),
181
188
  });
182
189
  }
183
190
 
@@ -237,7 +237,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
237
237
 
238
238
  const expected = new Map();
239
239
  const ops = [];
240
- for (const { table, record: scanned, group } of batch) {
240
+ for (const { table, record: scanned, group, patient } of batch) {
241
241
  if (changedGroups.has(group.groupId)) {
242
242
  counts[table].failed += 1;
243
243
  logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
@@ -249,7 +249,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
249
249
  const fieldsHash = hashFields(normalized);
250
250
  const sourceHash = hashFields(normalized, schema.computed.get(table));
251
251
  const tableId = schema.tableIds[table];
252
- const placement = placementOf(table, group.groupId, group.patient, record.createdTime);
252
+ const placement = placementOf(table, group.groupId, patient, record.createdTime);
253
253
  const previous = existing.get(_id);
254
254
  const previousIntact = previous?.tableId && previous.schemaId && hashFields(previous.fields) === previous.fieldsHash;
255
255
  if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.tableName, previous.groupId, previous.patient, previous.createdTime) === placement) {
@@ -265,7 +265,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
265
265
  update: {
266
266
  $set: {
267
267
  baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
268
- fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, schemaId, attachments: hosted,
268
+ fields: normalized, fieldsHash, sourceHash, patient, groupId: group.groupId, schemaId, attachments: hosted,
269
269
  schemaVersion: ARCHIVE_SCHEMA_VERSION,
270
270
  },
271
271
  $setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
@@ -337,7 +337,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
337
337
 
338
338
  Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
339
339
  const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
340
- const work = plan.eligible.map((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
340
+ const work = plan.eligible.map((group) => group.records.map(({ table, id, patient }) => ({ table, record: recordsById.get(id), group, patient })));
341
341
  work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
342
342
 
343
343
  if (mode === 'copy' && work.length) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.75.6",
3
+ "version": "5.75.8",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",