@peopl-health/nexus 6.5.4 → 6.5.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,6 +401,7 @@ class AssistantProcessor {
401
401
  sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt, ...(result.contactCode && { contactCode: result.contactCode, contactRole: result.contactRole }) });
402
402
  result.delivery = sent || null;
403
403
  } catch (error) {
404
+ await this._settleInTurnAsk(code, result);
404
405
  if (directive) {
405
406
  await this._settleDelivery({
406
407
  directive,
@@ -426,10 +427,19 @@ class AssistantProcessor {
426
427
  traceId: result.traceId || null,
427
428
  });
428
429
  }
430
+ if (deliveryOutcome(sent) !== 'known_not_sent') await this._settleInTurnAsk(code, result);
429
431
  clearBridgeState(code);
430
432
  return result.output;
431
433
  }
432
434
 
435
+ async _settleInTurnAsk(code, result) {
436
+ try {
437
+ await require('../services/stillNeededService').settleInTurnAsk(code, result.turnId, result.output);
438
+ } catch (error) {
439
+ logger.warn('[AssistantProcessor] in-turn ask not settled', { turnId: result.turnId || null, error: error.message });
440
+ }
441
+ }
442
+
433
443
  async discardResponse(code, result) {
434
444
  const directive = result?.deliveryDirective;
435
445
  if (!directive?.claimed || directive.settled) return false;
@@ -53,7 +53,7 @@ const deliveredWhileWaitingNote = (text) =>
53
53
  `${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
54
54
 
55
55
  const stillNeededNote = (question) =>
56
- `${OPERATOR_TURN_PREFIX} La revisión del equipo médico todavía necesita saber: "${question}". Si el paciente no lo contestó en este mensaje, pregúntalo con tus palabras al final de tu respuesta, como tu única pregunta, y no digas que el equipo ya tiene todo. Si ya lo contestó, no lo preguntes.`;
56
+ `${OPERATOR_TURN_PREFIX} La revisión del equipo médico todavía necesita saber: "${question}". Si el paciente no lo contestó en este mensaje, pregúntalo al final de tu respuesta en una sola pregunta corta (si son varios datos, júntalos en esa misma pregunta), con palabras sencillas y por lo que pueda notar o medir, sin nombrar diagnósticos; no digas que el equipo ya tiene todo ni que tiene el cuadro o la información completa. Si ya lo contestó, no lo preguntes.`;
57
57
 
58
58
  function readComorbidities(value) {
59
59
  const parsed = typeof value === 'string' ? safeParse(value, null) : value;
@@ -116,8 +116,11 @@ const inTurnAskSchema = new mongoose.Schema({
116
116
  draftAt: { type: Date, required: true },
117
117
  key: { type: String, required: true },
118
118
  question: { type: String, required: true },
119
+ flags: { type: [String], default: undefined },
119
120
  turnId: { type: String, default: null },
120
121
  at: { type: Date, required: true },
122
+ outcome: { type: String, enum: ['asked', 'not_asked', null], default: null },
123
+ askedAt: { type: Date, default: null },
121
124
  }, { _id: false });
122
125
 
123
126
  const reviewUpdateSchema = new mongoose.Schema({
@@ -42,6 +42,11 @@ const noteOf = (text) => cutOnWord(text, MAX_NOTE_LENGTH);
42
42
  const timeOf = (value) => new Date(value).getTime();
43
43
  const episodeAsks = (review, clock) => (review.blockingAsks ?? []).filter((ask) => timeOf(ask.draftAt) >= clock.since.getTime()
44
44
  && (ASKED_OUTCOMES.includes(ask.outcome) || (!ask.skippedReason && ask.outcome == null)));
45
+ // An entry from before replies were settled has no outcome; the bot asked it back then.
46
+ const inTurnOutcomeOf = (entry) => (entry.outcome === undefined ? 'asked' : entry.outcome);
47
+ const inTurnAsksOf = (review, clock) => (review.inTurnAsks ?? [])
48
+ .filter((entry) => inTurnOutcomeOf(entry) === 'asked' && timeOf(entry.draftAt) >= clock.since.getTime())
49
+ .map((entry) => ({ ...entry, askedAt: entry.askedAt ?? entry.at }));
45
50
  const lastAskAt = (review, clock) => Math.max(0, ...episodeAsks(review, clock).map((ask) => timeOf(ask.sentAt)));
46
51
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
47
52
  // When the team's alert for this grave datum first fell due, which a failed send's retry does not move; one not recorded yet has not.
@@ -53,9 +58,11 @@ const graveDueAt = (review, clock, flag) => {
53
58
 
54
59
  function teamGraveOf(review, clock, grave, now) {
55
60
  const waitMs = pendingWaitMinutes(clock.level) * 60000;
56
- const askedAt = ({ flag, firstSeenAt }) => Math.min(...(review.blockingAsks ?? [])
57
- .filter((ask) => ASKED_OUTCOMES.includes(ask.outcome) && timeOf(ask.draftAt) >= timeOf(firstSeenAt) && (ask.flags ?? []).map(normalizedKeyOf).includes(flag))
58
- .map((ask) => timeOf(ask.sentAt)));
61
+ const askedAt = ({ flag, firstSeenAt }) => Math.min(
62
+ ...[...(review.blockingAsks ?? []).filter((ask) => ASKED_OUTCOMES.includes(ask.outcome)), ...inTurnAsksOf(review, clock).map((entry) => ({ ...entry, sentAt: entry.askedAt }))]
63
+ .filter((ask) => timeOf(ask.draftAt) >= timeOf(firstSeenAt) && (ask.flags ?? []).map(normalizedKeyOf).includes(flag))
64
+ .map((ask) => timeOf(ask.sentAt)),
65
+ );
59
66
  const dueAt = (entry) => (entry.reason === 'unobtainable' ? -Infinity : askedAt(entry) + waitMs);
60
67
  // A datum the bot never asked about calls no one: it reaches the doctor in the note.
61
68
  const asked = grave.filter((entry) => dueAt(entry) < Infinity);
@@ -118,11 +125,11 @@ function outcomeOf(review, clock, now) {
118
125
  // The wait runs from the bot's question to the patient, so «no contestó» is said only of a question she was asked.
119
126
  const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
120
127
  // The bot asked this draft's question in its own reply when no redraft followed that reply.
121
- const inTurn = (review.inTurnAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
128
+ const inTurn = inTurnAsksOf(review, clock).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
122
129
  const sent = ask && !ask.skippedReason;
123
- const askedAt = sent ? ask.sentAt : inTurn?.at ?? latest.createdAt;
130
+ const askedAt = sent ? ask.sentAt : inTurn?.askedAt ?? latest.createdAt;
124
131
  // A first handoff with a question waits for its ask (recorded once the bot's reply is in), or in flight, up to twice the wait.
125
- if (!update && latest.blockingQuestion && (!ask || (sent && ask.outcome == null)) && minutesSince(askedAt, now) < 2 * wait) return null;
132
+ if (!update && latest.blockingQuestion && ((!ask && !inTurn) || (sent && ask.outcome == null)) && minutesSince(askedAt, now) < 2 * wait) return null;
126
133
  if (minutesSince(askedAt, now) < wait) return null;
127
134
  const missing = latest.blockingQuestion ? `Falta: ${latest.blockingQuestion}` : 'Falta información';
128
135
  // An update's draft is never asked about, so it says only what is missing.
@@ -148,7 +155,7 @@ async function claimGraveAlerts(review, clock, grave, now) {
148
155
  .filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
149
156
  const fresh = grave.filter((entry) => !recorded.has(entry.flag));
150
157
  // «No contestó» only for a datum the bot asked about while that question is still open; otherwise «no lo ha dicho».
151
- const askedFlags = new Set((review.blockingAsks ?? []).filter((ask) => ASKED_OUTCOMES.includes(ask.outcome) && timeOf(ask.draftAt) >= clock.since.getTime())
158
+ const askedFlags = new Set([...(review.blockingAsks ?? []).filter((ask) => ASKED_OUTCOMES.includes(ask.outcome) && timeOf(ask.draftAt) >= clock.since.getTime()), ...inTurnAsksOf(review, clock)]
152
159
  .flatMap((ask) => (ask.flags ?? []).map(normalizedKeyOf)));
153
160
  const open = fresh.some(({ flag, reason }) => reason === 'unanswered' && askedFlags.has(flag))
154
161
  && hasOpenQuestion(await lastChatMessage(review.patientCode).catch(() => null));
@@ -397,11 +404,11 @@ function pendingAskOf(review, clock) {
397
404
  // A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
398
405
  const settled = new Set([
399
406
  ...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
400
- ...episodeAsks(review, clock).flatMap((entry) => entry.flags ?? []),
407
+ ...[...episodeAsks(review, clock), ...inTurnAsksOf(review, clock)].flatMap((entry) => entry.flags ?? []),
401
408
  ].map(normalizedKeyOf));
402
409
  const graveFlags = latest.urgentPresentRedFlags?.length ? []
403
410
  : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
404
- const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
411
+ const blocking = withDoctor || graveFlags.length || settled.has(normalizedKeyOf(latest.blockingFlag ?? '')) ? null : latest.blockingQuestion;
405
412
  const question = graveFlags.join('; ') || blocking || null;
406
413
  if (!question) return null;
407
414
  const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
@@ -435,6 +442,8 @@ async function askBlockingQuestion(review, clock, now) {
435
442
  const fresh = await getEscalationReview().findById(review._id).lean();
436
443
  if (!fresh || fresh.closedAt || fresh.status !== review.status || (withDoctor && !stillDocumented(fresh))) return 'moved';
437
444
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
445
+ const askedInTurn = new Set(inTurnAsksOf(fresh, clock).flatMap((entry) => entry.flags ?? []));
446
+ if (flags.every((flag) => askedInTurn.has(flag))) return 'asked_in_turn';
438
447
  return takenOf(fresh, clock);
439
448
  };
440
449
  getMessaging().processInstruction(review.patientCode, graveAskText(graveFlags), 'developer', { triggeredBy: OPERATOR, beforeRun })
@@ -480,4 +489,4 @@ async function settleCharacterization(review, clock, now) {
480
489
  await askBlockingQuestion(review, clock, now);
481
490
  }
482
491
 
483
- module.exports = { outcomeOf, pendingAskOf, settleCharacterization };
492
+ module.exports = { ASKED_OUTCOMES, hasOpenQuestion, inTurnOutcomeOf, outcomeOf, pendingAskOf, settleCharacterization };
@@ -4,32 +4,50 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
4
4
  const { escalationInTurnAskLive } = require('../clinical/flags/escalationFlags');
5
5
 
6
6
  const { BOOKKEEPING, caseTakenReason } = require('./escalationReviewService');
7
- const { pendingAskOf } = require('./characterizationOutcomeService');
7
+ const { ASKED_OUTCOMES, hasOpenQuestion, inTurnOutcomeOf, pendingAskOf } = require('./characterizationOutcomeService');
8
8
  const { responseDeadlinePolicy } = require('./reviewDeadlineService');
9
9
  const { UNTAKEN_PROJECTION, untakenClockOf } = require('./untakenAlertService');
10
10
 
11
- // The review's blocking question the bot asks in its own reply: not grave, and served once per episode.
11
+ const IN_TURN_OUTCOMES = ['asked', 'not_asked'];
12
+ const ASK_TAKEN = { $or: [{ outcome: { $in: ASKED_OUTCOMES } }, { skippedReason: null, outcome: null }] };
13
+
14
+ // A claim is settled by its turn's reply, so a turn without an id never claims.
12
15
  async function claimStillNeeded(code, turnId = null, now = new Date()) {
13
- if (!escalationInTurnAskLive()) return null;
14
- const review = await getEscalationReview().findOne({ patientCode: ensureWhatsAppFormat(code), closedAt: null, status: 'draft_ready' }, UNTAKEN_PROJECTION).lean();
16
+ if (!turnId || !escalationInTurnAskLive()) return null;
17
+ const review = await getEscalationReview().findOne({ patientCode: ensureWhatsAppFormat(code), closedAt: null, status: { $in: ['draft_ready', 'awaiting_doctor'] } }, UNTAKEN_PROJECTION).lean();
15
18
  if (!review) return null;
16
19
  const clock = untakenClockOf(review, responseDeadlinePolicy());
17
- const pending = clock && pendingAskOf(review, clock);
18
- if (!pending?.blocking) return null;
19
- const key = normalizedKeyOf(pending.latest.blockingFlag || pending.blocking);
20
- const served = { key, draftAt: { $gte: clock.since } };
21
- const earlier = (review.inTurnAsks ?? []).find((entry) => entry.key === key && new Date(entry.draftAt) >= clock.since);
20
+ if (!clock) return null;
21
+ const episode = (review.inTurnAsks ?? []).filter((entry) => new Date(entry.draftAt) >= clock.since);
22
22
  // A retry of the same turn rebuilds its context, so it gets the question its first attempt claimed.
23
- if (earlier) return turnId && earlier.turnId === turnId ? earlier.question : null;
23
+ const retried = episode.find((entry) => entry.turnId === turnId);
24
+ if (retried) return retried.question;
25
+ const pending = pendingAskOf(review, clock);
26
+ if (!pending) return null;
27
+ const key = normalizedKeyOf(pending.graveFlags.length ? pending.graveFlags.join('; ') : pending.latest.blockingFlag || pending.blocking);
28
+ const served = { key, draftAt: { $gte: clock.since }, $or: [{ outcome: { $in: IN_TURN_OUTCOMES } }, { outcome: { $exists: false } }] };
29
+ if (episode.some((entry) => entry.key === key && IN_TURN_OUTCOMES.includes(inTurnOutcomeOf(entry)))) return null;
24
30
  // A case the team already took is theirs to ask; a missing thread does not count as taken.
25
31
  const taken = await caseTakenReason(review, clock.since, clock.level);
26
32
  if (taken && taken !== 'thread_missing') return null;
27
33
  const claimed = await getEscalationReview().updateOne(
28
- { _id: review._id, closedAt: null, inTurnAsks: { $not: { $elemMatch: served } } },
29
- { $push: { inTurnAsks: { draftAt: pending.latest.createdAt, key, question: pending.blocking, turnId, at: now } } },
34
+ { _id: review._id, closedAt: null, inTurnAsks: { $not: { $elemMatch: served } }, blockingAsks: { $not: { $elemMatch: { draftAt: pending.latest.createdAt, ...ASK_TAKEN } } } },
35
+ { $push: { inTurnAsks: { draftAt: pending.latest.createdAt, key, question: pending.question, flags: pending.graveFlags, turnId, at: now, outcome: null, askedAt: null } } },
36
+ BOOKKEEPING,
37
+ );
38
+ return claimed.modifiedCount ? pending.question : null;
39
+ }
40
+
41
+ async function settleInTurnAsk(code, turnId, output, now = new Date()) {
42
+ if (!turnId || !escalationInTurnAskLive()) return;
43
+ // The note asks for the datum as the reply's closing question.
44
+ const closing = String(output ?? '').split('\n').filter((line) => line.trim()).at(-1);
45
+ const asked = hasOpenQuestion({ from_me: true, body: closing });
46
+ await getEscalationReview().updateOne(
47
+ { patientCode: ensureWhatsAppFormat(code), closedAt: null, inTurnAsks: { $elemMatch: { turnId, outcome: { $type: 'null' } } } },
48
+ { $set: { 'inTurnAsks.$.outcome': asked ? 'asked' : 'not_asked', 'inTurnAsks.$.askedAt': asked ? now : null } },
30
49
  BOOKKEEPING,
31
50
  );
32
- return claimed.modifiedCount ? pending.blocking : null;
33
51
  }
34
52
 
35
- module.exports = { claimStillNeeded };
53
+ module.exports = { claimStillNeeded, settleInTurnAsk };
@@ -154,7 +154,8 @@ async function alertIfUntaken(review, clock, stage, now) {
154
154
  // Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
155
155
  const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
156
156
  if (!await claimStage(review, clock, stage, now)) return false;
157
- const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: clock.level === 'stat' && !who.identity.testPatient });
157
+ // A roster doctor gets the levels their sin_tomar lists, like anyone else on the team.
158
+ const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: !who.identity.testPatient });
158
159
  const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
159
160
  await getEscalationReview().updateOne(
160
161
  { _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.4",
3
+ "version": "6.5.6",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",