@peopl-health/nexus 6.2.2 → 6.3.0-dev.18359

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.
@@ -9,7 +9,7 @@ const EMPTY_OUTBOUND_FALLBACK = 'Recibí tu mensaje. Si quieres contarme más o
9
9
  const definition = {
10
10
  name: 'DeliverPatientMessage',
11
11
  replayArgs: ['message_text', 'purpose'],
12
- description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**When the patient asks what the care team answered:** say where the case stands from `turn_focus.team_cases` (load `getRouterContextBundle` first if you have not this turn). Never add a time, and never say the team already reviewed or saw something unless the status is one where the team answered (`Esperando paciente`, `Indicaciones dadas`, `En vigilancia`).\n\n**When you relay what a doctor indicated:** name the doctor the team instruction names, even when it is not the `Médico tratante` of the clinical context. Saying the treating doctor reviewed the case when another doctor did tells the patient something false.\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
12
+ description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**When the patient asks what the care team answered:** say where the case stands from `turn_focus.team_cases` (load `getRouterContextBundle` first if you have not this turn). Never add a time, and never say the team already reviewed or saw something unless the status is one where the team answered (`Esperando paciente`, `Indicaciones dadas`, `En vigilancia`).\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
13
13
  strict: false,
14
14
  parameters: {
15
15
  type: 'object',
@@ -57,6 +57,7 @@ const graveDueAt = (review, clock, flag) => {
57
57
  function outcomeOf(review, clock, now) {
58
58
  const wait = pendingWaitMinutes(clock?.level);
59
59
  if (!wait || !OUTCOME_LEVELS.includes(clock.level) || !['draft_ready', 'awaiting_doctor'].includes(review.status)) return null;
60
+ // Handoffs count since the last decision, so a higher alarm on a case already with the doctor goes as an update.
60
61
  const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => timeOf(decision.createdAt)));
61
62
  const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) > decidedAt);
62
63
  const last = handoffs.at(-1);
@@ -73,7 +74,7 @@ function outcomeOf(review, clock, now) {
73
74
  const present = latest.urgentPresentRedFlags ?? [];
74
75
  // An update reaches the doctor's phone only with a grave flag the draft they have did not show; the panel always shows the latest draft.
75
76
  const handedPresent = new Set((update ? review.drafts[last.draftNumber - 1]?.urgentPresentRedFlags ?? [] : []).map(flagKey));
76
- // Airtable's alert reaches the team, not the doctor's phone.
77
+ // A higher alarm already rang the doctor's phone since the last handoff, so its update shows in the panel only; Airtable's alert goes to the team.
77
78
  const raisedSince = (level) => (review.alarms ?? []).some((alarm) => alarm.urgencyLevel === level && timeOf(alarm.raisedAt) > timeOf(last.createdAt));
78
79
  const rangSince = update && (review.doctorAlerts ?? []).some((sent) => sent.kind === 'initial' && !sent.error
79
80
  && sent.transport && sent.transport !== 'airtable' && timeOf(sent.sentAt) > timeOf(last.createdAt) && raisedSince(sent.urgencyLevel));
@@ -1030,7 +1030,7 @@ async function caseTakenReason(review, from, level) {
1030
1030
  const changes = review.urgencyReclassifications ?? [];
1031
1031
  const levelsAt = (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1032
1032
  if (level !== 'stat' && levelsAt(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1033
- // A lowering means someone looked at the case; a raise restarts the clock instead.
1033
+ // Lowering the level, from what this episode's alarms were at, means someone looked at the case; a raise restarts the clock instead.
1034
1034
  const lowered = (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1035
1035
  if (changes.some((change) => atOrAfter(change.at) && lowered(change))) return 'reclassified';
1036
1036
  if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
@@ -20,6 +20,7 @@ function pendingFlagsOf(review, since) {
20
20
  return { latest: drafts.at(-1) ?? null, flags: [...firstSeen].map(([flag, firstSeenAt]) => ({ flag, firstSeenAt, unobtainable: unobtainable.includes(flag) })) };
21
21
  }
22
22
 
23
+ // The bot keeps documenting a case it handed to the doctor itself while it still redrafts it, so its grave questions still wait for the patient there.
23
24
  const stillDocumented = (review) => DOCUMENTING_STATUSES.includes(review.status) || updatesDoctor(review);
24
25
 
25
26
  // The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
@@ -45,7 +45,7 @@ function responseDeadlinePolicy() {
45
45
  };
46
46
  }
47
47
 
48
- // A raise restarts the alarm's clock; a lowering keeps it.
48
+ // Each alarm at the level the team set for it since it was raised; a raise restarts its clock, a lowering keeps it.
49
49
  function levelsOf(alarms, reclassifications, startLevel = (alarm) => alarm.urgencyLevel) {
50
50
  const changes = [...(reclassifications ?? [])].sort((a, b) => timeOf(a.at) - timeOf(b.at));
51
51
  return (alarms ?? []).map((alarm) => changes
@@ -34,7 +34,8 @@ const duration = (minutes) => {
34
34
  return rest ? `${hours} h ${rest} min` : `${hours} h`;
35
35
  };
36
36
 
37
- // Only the stages restart on a raise; the episode start ignores reclassifications so drafts and grave alerts keep their key.
37
+ // The clock runs at the highest level since the last decision, its stages from the first alarm or team raise at that level.
38
+ // The episode keeps the start the alarms' own levels give it, so a reclassification never re-keys its drafts or grave alerts.
38
39
  function episodeStartOf(alarms) {
39
40
  const top = alarms.reduce((level, alarm) => ((URGENCY_RANK[appliedLevelOf(alarm)] || 0) > (URGENCY_RANK[level] || 0) ? appliedLevelOf(alarm) : level), null);
40
41
  return new Date(Math.min(...alarms.filter((alarm) => appliedLevelOf(alarm) === top).map((alarm) => new Date(alarm.raisedAt).getTime())));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.2.2",
3
+ "version": "6.3.0-dev.18359",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",