@peopl-health/nexus 6.6.0-dev.20750 → 6.6.0-dev.20830
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.
|
@@ -21,7 +21,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
|
|
|
21
21
|
|
|
22
22
|
const definition = {
|
|
23
23
|
'name': 'reportMedicalEscalation',
|
|
24
|
-
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go and asks nothing. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\'), the availability line and, as in `asap` and `urgent`, at most the one conditional urgencias line below — no direct urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: never 911 and never an instruction to go now, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen. The one warning sign allowed above may point to urgencias, as a single calm conditional line about ONE symptom they already reported getting clearly worse (\'si el dolor aumenta mucho, ve a urgencias con alguien que te acompañe\'): one condition, no list of signs and no \'si alguno de estos…\', no other symptom or body part, and never 911 in it (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where that line is always: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias beyond the one conditional line `asap` and `urgent` allow). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
24
|
+
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (new, sudden weakness of an arm, a leg or one side, numbness of the face or a whole side, a drooping face or new trouble speaking — even if they can still move it —; new loss of bladder or bowel control; new or worsening leg weakness with back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine), or groin numbness, or sudden weakness of both legs → possible cord compression) or any instability; an acute deficit is must-go and asks nothing, except the one onset question when it is not yet known whether it came on suddenly. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop, or vomiting blood or black, tarry stool together with dizziness or near-fainting on standing (even without the skin signs of shock); fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go, except with the checkpoint-inhibitor signs below); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; NEW, SUDDEN weakness of one arm, one leg or one side, numbness of the face or of a whole side (face, arm and leg), a drooping face or new trouble speaking, even if they can still move it (a known, long-standing limitation is not sudden; general weakness or tiredness, or not getting up from fatigue, is not must-go: `asap`, or `urgent` if it is gradual and they are eating, drinking and passing urine; if they cannot stand because they feel faint, check it against fainting and shock); possible cord compression — NEW or WORSENING weakness in the legs TOGETHER WITH back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine: breast, prostate, lung, kidney, myeloma), or numbness in the groin or buttocks, even if it came on over hours or days; or SUDDEN weakness of both legs (it came on within hours), even without back pain; or new loss of bladder or bowel control on its own (not feeling or not holding urine or stool, or not being able to pass urine; urgency from diarrhea is not this) — tingling or numbness in hands and feet from neuropathy, or long-standing leg weakness without back pain, is not must-go, and new back pain with no neurologic sign is `asap`; on active or recent checkpoint-inhibitor immunotherapy, drooping eyelids, double vision, new trouble swallowing or leg weakness getting worse over days is at least `asap`, and must-go with shortness of breath at rest or when they cannot swallow; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, or mottled, or grey or bluish lips, TOGETHER WITH at least one of: near-fainting on standing, new confusion or drowsiness, a racing heart at rest, or almost no urine (none in 12 hours or more); pallor, tiredness or weakness without those skin signs is not must-go (`asap`). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands, pallor or tiredness alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; cold or mottled skin with nothing else; weakness without knowing whether it is one side; leg weakness or numbness without knowing when it started — «sudden» means within minutes or hours, as the patient says, never assumed; numbness or tingling alone, without weakness, is not must-go unless it is of the face, of a whole side, or of the groin with leg weakness; numbness of one arm or one leg alone gets the onset question first), it is not confirmed yet: ask ONE question about the missing part before choosing the level; when leg weakness or numbness has no stated onset, that question MUST ask when it started (walking or back pain may go in the same question, never instead of it) (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\' / \'¿La debilidad es de todo el cuerpo, como cansancio, o de un brazo, una pierna o un lado?\' / \'¿Desde cuándo lo sientes, fue de golpe o poco a poco, y puedes caminar?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado, and they never drive themselves; if they are alone: \'pide que alguien venga por ti o toma un taxi; si no puedes moverte o te sientes peor, llama al 911\'. 911 (or an ambulance) FIRST, alone or not and even if they can move, for: anaphylaxis; fainting they have not fully recovered from; a seizure or sudden confusion; a possible stroke (sudden weakness of one side, an arm or a leg, sudden numbness of the face or a whole side, a drooping face, sudden trouble speaking); chest pain with clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw; INTENSE shortness of breath at rest; shock; heavy bleeding (vomiting blood, a lot of black or bloody stool, or bleeding that soaks through cloths or towels; a nosebleed or other bleed that keeps going despite pressure without soaking through is must-go, not 911-first); and cord compression when they cannot walk. For anaphylaxis, if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\'), the availability line and, as in `asap` and `urgent`, at most the one conditional urgencias line below — no direct urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: never 911 and never an instruction to go now, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen. The one warning sign allowed above may point to urgencias, as a single calm conditional line about ONE symptom they already reported getting clearly worse (\'si el dolor aumenta mucho, ve a urgencias con alguien que te acompañe\'): one condition, no list of signs and no \'si alguno de estos…\', no other symptom or body part, and never 911 in it (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where that line is always: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way: accompanied, someone or a taxi coming, or the ambulance called.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias beyond the one conditional line `asap` and `urgent` allow). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
25
25
|
'strict': true,
|
|
26
26
|
'parameters': {
|
|
27
27
|
'type': 'object',
|
|
@@ -34,7 +34,7 @@ const definition = {
|
|
|
34
34
|
'urgent',
|
|
35
35
|
'routine'
|
|
36
36
|
],
|
|
37
|
-
'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con
|
|
37
|
+
'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, posible compresión medular (debilidad de piernas nueva o en aumento con dolor de espalda o cuello, enfermedad de columna o metástasis óseas (o, si no se sabe, un cáncer que suele ir a la columna), o adormecimiento en ingle o glúteos; debilidad de las dos piernas de golpe; o pérdida nueva del control de orina o excremento), anafilaxia confirmada (hinchazón de lengua o garganta, dificultad para tragar, respirar o hablar, o ronchas en todo el cuerpo con mareo), choque (piel fría y sudorosa o manchada, o labios grises o morados, junto con casi desmayarse al pararse, confusión o somnolencia nueva, corazón acelerado en reposo o casi no orinar). Cualquier dato confirmado de la lista de ir sí o sí (descrita en la descripción de la herramienta, incluida la posible compresión medular aunque venga en horas o días) es `stat`, nunca `asap`.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias (salvo que una instrucción interna del sistema lo indique); el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
|
|
38
38
|
},
|
|
39
39
|
'patient_check_in': {
|
|
40
40
|
'anyOf': [
|
|
@@ -69,7 +69,7 @@ const definition = {
|
|
|
69
69
|
'persistent_symptom_72h',
|
|
70
70
|
'stale_clinical_context'
|
|
71
71
|
],
|
|
72
|
-
'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: fiebre o sospecha de infección en ventana de quimioterapia.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`:
|
|
72
|
+
'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: fiebre o sospecha de infección en ventana de quimioterapia.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`: debilidad de piernas nueva o en aumento con dolor de espalda o cuello, enfermedad de columna o metástasis óseas (o, si no se sabe, un cáncer que suele ir a la columna), o adormecimiento en ingle o glúteos; debilidad de las dos piernas de golpe; o pérdida nueva del control de orina o excremento.\n- `treatment_concern`: duda o efecto atribuible al tratamiento en curso.\n- `persistent_symptom_72h`: síntoma que lleva MÁS DE 72 HORAS sin resolverse. No es el cajón por defecto: un síntoma de hoy o de ayer no entra aquí.\n- `stale_clinical_context`: el expediente no refleja la situación real del paciente.'
|
|
73
73
|
},
|
|
74
74
|
{
|
|
75
75
|
'type': 'null'
|
|
@@ -163,7 +163,7 @@ const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
|
|
|
163
163
|
const FEVER_ASK = 'If they ask whether to go to urgencias or what to watch';
|
|
164
164
|
const FEVER_ASK_TIMER = 'In a fever `asap` (`febrile_neutropenia`) leave that line out: its patient timer gives that instruction. ' + FEVER_ASK;
|
|
165
165
|
|
|
166
|
-
const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. A low reading means below 36.0 °C only; 36.0 °C is normal. A low reading is not fever and is never called fever, neither to the patient nor in `details`: before escalating, ask for a re-measure and how they feel right now. Still below 36.0 °C with current malaise, chills or shivering, or a confirmed ≤35.0 °C, is `asap`; still below 36.0 °C with no other symptom is `urgent`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
|
|
166
|
+
const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. A low reading means below 36.0 °C only; 36.0 °C is normal. A low reading is not fever and is never called fever, neither to the patient nor in `details`: before escalating, ask for a re-measure and how they feel right now. Still below 36.0 °C with current malaise, chills or shivering, or a confirmed ≤35.0 °C, is `asap`; still below 36.0 °C with no other symptom is `urgent`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand with the fever, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
|
|
167
167
|
|
|
168
168
|
const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
|
|
169
169
|
|
|
@@ -8,6 +8,7 @@ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUti
|
|
|
8
8
|
const { ageInYears, isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
9
9
|
const { safeParse } = require('../utils/jsonUtils');
|
|
10
10
|
const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
|
|
11
|
+
const { mexicanPhoneForDisplay } = require('../utils/formatUtils');
|
|
11
12
|
const {
|
|
12
13
|
CALL_OUTCOMES,
|
|
13
14
|
CANCELLABLE_AFTER_HANDOFF_STATUSES,
|
|
@@ -1204,7 +1205,7 @@ async function sendPatientPrompt({ id, release, lease, now }) {
|
|
|
1204
1205
|
|
|
1205
1206
|
let directive;
|
|
1206
1207
|
try {
|
|
1207
|
-
directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
|
|
1208
|
+
directive = String((await composePrompt({ promptId: timer.promptId, variables: await primaryDoctorVariables(review) }))?.resolvedPrompt ?? '').trim();
|
|
1208
1209
|
} catch (composeError) {
|
|
1209
1210
|
// A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
|
|
1210
1211
|
// drops it (with a ledger entry) if Airtable stays unreachable.
|
|
@@ -1787,6 +1788,16 @@ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId =
|
|
|
1787
1788
|
return review;
|
|
1788
1789
|
}
|
|
1789
1790
|
|
|
1791
|
+
async function primaryDoctorVariables(review) {
|
|
1792
|
+
try {
|
|
1793
|
+
const approver = await notifiedApprover();
|
|
1794
|
+
return { medico_principal_nombre: approver.name, medico_principal_telefono: mexicanPhoneForDisplay(approver.phone) };
|
|
1795
|
+
} catch (error) {
|
|
1796
|
+
logger.error('[EscalationReview] The primary doctor could not be read or chosen; the patient prompt goes without one', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
1797
|
+
return {};
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1790
1801
|
async function notifiedApprover() {
|
|
1791
1802
|
const approvers = await listEscalationApprovers();
|
|
1792
1803
|
if (!approvers.length) {
|
package/lib/utils/formatUtils.js
CHANGED
|
@@ -42,6 +42,16 @@ function stripSpreadsheetErrorsDeep(value, options = {}) {
|
|
|
42
42
|
return value;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
// Mexico's two-digit area codes (Guadalajara, Mexico City, Monterrey); the rest have three digits.
|
|
46
|
+
const TWO_DIGIT_AREA_CODES = new Set(['33', '55', '56', '81']);
|
|
47
|
+
|
|
48
|
+
function mexicanPhoneForDisplay(phone) {
|
|
49
|
+
const national = String(phone ?? '').replace(/\D/g, '').match(/^521?(\d{10})$/)?.[1];
|
|
50
|
+
if (!national) return String(phone ?? '').trim();
|
|
51
|
+
const area = TWO_DIGIT_AREA_CODES.has(national.slice(0, 2)) ? 2 : 3;
|
|
52
|
+
return `+52 ${national.slice(0, area)} ${national.slice(area, 6)} ${national.slice(6)}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
45
55
|
function usableText(value) {
|
|
46
56
|
if (value === null || value === undefined) return '';
|
|
47
57
|
const text = typeof value === 'string' ? value : String(value);
|
|
@@ -54,5 +64,6 @@ module.exports = {
|
|
|
54
64
|
hasSpreadsheetError,
|
|
55
65
|
stripSpreadsheetErrors,
|
|
56
66
|
stripSpreadsheetErrorsDeep,
|
|
67
|
+
mexicanPhoneForDisplay,
|
|
57
68
|
usableText
|
|
58
69
|
};
|