@peopl-health/nexus 5.75.6 → 5.76.0-dev.15838

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'],
@@ -28,7 +28,13 @@ const hashFields = (fields, skip = new Set()) => crypto.createHash('sha256')
28
28
  const schemaSnapshotId = (baseId, snapshot) => `${baseId}:${crypto.createHash('sha256').update(stableStringify(snapshot)).digest('hex').slice(0, 24)}`;
29
29
 
30
30
  // Same shape as airtableService.getRecordByFilter(..., withRecordId = true), flagged as archived.
31
- const toAirtableRow = (doc) => ({ ...doc.fields, _recordId: doc.recordId, _createdTime: new Date(doc.createdTime).toISOString(), _archived: true });
31
+ const toAirtableRow = (doc) => ({
32
+ ...doc.fields,
33
+ _recordId: doc.recordId,
34
+ _createdTime: new Date(doc.createdTime).toISOString(),
35
+ _archived: true,
36
+ ...(doc.attachments ? { _attachments: doc.attachments } : {}),
37
+ });
32
38
 
33
39
  // Union by record id, live row winning; archived rows are appended, so callers sort after merging.
34
40
  function mergeArchivedRows(liveRows = [], archivedRows = []) {
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
 
@@ -42,6 +42,7 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
42
42
 
43
43
  airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.whatsappId': 1, createdTime: -1 });
44
44
  airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.recordId': 1, createdTime: -1 });
45
+ airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, createdTime: -1 });
45
46
  airtableArchiveRecordSchema.index({ baseId: 1, groupId: 1 });
46
47
  airtableArchiveRecordSchema.index({ runId: 1 });
47
48
 
@@ -1,25 +1,50 @@
1
+ const { getModelDatabase } = require('../config/mongoConfig');
1
2
  const { getAirtableArchiveRecord, archiveRecordId } = require('../models/airtableArchiveModel');
2
3
  const { toAirtableRow } = require('../helpers/airtableArchiveHelper');
3
4
 
4
- const READ_PROJECTION = { recordId: 1, createdTime: 1, fields: 1 };
5
+ // Only rows already deleted from Airtable: a copy whose source is still live must never reach a reader.
6
+ const DELETED_FROM_SOURCE = { sourceDeletedAt: { $ne: null } };
5
7
 
6
- async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since }) {
8
+ // Unmapped, the model would fall back to the default database and every read would come back empty.
9
+ function archiveRecords() {
10
+ if (!getModelDatabase('AirtableArchiveRecord')) throw new Error('AirtableArchiveRecord db not mapped (setModelDatabases)');
11
+ return getAirtableArchiveRecord();
12
+ }
13
+
14
+ function readProjection({ fields, withAttachments = false } = {}) {
15
+ const projection = { recordId: 1, createdTime: 1 };
16
+ if (fields?.length) fields.forEach((name) => { projection[`fields.${name}`] = 1; });
17
+ else projection.fields = 1;
18
+ if (withAttachments) projection.attachments = 1;
19
+ return projection;
20
+ }
21
+
22
+ async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since, fields, withAttachments }) {
7
23
  if (!whatsappId && !patientRecordId) return [];
8
- const query = { baseId, tableName };
24
+ const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
9
25
  if (patientRecordId) query['patient.recordId'] = patientRecordId;
10
26
  else query['patient.whatsappId'] = whatsappId;
11
27
  if (since) query.createdTime = { $gte: since };
12
- const docs = await getAirtableArchiveRecord().find(query, READ_PROJECTION).sort({ createdTime: -1 }).lean();
28
+ const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).sort({ createdTime: -1 }).lean();
13
29
  return docs.map(toAirtableRow);
14
30
  }
15
31
 
16
- async function findArchivedByRecordIds({ baseId, tableName, recordIds }) {
32
+ async function findArchivedByRecordIds({ baseId, tableName, recordIds, fields, withAttachments }) {
17
33
  if (!recordIds?.length) return [];
18
- const docs = await getAirtableArchiveRecord().find({ _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName }, READ_PROJECTION).lean();
34
+ const query = { _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName, ...DELETED_FROM_SOURCE };
35
+ const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).lean();
36
+ return docs.map(toAirtableRow);
37
+ }
38
+
39
+ async function findArchivedByTable({ baseId, tableName, since, fields }) {
40
+ const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
41
+ if (since) query.createdTime = { $gte: since };
42
+ const docs = await archiveRecords().find(query, readProjection({ fields })).sort({ createdTime: -1 }).lean();
19
43
  return docs.map(toAirtableRow);
20
44
  }
21
45
 
22
46
  module.exports = {
23
47
  findArchivedByPatient,
24
48
  findArchivedByRecordIds,
49
+ findArchivedByTable,
25
50
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.75.6",
3
+ "version": "5.76.0-dev.15838",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",