@peopl-health/nexus 5.61.0-dev.11186 → 5.61.0-dev.11231

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.
@@ -216,7 +216,6 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
216
216
  }
217
217
 
218
218
  module.exports = {
219
- MAX_NOTE_LENGTH,
220
219
  openCaseIds,
221
220
  getPatientTasks,
222
221
  updatePatientTask,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.61.0-dev.11186",
3
+ "version": "5.61.0-dev.11231",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,74 +0,0 @@
1
- const { objectArg } = require('../../utils/jsonUtils');
2
- const { isToolFailure } = require('./toolResultHelper');
3
-
4
- const IMPRESSION_TOOLS = ['openCondition', 'recordClinicalImpression'];
5
- const CHARACTERIZATION_TOOLS = ['extractClinicalInfo', ...IMPRESSION_TOOLS, 'reportMedicalEscalation'];
6
- const MAX_PATIENT_TEXT = 500;
7
-
8
- const textOf = (value) => {
9
- const text = typeof value === 'string' ? value.trim() : '';
10
- return text && text.toLowerCase() !== 'none' ? text : null;
11
- };
12
-
13
- const gradeOf = (gradeEstimate) => {
14
- const grade = objectArg(gradeEstimate)?.best_estimate;
15
- return Number.isInteger(grade) ? grade : null;
16
- };
17
-
18
- const impressionOf = (call) => {
19
- const args = objectArg(call.tool_arguments) || {};
20
- const result = objectArg(call.tool_output)?.data;
21
- return {
22
- caseId: textOf(args.case_id) || textOf(result?.case_id),
23
- ctcaeTerm: textOf(args.ctcae_term),
24
- event: call.tool_name === 'openCondition' ? 'opened' : textOf(args.event),
25
- // A carried-forward grade is resolved by the tool, so its result holds the grade the call omitted.
26
- grade: gradeOf(args.grade_estimate) ?? gradeOf(result?.grade_estimate),
27
- trajectory: textOf(args.trajectory_direction),
28
- missingForHigherGrade: textOf(args.missing_for_higher_grade),
29
- checkInQuestion: textOf(args.check_in_question),
30
- };
31
- };
32
-
33
- const flagNameOf = (flag) => textOf(typeof flag === 'string' ? flag : flag?.flag);
34
-
35
- // What the agent characterized this turn, or null when it did not characterize anything:
36
- // a courtesy reply runs the extractor too, but leaves no mention, impression or escalation behind.
37
- function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText = null, at = new Date() } = {}) {
38
- const calls = toolHistory.filter((call) => CHARACTERIZATION_TOOLS.includes(call?.tool_name) && !isToolFailure(call.tool_output));
39
- const mentionCount = Array.isArray(signals?.clinicalMentions) ? signals.clinicalMentions.length : 0;
40
- const safetyFlags = (Array.isArray(signals?.safetyFlags) ? signals.safetyFlags : []).map(flagNameOf).filter(Boolean);
41
- const assessed = calls.some((call) => call.tool_name !== 'extractClinicalInfo');
42
- if (!turnId || (!assessed && mentionCount === 0 && !safetyFlags.length)) return null;
43
-
44
- return {
45
- turnId,
46
- tools: [...new Set(calls.map((call) => call.tool_name))],
47
- patientText: textOf(patientText)?.slice(0, MAX_PATIENT_TEXT) || null,
48
- impressions: calls.filter((call) => IMPRESSION_TOOLS.includes(call.tool_name)).map(impressionOf),
49
- safetyFlags,
50
- at,
51
- };
52
- }
53
-
54
- // The agent's own reading of each case since the escalation, handed to the draft so it builds on it
55
- // instead of re-deriving it: the latest impression per case, the safety flags and what the patient said.
56
- function characterizationSeedOf(updates = []) {
57
- if (!Array.isArray(updates) || !updates.length) return null;
58
- // Clinical order is the turn time, not the order the writes landed in.
59
- const byTime = [...updates].sort((a, b) => new Date(a.at) - new Date(b.at));
60
- const latestByCase = new Map();
61
- byTime.forEach((update) => (update.impressions || []).forEach((impression) => {
62
- const key = impression.caseId || impression.ctcaeTerm;
63
- if (key) latestByCase.set(key, { ...impression, at: update.at });
64
- }));
65
- return {
66
- cases: [...latestByCase.values()],
67
- safetyFlags: [...new Set(updates.flatMap((update) => update.safetyFlags || []))],
68
- newSinceEscalation: byTime
69
- .filter((update) => update.patientText)
70
- .map((update) => ({ at: update.at, patientText: update.patientText })),
71
- };
72
- }
73
-
74
- module.exports = { characterizationSeedOf, reviewUpdateOf };
@@ -1,88 +0,0 @@
1
- const { logger } = require('../utils/logger');
2
- const { createIntervalSweeper } = require('../utils/intervalSweeper');
3
- const { withTimeout } = require('../utils/timeoutUtils');
4
- const { getEscalationReview } = require('../models/escalationReviewModel');
5
-
6
- const { sendScheduledDoctorAlert } = require('./escalationReviewService');
7
-
8
- const SWEEP_LIMIT = 10;
9
- const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
10
- const LEASE_MS = 5 * 60 * 1000;
11
- // Well inside the lease: an alert never outlives its claim, so two sweeps never send the same one.
12
- const SEND_TIMEOUT_MS = 2 * 60 * 1000;
13
- const MAX_ALERT_ATTEMPTS = 3;
14
- const SELF_HEAL_WINDOW_MS = 60 * 60 * 1000;
15
- const ALERTED_URGENCIES = ['stat', 'asap'];
16
-
17
- // Due alerts, plus a recent stat/asap review that never got its first alert because scheduling it
18
- // failed after the alarm was written.
19
- const dueQuery = (now) => ({
20
- closedAt: null,
21
- $or: [
22
- { doctorAlertDueAt: { $lte: now } },
23
- {
24
- doctorAlertDueAt: null,
25
- 'doctorAlerts.0': { $exists: false },
26
- alarms: { $elemMatch: { urgencyLevel: { $in: ALERTED_URGENCIES }, raisedAt: { $gte: new Date(now.getTime() - SELF_HEAL_WINDOW_MS) } } },
27
- },
28
- ],
29
- });
30
-
31
- async function sweepDoctorAlerts({ now = new Date(), clock = () => new Date() } = {}) {
32
- const EscalationReview = getEscalationReview();
33
- const due = await EscalationReview
34
- .find(dueQuery(now), { _id: 1, doctorAlertDueAt: 1, doctorAlertKind: 1, doctorAlertAttempts: 1 })
35
- .sort({ doctorAlertDueAt: 1 })
36
- .limit(SWEEP_LIMIT)
37
- .lean();
38
-
39
- let sent = 0;
40
- for (const { _id: reviewId, doctorAlertDueAt = null, doctorAlertKind, doctorAlertAttempts = 0 } of due) {
41
- const kind = doctorAlertKind || 'initial';
42
- // Each claim starts its own clock: a slow alert earlier in the pass must not shorten the next lease.
43
- const claimedAt = clock();
44
- try {
45
- if (doctorAlertAttempts >= MAX_ALERT_ATTEMPTS) {
46
- logger.error('[ReviewAlertSweep] The doctor alert failed on every attempt; it is dropped', {
47
- escalationReviewId: String(reviewId), kind, attempts: doctorAlertAttempts,
48
- });
49
- // The drop is on the record, so the recovery of never-sent first alerts does not pick it up again.
50
- await EscalationReview.updateOne(
51
- { _id: reviewId, doctorAlertDueAt },
52
- {
53
- $set: { doctorAlertDueAt: null, doctorAlertKind: null, doctorAlertAttempts: 0 },
54
- $push: { doctorAlerts: { kind, urgencyLevel: null, error: `dropped after ${doctorAlertAttempts} attempts`, sentAt: claimedAt } },
55
- },
56
- );
57
- continue;
58
- }
59
- // Claiming turns the due time into a short lease: a pass that dies or throws leaves the alert
60
- // due again once it expires, and the sender only touches the schedule while the lease is its own.
61
- const lease = new Date(claimedAt.getTime() + LEASE_MS);
62
- const claimed = await EscalationReview
63
- .findOneAndUpdate(
64
- { _id: reviewId, doctorAlertDueAt },
65
- { $set: { doctorAlertDueAt: lease, doctorAlertKind: kind }, $inc: { doctorAlertAttempts: 1 } },
66
- { new: true, projection: { _id: 1 } },
67
- )
68
- .lean();
69
- if (!claimed) continue;
70
- const alert = sendScheduledDoctorAlert({ id: String(reviewId), kind, lease, now: claimedAt });
71
- if (await withTimeout(alert, SEND_TIMEOUT_MS, 'doctor alert')) sent += 1;
72
- } catch (error) {
73
- logger.error('[ReviewAlertSweep] Could not alert the doctor for a review', { escalationReviewId: String(reviewId), error: error.message });
74
- }
75
- }
76
- return sent;
77
- }
78
-
79
- const sweeper = createIntervalSweeper({
80
- label: '[ReviewAlertSweep]',
81
- sweep: () => sweepDoctorAlerts(),
82
- defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
83
- });
84
-
85
- const startReviewAlertSweep = (options) => sweeper.start(options);
86
- const stopReviewAlertSweep = () => sweeper.stop();
87
-
88
- module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -1,79 +0,0 @@
1
- const { logger } = require('../utils/logger');
2
- const { createIntervalSweeper } = require('../utils/intervalSweeper');
3
- const { withTimeout } = require('../utils/timeoutUtils');
4
- const { getEscalationReview } = require('../models/escalationReviewModel');
5
-
6
- const { generateBotDraft } = require('./escalationReviewService');
7
-
8
- // One review per pass keeps a pass inside the sweeper's pass timeout, so shutdown always waits for it.
9
- const SWEEP_LIMIT = 1;
10
- const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
11
- const RETRY_DELAY_MS = 5 * 60 * 1000;
12
- const MAX_DRAFT_ATTEMPTS = 3;
13
- const LEASE_MS = 10 * 60 * 1000;
14
- // Well inside the lease: a run never outlives its claim, so two runs never draft the same review.
15
- const GENERATION_TIMEOUT_MS = 4 * 60 * 1000;
16
-
17
- async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts = 0 }, now) {
18
- // Claiming moves draftDueAt to a lease deadline: a worker that dies mid-draft leaves the review due
19
- // again once the lease expires, and an alarm or update that lands meanwhile replaces the lease.
20
- const lease = new Date(now.getTime() + LEASE_MS);
21
- const claimed = await EscalationReview
22
- .findOneAndUpdate({ _id, draftDueAt }, { $set: { draftDueAt: lease } }, { new: true, projection: { _id: 1 } })
23
- .lean();
24
- if (!claimed) return false;
25
-
26
- let outcome;
27
- try {
28
- outcome = await withTimeout(generateBotDraft({ id: String(_id), lease }), GENERATION_TIMEOUT_MS, 'automatic draft generation');
29
- } catch (error) {
30
- logger.error('[ReviewDraftSweep] The automatic draft threw', { escalationReviewId: String(_id), error: error.message });
31
- outcome = { review: null, retry: true };
32
- }
33
- const { review, retry } = outcome;
34
- if (review) return true;
35
- const willRetry = retry && draftAttempts + 1 < MAX_DRAFT_ATTEMPTS;
36
- if (retry && !willRetry) {
37
- logger.error('[ReviewDraftSweep] The automatic draft failed on every attempt; it waits for new material', {
38
- escalationReviewId: String(_id), attempts: draftAttempts + 1,
39
- });
40
- }
41
- // Releases the lease, unless new material replaced it meanwhile.
42
- await EscalationReview.updateOne(
43
- { _id, draftDueAt: lease },
44
- willRetry
45
- ? { $set: { draftDueAt: new Date(Date.now() + RETRY_DELAY_MS) }, $inc: { draftAttempts: 1 } }
46
- : { $set: { draftDueAt: null } },
47
- );
48
- return false;
49
- }
50
-
51
- async function sweepReviewDrafts({ now = new Date() } = {}) {
52
- const EscalationReview = getEscalationReview();
53
- const due = await EscalationReview
54
- .find({ closedAt: null, draftDueAt: { $lte: now } }, { _id: 1, draftDueAt: 1, draftAttempts: 1 })
55
- .sort({ draftDueAt: 1 })
56
- .limit(SWEEP_LIMIT)
57
- .lean();
58
-
59
- let written = 0;
60
- for (const entry of due) {
61
- try {
62
- if (await draftReview(EscalationReview, entry, now)) written += 1;
63
- } catch (error) {
64
- logger.error('[ReviewDraftSweep] Could not draft a review', { escalationReviewId: String(entry._id), error: error.message });
65
- }
66
- }
67
- return written;
68
- }
69
-
70
- const sweeper = createIntervalSweeper({
71
- label: '[ReviewDraftSweep]',
72
- sweep: () => sweepReviewDrafts(),
73
- defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
74
- });
75
-
76
- const startReviewDraftSweep = (options) => sweeper.start(options);
77
- const stopReviewDraftSweep = () => sweeper.stop();
78
-
79
- module.exports = { startReviewDraftSweep, stopReviewDraftSweep, sweepReviewDrafts };