@peopl-health/nexus 5.62.0-dev.11344 → 5.62.1

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.
@@ -2,6 +2,7 @@ const { Config_ID } = require('../../config/airtableConfig');
2
2
 
3
3
  const { getRecordByFilter } = require('../../services/airtableService');
4
4
 
5
+ const { logger } = require('../../utils/logger');
5
6
  const { MapCache } = require('../../utils/MapCache');
6
7
  const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
7
8
 
@@ -67,9 +68,11 @@ async function load() {
67
68
  if (byKey.ESCALATION_NOTE_FACTS && !isPlainObject(parsedNoteFacts)) throw new Error('subAgents config ESCALATION_NOTE_FACTS is not a JSON object');
68
69
  const escalationNoteFacts = { ...ESCALATION_NOTE_FACTS_DEFAULTS, ...(parsedNoteFacts || {}) };
69
70
 
71
+ // SUPPORT_LIGHT drives an optional sweep, so a malformed row leaves it unconfigured instead of failing every sub-agent.
70
72
  const parsedSupportLight = safeParse(byKey.SUPPORT_LIGHT, null);
71
- if (byKey.SUPPORT_LIGHT && !isPlainObject(parsedSupportLight)) throw new Error('subAgents config SUPPORT_LIGHT is not a JSON object');
72
- const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(parsedSupportLight || {}) };
73
+ const isSupportLightValid = !byKey.SUPPORT_LIGHT || isPlainObject(parsedSupportLight);
74
+ if (!isSupportLightValid) logger.error('[subAgentsConfig] SUPPORT_LIGHT is not a JSON object; the support-light sweep stays unconfigured');
75
+ const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(isSupportLightValid ? parsedSupportLight || {} : {}) };
73
76
 
74
77
  const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight };
75
78
  cache.set(CACHE_KEY, config);
@@ -0,0 +1,16 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ const flagOn = (key) => String(runtimeConfig.get(key, 'false')).trim().toLowerCase() === 'true';
4
+
5
+ function escalationUpdateModeLive() {
6
+ return flagOn('ESCALATION_UPDATE_MODE_LIVE');
7
+ }
8
+
9
+ function escalationAssessmentLive() {
10
+ return flagOn('ESCALATION_ASSESSMENT_LIVE');
11
+ }
12
+
13
+ module.exports = {
14
+ escalationAssessmentLive,
15
+ escalationUpdateModeLive,
16
+ };
@@ -46,7 +46,6 @@ const supportLightSchema = new mongoose.Schema({
46
46
  supportLightSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_light_per_service' });
47
47
  supportLightSchema.index({ service: 1, color: 1 });
48
48
  supportLightSchema.index({ 'pendingImprovement.proposedAt': 1 }, { sparse: true });
49
- supportLightSchema.index({ 'outbox.at': 1 }, { sparse: true });
50
49
 
51
50
  const supportLightEventSchema = new mongoose.Schema({
52
51
  patientId: { type: String, required: true },
@@ -56,14 +55,14 @@ const supportLightEventSchema = new mongoose.Schema({
56
55
 
57
56
  supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
58
57
  supportLightEventSchema.index({ patientId: 1, at: -1 });
59
- supportLightEventSchema.index({ service: 1, to: 1, at: 1 });
60
- supportLightEventSchema.index({ at: 1 });
61
58
 
62
59
  const supportLightSweepSchema = new mongoose.Schema({
63
60
  patientId: { type: String, required: true, unique: true },
64
- lastAttemptAt: { type: Date, required: true },
61
+ lastAttemptAt: { type: Date, default: null },
65
62
  lastEvaluatedAt: { type: Date, default: null },
66
63
  lastOutcome: { type: String, required: true },
64
+ claimedUntil: { type: Date, default: null },
65
+ claimToken: { type: String, default: null },
67
66
  }, { timestamps: true });
68
67
 
69
68
  function getSupportLightModel() {
@@ -224,13 +224,27 @@ async function rememberEmergency(code, recordId, urgencyFhir) {
224
224
  if (recordId && !isShadowRun()) await recentEmergencyCache.set(code, { recordId, urgencyFhir });
225
225
  }
226
226
 
227
- async function recordEmergency({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true }) {
227
+ const emergencyWrites = new Map();
228
+
229
+ function serializedEmergencyWrite(code, write) {
230
+ const run = (emergencyWrites.get(code) || Promise.resolve()).then(write);
231
+ const settled = run.catch(() => null);
232
+ emergencyWrites.set(code, settled);
233
+ settled.then(() => { if (emergencyWrites.get(code) === settled) emergencyWrites.delete(code); });
234
+ return run;
235
+ }
236
+
237
+ function recordEmergency(params) {
238
+ return serializedEmergencyWrite(params.code, () => recordEmergencyNow(params));
239
+ }
240
+
241
+ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true, anchor = null, keepOpenRow = false, onRecorded = null }) {
228
242
  const level = urgencyLevel || MEDICAL_URGENCY_TO_EMERGENCY_LEVEL[urgencyFhir] || 'Alta';
229
- const prior = mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null;
243
+ const prior = anchor?.recordId ? anchor : (mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null);
230
244
  const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
231
245
  const priorRank = prior ? EMERGENCY_URGENCY_RANK[prior.urgencyFhir] : undefined;
232
246
  const mergeable = Boolean(prior) && rank !== undefined && priorRank !== undefined && rank <= priorRank;
233
- const belowPrior = mergeable && rank < priorRank;
247
+ const belowPrior = mergeable && (rank < priorRank || keepOpenRow);
234
248
  const meta = {};
235
249
 
236
250
  return auditedWrite({
@@ -266,6 +280,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
266
280
  meta.mergedInto = prior.recordId;
267
281
  if (belowPrior) meta.keptUrgencyFhir = prior.urgencyFhir;
268
282
  await rememberEmergency(code, prior.recordId, belowPrior ? prior.urgencyFhir : urgencyFhir);
283
+ onRecorded?.(prior.recordId);
269
284
  return updated;
270
285
  }
271
286
  }
@@ -274,6 +289,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
274
289
  const created = await airtableService.addRecord(Monitoreo_ID, 'emergencies', [{ fields }], code);
275
290
  const record = Array.isArray(created) ? created[0] : created;
276
291
  await rememberEmergency(code, record?.id, mergeWithRecent ? urgencyFhir : null);
292
+ if (record?.id) onRecorded?.(record.id);
277
293
  return created;
278
294
  },
279
295
  });
@@ -1,3 +1,5 @@
1
+ const { randomUUID } = require('crypto');
2
+
1
3
  const { requireGatewayProvider } = require('../config/llmConfig');
2
4
  const { getSupportLightEvaluator } = require('../config/subAgentsConfig');
3
5
  const { getSupportLightSweepModel } = require('../models/supportLightModel');
@@ -16,16 +18,26 @@ const DEFAULT_WINDOW_DAYS = 14;
16
18
  const MAX_MESSAGES = 60;
17
19
  const MAX_PATIENT_MESSAGES = 20;
18
20
  const CANDIDATE_PAGE = 200;
21
+ const MAX_CANDIDATE_PAGES = 10;
22
+ const CLAIM_MINUTES = 15;
19
23
  const SETTLED_OUTCOMES = ['evaluated', 'no_messages'];
20
24
  const MAX_REASON_CHARS = 500;
21
25
  const MAX_EVIDENCE = 5;
22
26
  const INTERNAL_ORIGINS = ['system', 'instruction'];
27
+ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
28
+ const DUPLICATE_KEY_ERROR = 11000;
29
+ const MINUTE_MS = 60 * 1000;
23
30
  const SERVICES = Object.keys(LIGHT_SCALE);
24
31
 
32
+ function speakerOf(message) {
33
+ if (message.from_me) return 'Equipo';
34
+ return message.contact_role === 'caregiver' ? 'Cuidador(a)' : 'Paciente';
35
+ }
36
+
25
37
  function transcriptOf(messages) {
26
38
  return messages.map((message, index) => {
27
39
  const at = new Date(message.createdAt).toISOString().slice(0, 16).replace('T', ' ');
28
- return `[${index}] ${at} ${message.from_me ? 'Equipo' : 'Paciente'}: ${String(message.body || '').trim()}`;
40
+ return `[${index}] ${at} ${speakerOf(message)}: ${String(message.body || '').trim()}`;
29
41
  }).join('\n');
30
42
  }
31
43
 
@@ -45,9 +57,10 @@ async function readRecentMessages(patientId, { now, windowDays, readMessages })
45
57
  numero: patientId,
46
58
  createdAt: { $gte: new Date(now.getTime() - windowDays * DAY_MS) },
47
59
  origin: { $nin: INTERNAL_ORIGINS },
60
+ 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
48
61
  body: { $regex: '\\S' },
49
62
  };
50
- const options = { sort: { createdAt: -1 }, select: '_id body from_me createdAt' };
63
+ const options = { sort: { createdAt: -1 }, select: '_id body from_me contact_role createdAt' };
51
64
  const [recent, fromPatient] = await Promise.all([
52
65
  readMessages(query, { ...options, limit: MAX_MESSAGES }),
53
66
  readMessages({ ...query, from_me: false }, { ...options, limit: MAX_PATIENT_MESSAGES }),
@@ -95,7 +108,7 @@ async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel
95
108
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
96
109
  const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
97
110
  const selected = [];
98
- for (let page = 0; selected.length < limit; page += 1) {
111
+ for (let page = 0; selected.length < limit && page < MAX_CANDIDATE_PAGES; page += 1) {
99
112
  const active = await aggregateMessages([
100
113
  { $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
101
114
  { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
@@ -107,7 +120,7 @@ async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel
107
120
  if (!ids.length) break;
108
121
  const recent = await SweepModel.find({
109
122
  patientId: { $in: ids },
110
- $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }],
123
+ $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }, { claimedUntil: { $gt: now } }],
111
124
  }).select('patientId').lean();
112
125
  const done = new Set(recent.map((row) => row.patientId));
113
126
  selected.push(...ids.filter((id) => !done.has(id)));
@@ -121,24 +134,72 @@ function validPatientIds(ids) {
121
134
  }
122
135
 
123
136
  function sweepState(outcome, now) {
124
- return { lastAttemptAt: now, lastOutcome: outcome, ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}) };
137
+ return {
138
+ lastAttemptAt: now, lastOutcome: outcome, claimedUntil: null, claimToken: null,
139
+ ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}),
140
+ };
141
+ }
142
+
143
+ function stillDue({ now, cadenceHours }) {
144
+ const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
145
+ const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
146
+ return [
147
+ { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: since } }] },
148
+ { $or: [{ lastAttemptAt: null }, { lastAttemptAt: { $lt: retrySince } }] },
149
+ ];
150
+ }
151
+
152
+ async function claimPatient(SweepModel, patientId, clock, conditions = []) {
153
+ const at = clock();
154
+ const claimToken = randomUUID();
155
+ try {
156
+ const claimed = await SweepModel.findOneAndUpdate(
157
+ { patientId, $and: [{ $or: [{ claimedUntil: null }, { claimedUntil: { $lte: at } }] }, ...conditions] },
158
+ { $set: { claimedUntil: new Date(at.getTime() + CLAIM_MINUTES * MINUTE_MS), claimToken }, $setOnInsert: { lastOutcome: 'claimed' } },
159
+ { upsert: true, new: true },
160
+ );
161
+ return claimed ? claimToken : null;
162
+ } catch (error) {
163
+ if (error?.code === DUPLICATE_KEY_ERROR) return null;
164
+ throw error;
165
+ }
166
+ }
167
+
168
+ async function settleClaim(SweepModel, patientId, claimToken, update) {
169
+ try {
170
+ const settled = await SweepModel.updateOne({ patientId, claimToken }, { $set: update });
171
+ if (!settled?.matchedCount) logger.warn('[supportLightEvaluation] claim lost before its outcome was recorded', { code: patientId });
172
+ } catch (stateError) {
173
+ logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
174
+ }
125
175
  }
126
176
 
127
177
  async function runSupportLightSweep({
128
178
  now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
129
- } = {}, { SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, ...deps } = {}) {
130
- const candidates = Array.isArray(patientIds)
179
+ } = {}, {
180
+ SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, getConfig = getSupportLightEvaluator,
181
+ clock = () => new Date(), ...deps
182
+ } = {}) {
183
+ const config = await getConfig();
184
+ if (!config?.presetId) return { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [], outcome: 'not_configured' };
185
+ const isBackfill = Array.isArray(patientIds);
186
+ const candidates = isBackfill
131
187
  ? validPatientIds(patientIds).slice(0, limit)
132
188
  : await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
133
- const summary = { evaluated: 0, skipped: 0, failed: 0, changes: [] };
189
+ const evaluationDeps = { ...deps, getConfig: async () => config };
190
+ const summary = { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [] };
134
191
  for (const patientId of candidates) {
192
+ const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours }));
193
+ if (!claimToken) {
194
+ summary.busy += 1;
195
+ continue;
196
+ }
135
197
  let outcome = 'error';
136
198
  try {
137
- const result = await evaluate({ patientId, now, windowDays }, deps);
138
- if (result.outcome === 'not_configured') return { ...summary, outcome: 'not_configured' };
199
+ const result = await evaluate({ patientId, now, windowDays }, evaluationDeps);
139
200
  outcome = result.outcome;
140
201
  if (outcome === 'evaluated' || outcome === 'partial') {
141
- summary.evaluated += 1;
202
+ summary[outcome] += 1;
142
203
  summary.changes.push(...result.changes.map((change) => ({ patientId, ...change })));
143
204
  } else {
144
205
  summary.skipped += 1;
@@ -147,13 +208,9 @@ async function runSupportLightSweep({
147
208
  summary.failed += 1;
148
209
  logger.error('[supportLightEvaluation] patient evaluation failed', { code: patientId, error: error.message, stack: error.stack });
149
210
  }
150
- try {
151
- await SweepModel.updateOne({ patientId }, { $set: sweepState(outcome, now) }, { upsert: true });
152
- } catch (stateError) {
153
- logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
154
- }
211
+ await settleClaim(SweepModel, patientId, claimToken, sweepState(outcome, now));
155
212
  }
156
- return { ...summary, outcome: 'completed' };
213
+ return { ...summary, outcome: isBackfill && summary.busy ? 'incomplete' : 'completed' };
157
214
  }
158
215
 
159
216
  module.exports = { evaluatePatientSupport, runSupportLightSweep };
@@ -1,14 +1,10 @@
1
1
  const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
2
2
  const { logger } = require('../../utils/logger');
3
- const { supportLightFromChatLive } = require('../flags/supportLightFlags');
4
3
  const { nextLight } = require('./supportInvitability');
5
4
 
6
5
  const AI_ACTOR = 'ai';
7
6
  const BOARD_LIMIT = 2000;
8
7
  const HISTORY_READ_LIMIT = 200;
9
- const EVENT_READ_LIMIT = 500;
10
- const MAX_CHAT_REASON_CHARS = 1000;
11
- const RISK_FIELD = { nutrition: 'nutritionRisk', psychology: 'psychologyRisk' };
12
8
 
13
9
  function requireText(value, name) {
14
10
  if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
@@ -140,26 +136,6 @@ async function readSupportLights(patientId, { Model = getSupportLightModel() } =
140
136
  return Model.find({ patientId }).select('-outbox').lean();
141
137
  }
142
138
 
143
- function eventKey(event) {
144
- return `${event.patientId}:${event.service}:${event.revision}`;
145
- }
146
-
147
- function withOutboxEvents(stored, lights, isWanted = () => true) {
148
- const byKey = new Map(stored.map((event) => [eventKey(event), event]));
149
- for (const light of lights) {
150
- for (const outboxEvent of light.outbox || []) {
151
- const event = { ...outboxEvent, patientId: light.patientId, service: light.service };
152
- if (isWanted(event) && !byKey.has(eventKey(event))) byKey.set(eventKey(event), event);
153
- }
154
- }
155
- return [...byKey.values()];
156
- }
157
-
158
- function byTimeThenIdentity(left, right) {
159
- return new Date(left.at) - new Date(right.at) || left.patientId.localeCompare(right.patientId)
160
- || left.service.localeCompare(right.service) || left.revision - right.revision;
161
- }
162
-
163
139
  async function readSupportLightHistory(patientId, {
164
140
  service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
165
141
  } = {}) {
@@ -170,7 +146,14 @@ async function readSupportLightHistory(patientId, {
170
146
  EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
171
147
  Model.find(scope).select('patientId service outbox').lean(),
172
148
  ]);
173
- return withOutboxEvents(stored, lights)
149
+ const byKey = new Map(stored.map((event) => [`${event.service}:${event.revision}`, event]));
150
+ for (const light of lights) {
151
+ for (const event of light.outbox || []) {
152
+ const key = `${light.service}:${event.revision}`;
153
+ if (!byKey.has(key)) byKey.set(key, { ...event, patientId: light.patientId, service: light.service });
154
+ }
155
+ }
156
+ return [...byKey.values()]
174
157
  .sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
175
158
  || left.service.localeCompare(right.service))
176
159
  .slice(0, bounded);
@@ -207,59 +190,8 @@ async function readSupportLightBoard({ service = null, color = null, isPendingOn
207
190
  ]).option({ maxTimeMS: 10000, allowDiskUse: true });
208
191
  }
209
192
 
210
- async function readSupportLightEvents({
211
- since, service = null, outcome = null, to = null,
212
- } = {}, { limit = EVENT_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
213
- const from = since == null ? null : new Date(since);
214
- if (!from || Number.isNaN(from.getTime())) throw new Error('since is required');
215
- const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, EVENT_READ_LIMIT) : EVENT_READ_LIMIT;
216
- const filters = { ...(outcome ? { outcome } : {}), ...(to ? { to } : {}) };
217
- const [stored, lights] = await Promise.all([
218
- EventModel.find({ at: { $gte: from }, ...(service ? { service } : {}), ...filters })
219
- .sort({ at: 1, patientId: 1, service: 1, revision: 1 }).limit(bounded).lean(),
220
- Model.find({ ...(service ? { service } : {}), outbox: { $elemMatch: { at: { $gte: from }, ...filters } } })
221
- .select('patientId service outbox').sort({ 'outbox.at': 1, patientId: 1, service: 1 }).limit(bounded).lean(),
222
- ]);
223
- const isWanted = (event) => new Date(event.at) >= from && Object.entries(filters).every(([field, value]) => event[field] === value);
224
- return withOutboxEvents(stored, lights, isWanted).sort(byTimeThenIdentity).slice(0, bounded);
225
- }
226
-
227
- function chatReading(recommendation, decision) {
228
- const color = decision[RISK_FIELD[decision.service]];
229
- if (!color) return null;
230
- const summaries = decision.evidence.map((item) => item.summary).filter(Boolean);
231
- const reason = (summaries.length ? summaries : decision.reasonCodes).join('; ').slice(0, MAX_CHAT_REASON_CHARS) || null;
232
- return {
233
- patientId: recommendation.patientId,
234
- service: decision.service,
235
- color,
236
- source: 'ai',
237
- reason,
238
- evidence: decision.evidence.map((item) => ({ source: 'chat', sourceId: item.sourceId, summary: item.summary ?? item.code ?? null })),
239
- };
240
- }
241
-
242
- async function applyChatSupportReadings(recommendation, { now = new Date(), isLive = supportLightFromChatLive, apply = applySupportLight } = {}) {
243
- if (!isLive()) return [];
244
- const results = [];
245
- for (const decision of recommendation.decisions || []) {
246
- const reading = chatReading(recommendation, decision);
247
- if (!reading) continue;
248
- try {
249
- const { light, outcome } = await apply({ ...reading, now });
250
- results.push({ service: reading.service, color: reading.color, outcome, revision: light?.revision ?? null });
251
- } catch (error) {
252
- logger.error('[supportLight] chat reading not applied', { code: recommendation.patientId, service: reading.service, error: error.message });
253
- results.push({ service: reading.service, color: reading.color, outcome: 'error', revision: null });
254
- }
255
- }
256
- return results;
257
- }
258
-
259
193
  module.exports = {
260
- applyChatSupportReadings,
261
194
  applySupportLight,
262
- readSupportLightEvents,
263
195
  readSupportLightBoard,
264
196
  resolvePendingImprovement,
265
197
  readSupportLights,
@@ -48,13 +48,14 @@ function registerClinicalTools() {
48
48
  unregisterTool(analyzeSymptomPatternsTool.definition.name);
49
49
  for (const tool of tools) unregisterTool(tool.definition.name);
50
50
  for (const tool of tools) {
51
+ const definition = tool.liveDefinition ? tool.liveDefinition() : tool.definition;
51
52
  registerTool({
52
- name: tool.definition.name,
53
- description: tool.definition.description,
54
- parameters: tool.definition.parameters,
55
- strict: tool.definition.strict,
56
- replayScope: tool.definition.replayScope,
57
- replayArgs: tool.definition.replayArgs,
53
+ name: definition.name,
54
+ description: definition.description,
55
+ parameters: definition.parameters,
56
+ strict: definition.strict,
57
+ replayScope: definition.replayScope,
58
+ replayArgs: definition.replayArgs,
58
59
  handler: tool.handler,
59
60
  });
60
61
  }
@@ -1,3 +1,5 @@
1
+ const { randomUUID } = require('crypto');
2
+
1
3
  const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
2
4
  const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
3
5
  const { isShadowRun } = require('../helpers/shadowHelper');
@@ -5,7 +7,9 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
5
7
  const { dispatcherService } = require('../services/dispatcherService');
6
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
7
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
8
- const { recordEscalationAlarm } = require('../../services/escalationReviewService');
10
+ const { escalationAssessmentLive, escalationUpdateModeLive } = require('../flags/escalationFlags');
11
+ const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
+ const { URGENCY_RANK } = require('../../models/escalationReviewModel');
9
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
10
14
  const { logger } = require('../../utils/logger');
11
15
 
@@ -134,6 +138,104 @@ const definition = {
134
138
  }
135
139
  };
136
140
 
141
+ const nullable = (schema) => ({ 'anyOf': [schema, { 'type': 'null' }] });
142
+ const nullableEnum = (values) => nullable({ 'type': 'string', 'enum': values });
143
+
144
+ const MODE_PROPERTY = {
145
+ 'type': 'string',
146
+ 'enum': ['new', 'update'],
147
+ 'description': '`new`: primer aviso de este episodio. `update`: agrega lo nuevo a la escalación que sigue abierta para este paciente, sin generar otro aviso al equipo si el nivel no sube. El nivel aplicado es el mayor entre el abierto y el que pides: uno menor no baja la escalación, queda registrado como sugerencia para el equipo. Usa `update` para sumar lo que respondió el paciente y para subir el nivel en cuanto un dato nuevo haga plausible algo más grave.',
148
+ };
149
+
150
+ const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
151
+
152
+ const CLINICAL_ASSESSMENT_PROPERTY = nullable({
153
+ 'type': 'object',
154
+ 'description': 'Tu razonamiento clínico, estructurado para auditoría. Todos los campos aceptan `null`. No cambia el nivel: el nivel lo decides tú en `urgency_level`.',
155
+ 'properties': {
156
+ 'serious_hypotheses': nullable({
157
+ 'type': 'array',
158
+ 'items': {
159
+ 'type': 'object',
160
+ 'properties': {
161
+ 'label': { 'type': 'string' },
162
+ 'status': { 'type': 'string', 'enum': ['ruled_out', 'not_ruled_out', 'supported', 'unknown'] },
163
+ 'key_evidence': nullable({ 'type': 'string' }),
164
+ },
165
+ 'required': ['label', 'status', 'key_evidence'],
166
+ 'additionalProperties': false,
167
+ },
168
+ 'description': 'Cuadros graves que consideraste y en qué quedaron.',
169
+ }),
170
+ 'known_explanation': nullable({
171
+ 'type': 'object',
172
+ 'properties': {
173
+ 'present': nullable({ 'type': 'boolean' }),
174
+ 'plan_in_course': nullable({ 'type': 'boolean' }),
175
+ 'what': nullable({ 'type': 'string' }),
176
+ },
177
+ 'required': ['present', 'plan_in_course', 'what'],
178
+ 'additionalProperties': false,
179
+ 'description': 'Si el síntoma tiene una explicación conocida (cirugía, procedimiento, efecto esperado) y si ya hay un manejo indicado.',
180
+ }),
181
+ 'response_to_prior_management': nullableEnum(['complete', 'partial', 'none', 'worse', 'not_applicable', 'unknown']),
182
+ 'trajectory': nullableEnum(['better', 'same', 'worse', 'unknown']),
183
+ 'temporality': nullableEnum(['current', 'recent_resolved', 'past', 'unknown']),
184
+ 'missing_to_rule_out': nullable({ 'type': 'array', 'items': { 'type': 'string' }, 'description': 'Lo que falta preguntar para descartar lo grave.' }),
185
+ 'characterization_incomplete': nullable({ 'type': 'boolean', 'description': '`true` si el paciente dejó de responder antes de completar la caracterización.' }),
186
+ },
187
+ 'required': ['serious_hypotheses', 'known_explanation', 'response_to_prior_management', 'trajectory', 'temporality', 'missing_to_rule_out', 'characterization_incomplete'],
188
+ 'additionalProperties': false,
189
+ });
190
+
191
+ function liveDefinition() {
192
+ const updateMode = escalationUpdateModeLive();
193
+ const assessment = escalationAssessmentLive();
194
+ if (!updateMode && !assessment) return definition;
195
+ const live = structuredClone(definition);
196
+ const { properties, required } = live.parameters;
197
+ if (updateMode) {
198
+ live.description += MODE_DESCRIPTION;
199
+ properties.mode = MODE_PROPERTY;
200
+ required.push('mode');
201
+ }
202
+ if (assessment) {
203
+ properties.details.properties.clinical_assessment = CLINICAL_ASSESSMENT_PROPERTY;
204
+ properties.details.required.push('clinical_assessment');
205
+ }
206
+ return live;
207
+ }
208
+
209
+ const yesNo = (value) => (value === true ? 'sí' : value === false ? 'no' : null);
210
+
211
+ function knownExplanationNote(known) {
212
+ if (!isPlainObject(known)) return '';
213
+ const parts = [
214
+ yesNo(known.present) && `presente: ${yesNo(known.present)}`,
215
+ known.what,
216
+ yesNo(known.plan_in_course) && `manejo en curso: ${yesNo(known.plan_in_course)}`,
217
+ ].filter(Boolean);
218
+ return parts.length ? `Explicación conocida: ${parts.join(', ')}` : '';
219
+ }
220
+
221
+ function assessmentNote(assessment) {
222
+ if (!isPlainObject(assessment)) return '';
223
+ const hypotheses = (Array.isArray(assessment.serious_hypotheses) ? assessment.serious_hypotheses : [])
224
+ .filter((hypothesis) => hypothesis?.label)
225
+ .map((hypothesis) => `${hypothesis.label} (${hypothesis.status || 'unknown'})`)
226
+ .join('; ');
227
+ const missing = Array.isArray(assessment.missing_to_rule_out) ? assessment.missing_to_rule_out.filter(Boolean).join('; ') : '';
228
+ return [
229
+ assessment.temporality && `Temporalidad: ${assessment.temporality}`,
230
+ assessment.trajectory && `Trayectoria: ${assessment.trajectory}`,
231
+ assessment.response_to_prior_management && `Respuesta al manejo: ${assessment.response_to_prior_management}`,
232
+ hypotheses && `Hipótesis graves: ${hypotheses}`,
233
+ knownExplanationNote(assessment.known_explanation),
234
+ missing && `Falta para descartar: ${missing}`,
235
+ yesNo(assessment.characterization_incomplete) && `Caracterización incompleta: ${yesNo(assessment.characterization_incomplete)}`,
236
+ ].filter(Boolean).join(' · ');
237
+ }
238
+
137
239
  function followUpNote(armed, reason) {
138
240
  if (armed) {
139
241
  return 'An automatic check-in is armed for this escalation: if the patient goes silent, they will be contacted again about it.';
@@ -148,6 +250,7 @@ function followUpNote(armed, reason) {
148
250
  }
149
251
 
150
252
  const CATEGORIES = definition.parameters.properties.details.properties.category.anyOf.find((v) => v.enum).enum;
253
+ const LEVELS = definition.parameters.properties.urgency_level.enum;
151
254
 
152
255
  async function handler(args, context = {}) {
153
256
  try {
@@ -157,10 +260,10 @@ async function handler(args, context = {}) {
157
260
  logger.error('[reportMedicalEscalation] Medical escalation dropped — no active turn trace', { patientCode: runtime?.patientCode || null });
158
261
  return JSON.stringify({ success: false, error: 'reportMedicalEscalation requires an active turn context (trace).' });
159
262
  }
160
- const levels = definition.parameters.properties.urgency_level.enum;
161
263
  const requested = (args?.urgency_level || '').trim().toLowerCase();
162
- const isCoerced = !levels.includes(requested);
163
- const urgencyLevel = isCoerced ? 'urgent' : requested;
264
+ const isCoerced = !LEVELS.includes(requested);
265
+ const requestedLevel = isCoerced ? 'urgent' : requested;
266
+ const updateMode = escalationUpdateModeLive() && args?.mode === 'update';
164
267
  const rawDetails = args?.details;
165
268
  const parsedDetails = objectArg(rawDetails);
166
269
  const details = parsedDetails || {};
@@ -168,19 +271,46 @@ async function handler(args, context = {}) {
168
271
  const requestedCategory = typeof rawCategory === 'string' ? rawCategory.trim() : rawCategory;
169
272
  const category = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
170
273
  const categoryCoerced = rawCategory !== null && category === null;
274
+ const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
171
275
  const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
172
276
  const detailsArg = typeof rawDetails === 'string'
173
277
  ? (parsedDetails ? (strictlyParsed ? 'decoded' : 'recovered') : 'unreadable')
174
278
  : (parsedDetails ? 'object' : 'absent');
175
279
  if (detailsArg === 'recovered') {
176
- logger.warn('[reportMedicalEscalation] details arrived as malformed JSON and was recovered from its balanced prefix', { turnId: runtime.turnId, urgencyLevel });
280
+ logger.warn('[reportMedicalEscalation] details arrived as malformed JSON and was recovered from its balanced prefix', { turnId: runtime.turnId, urgencyLevel: requestedLevel });
177
281
  }
178
282
  if (detailsArg === 'unreadable') {
179
- logger.error('[reportMedicalEscalation] details arrived as a string that is not valid JSON', { turnId: runtime.turnId, urgencyLevel });
283
+ logger.error('[reportMedicalEscalation] details arrived as a string that is not valid JSON', { turnId: runtime.turnId, urgencyLevel: requestedLevel });
180
284
  const justification = String(args?.urgency_justification || '').trim();
181
285
  if (justification) details.symptom = `Sin síntoma estructurado — ${justification}`;
182
286
  }
183
287
 
288
+ const alarmId = randomUUID();
289
+ const recordsAlarm = Boolean(runtime.patientCode) && requestedLevel !== 'routine' && !isShadowRun() && runtime.isLive?.() !== false;
290
+ const review = recordsAlarm
291
+ ? await recordEscalationAlarm({
292
+ code: runtime.patientCode,
293
+ alarm: {
294
+ alarmId,
295
+ urgencyLevel: requestedLevel,
296
+ category,
297
+ symptom: details.symptom || null,
298
+ evidenceQuote: details.evidence_quote || null,
299
+ suspectedCondition: details.suspected_condition || null,
300
+ recommendedAction: details.recommended_action || null,
301
+ justification: args?.urgency_justification || null,
302
+ indicators: (Array.isArray(details.indicators) ? details.indicators : [])
303
+ .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
304
+ turnId: runtime.turnId || null,
305
+ ...(clinicalAssessment ? { clinicalAssessment } : {}),
306
+ },
307
+ })
308
+ : null;
309
+ const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
310
+ const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
311
+ const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
312
+ const raisesOpen = !anchor || (URGENCY_RANK[requestedLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
313
+
184
314
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
185
315
  trace.setSignals({
186
316
  medicalEscalation: {
@@ -199,10 +329,12 @@ async function handler(args, context = {}) {
199
329
  coercedUrgency: isCoerced,
200
330
  requestedUrgencyLevel: requested,
201
331
  detailsArg,
332
+ ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
333
+ ...(clinicalAssessment ? { clinicalAssessment } : {}),
202
334
  },
203
335
  });
204
336
 
205
- if (runtime.turnId && runtime.patientCode) {
337
+ if (runtime.turnId && runtime.patientCode && raisesOpen) {
206
338
  try {
207
339
  await dispatcherService.dispatch({
208
340
  trace,
@@ -231,21 +363,7 @@ async function handler(args, context = {}) {
231
363
  });
232
364
  queued = written || duplicate;
233
365
  } else {
234
- if (!isShadowRun() && runtime.isLive?.() !== false) await recordEscalationAlarm({
235
- code: runtime.patientCode,
236
- alarm: {
237
- urgencyLevel,
238
- category,
239
- symptom: details.symptom || null,
240
- evidenceQuote: details.evidence_quote || null,
241
- suspectedCondition: details.suspected_condition || null,
242
- recommendedAction: details.recommended_action || null,
243
- justification: args?.urgency_justification || null,
244
- indicators: (Array.isArray(details.indicators) ? details.indicators : [])
245
- .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
246
- turnId: runtime.turnId || null,
247
- },
248
- });
366
+ let emergencyRecordId = null;
249
367
  queued = await recordEmergency({
250
368
  code: runtime.patientCode,
251
369
  trace,
@@ -254,10 +372,16 @@ async function handler(args, context = {}) {
254
372
  recommendedAction: details.recommended_action || '',
255
373
  urgencyFhir: urgencyLevel,
256
374
  documentation: [
375
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
257
376
  args?.urgency_justification || '',
258
377
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
378
+ assessmentNote(clinicalAssessment),
259
379
  ].filter(Boolean).join('\n'),
380
+ anchor: anchor?.emergencyRecordId ? { recordId: anchor.emergencyRecordId, urgencyFhir: anchor.urgencyLevel } : null,
381
+ keepOpenRow: keptOpenLevel,
382
+ onRecorded: (recordId) => { emergencyRecordId = recordId; },
260
383
  });
384
+ if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId });
261
385
  try {
262
386
  const net = queued ? await armEscalationNet({
263
387
  patientCode: runtime.patientCode,
@@ -292,6 +416,8 @@ async function handler(args, context = {}) {
292
416
  ? 'The escalation is QUEUED for the care team. This is not confirmation that anyone has read or acted on it, and no reply has arrived. Do not tell the patient the team already reviewed it, and do not treat the topic as closed on the strength of this ack.'
293
417
  : 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
294
418
  follow_up: followUpNote(netArmed, netReason),
419
+ ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
420
+ ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
295
421
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
296
422
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
297
423
  ...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
@@ -304,5 +430,6 @@ async function handler(args, context = {}) {
304
430
 
305
431
  module.exports = {
306
432
  definition,
433
+ liveDefinition,
307
434
  handler,
308
435
  };
@@ -1,7 +1,6 @@
1
1
  const { ZodError } = require('zod');
2
2
 
3
3
  const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
4
- const { applyChatSupportReadings } = require('../services/supportLightService');
5
4
  const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
6
5
 
7
6
  const decisionProperties = {
@@ -44,7 +43,7 @@ const decisionProperties = {
44
43
 
45
44
  const definition = {
46
45
  name: 'submitSupportRoutingRecommendation',
47
- description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. The specialty risk also updates the patient support light: a higher risk applies at once, a lower one waits for a specialist to confirm. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
46
+ description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
48
47
  strict: false,
49
48
  parameters: {
50
49
  type: 'object',
@@ -117,7 +116,6 @@ async function handler(args = {}, context = {}) {
117
116
  });
118
117
  if (!isRuntimeLive(runtime)) return inactiveTurn();
119
118
  const candidates = await recordSupportRoutingRecommendation(recommendation);
120
- const lights = await applyChatSupportReadings(recommendation);
121
119
  runtime.trace?.setSignals?.({
122
120
  supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
123
121
  });
@@ -130,7 +128,6 @@ async function handler(args = {}, context = {}) {
130
128
  service: candidate.service,
131
129
  disposition: candidate.disposition,
132
130
  })),
133
- lights,
134
131
  invitation_sent: false,
135
132
  },
136
133
  });
package/lib/index.d.ts CHANGED
@@ -1006,18 +1006,6 @@ declare module '@peopl-health/nexus' {
1006
1006
  isPendingOnly?: boolean;
1007
1007
  }, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
1008
1008
  readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
1009
- readSupportLightEvents(filters: {
1010
- since: Date | string;
1011
- service?: SupportService | null;
1012
- outcome?: SupportLightEventRecord['outcome'] | null;
1013
- to?: SupportLightColor | null;
1014
- }, options?: { limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
1015
- applyChatSupportReadings(recommendation: Pick<SupportRoutingRecommendationInput, 'patientId' | 'decisions'>, options?: { now?: Date; isLive?: () => boolean; apply?: unknown }): Promise<Array<{
1016
- service: SupportService;
1017
- color: SupportLightColor;
1018
- outcome: SupportLightOutcome | 'stale' | 'error';
1019
- revision: number | null;
1020
- }>>;
1021
1009
  };
1022
1010
 
1023
1011
  export const supportInvitability: {
@@ -1064,8 +1052,10 @@ declare module '@peopl-health/nexus' {
1064
1052
  windowDays?: number;
1065
1053
  limit?: number;
1066
1054
  }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
1067
- outcome: 'completed' | 'not_configured';
1055
+ outcome: 'completed' | 'incomplete' | 'not_configured';
1068
1056
  evaluated: number;
1057
+ partial: number;
1058
+ busy: number;
1069
1059
  skipped: number;
1070
1060
  failed: number;
1071
1061
  changes: SupportLightSweepChange[];
@@ -16,6 +16,7 @@ const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
16
16
  const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
17
17
 
18
18
  const alarmSchema = new mongoose.Schema({
19
+ alarmId: { type: String, default: null },
19
20
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
20
21
  category: { type: String, default: null },
21
22
  symptom: { type: String, default: null },
@@ -25,6 +26,8 @@ const alarmSchema = new mongoose.Schema({
25
26
  justification: { type: String, default: null },
26
27
  indicators: { type: [String], default: undefined },
27
28
  turnId: { type: String, default: null },
29
+ clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
30
+ emergencyRecordId: { type: String, default: null },
28
31
  raisedAt: { type: Date, required: true },
29
32
  }, { _id: false });
30
33
 
@@ -543,6 +543,30 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
543
543
  }
544
544
  }
545
545
 
546
+ function escalationAnchorOf(review, alarmId) {
547
+ const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
548
+ if (!prior.length) return null;
549
+ const rankOf = (alarm) => URGENCY_RANK[alarm.urgencyLevel] || 0;
550
+ const topRank = Math.max(...prior.map(rankOf));
551
+ const top = prior.filter((alarm) => rankOf(alarm) === topRank);
552
+ const topRow = [...top].reverse().find((alarm) => alarm.emergencyRecordId);
553
+ return { urgencyLevel: top[0].urgencyLevel, emergencyRecordId: topRow?.emergencyRecordId || null };
554
+ }
555
+
556
+ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId }) {
557
+ try {
558
+ await getEscalationReview().updateOne(
559
+ { _id: reviewId, 'alarms.alarmId': alarmId },
560
+ { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId } },
561
+ { timestamps: false },
562
+ );
563
+ } catch (error) {
564
+ logger.error('[EscalationReview] The emergency row was not linked to its alarm', {
565
+ error: error.message, stack: redactedStack(error),
566
+ });
567
+ }
568
+ }
569
+
546
570
  async function openEscalationReview({
547
571
  code,
548
572
  patientCaseRecordId = null,
@@ -837,11 +861,15 @@ async function prepareDoctorAlert(review, kind, urgencyLevel) {
837
861
  return { approver, message };
838
862
  }
839
863
 
864
+ const currentAlarms = (review) => {
865
+ const alarms = review?.alarms ?? [];
866
+ const decidedAt = (review?.decisions ?? []).at(-1)?.createdAt;
867
+ return decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
868
+ };
869
+
840
870
  const topUrgencyOf = (review) => {
841
- const alarms = review.alarms ?? [];
842
- const decidedAt = (review.decisions ?? []).at(-1)?.createdAt;
843
- const open = decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
844
- return (open.length ? open : alarms)
871
+ const open = currentAlarms(review);
872
+ return (open.length ? open : review.alarms ?? [])
845
873
  .reduce((top, alarm) => (URGENCY_RANK[alarm.urgencyLevel] > (URGENCY_RANK[top] || 0) ? alarm.urgencyLevel : top), null);
846
874
  };
847
875
 
@@ -1720,8 +1748,10 @@ module.exports = {
1720
1748
  _resetEscalationReviewIndexes,
1721
1749
  addCallLog,
1722
1750
  addDraft,
1751
+ attachEmergencyRow,
1723
1752
  cancelEscalationReview,
1724
1753
  closeEscalationReview,
1754
+ escalationAnchorOf,
1725
1755
  generateBotDraft,
1726
1756
  getEscalationReviewById,
1727
1757
  getReviewTimeline,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.62.0-dev.11344",
3
+ "version": "5.62.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,7 +0,0 @@
1
- const runtimeConfig = require('../../config/runtimeConfig');
2
-
3
- function supportLightFromChatLive() {
4
- return String(runtimeConfig.get('SUPPORT_LIGHT_FROM_CHAT', 'false')).trim().toLowerCase() === 'true';
5
- }
6
-
7
- module.exports = { supportLightFromChatLive };