@peopl-health/nexus 5.62.2 → 5.63.0-dev.11427

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.
@@ -0,0 +1,7 @@
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 };
@@ -46,6 +46,7 @@ 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 });
49
50
 
50
51
  const supportLightEventSchema = new mongoose.Schema({
51
52
  patientId: { type: String, required: true },
@@ -55,6 +56,8 @@ const supportLightEventSchema = new mongoose.Schema({
55
56
 
56
57
  supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
57
58
  supportLightEventSchema.index({ patientId: 1, at: -1 });
59
+ supportLightEventSchema.index({ service: 1, to: 1, at: 1 });
60
+ supportLightEventSchema.index({ at: 1 });
58
61
 
59
62
  const supportLightSweepSchema = new mongoose.Schema({
60
63
  patientId: { type: String, required: true, unique: true },
@@ -1,10 +1,14 @@
1
1
  const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
2
2
  const { logger } = require('../../utils/logger');
3
+ const { supportLightFromChatLive } = require('../flags/supportLightFlags');
3
4
  const { nextLight } = require('./supportInvitability');
4
5
 
5
6
  const AI_ACTOR = 'ai';
6
7
  const BOARD_LIMIT = 2000;
7
8
  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' };
8
12
 
9
13
  function requireText(value, name) {
10
14
  if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
@@ -136,6 +140,26 @@ async function readSupportLights(patientId, { Model = getSupportLightModel() } =
136
140
  return Model.find({ patientId }).select('-outbox').lean();
137
141
  }
138
142
 
143
+ function eventKey(event) {
144
+ return `${event.patientId}:${event.service}:${event.revision}`;
145
+ }
146
+
147
+ function withOutboxEvents(stored, lights) {
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 (!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
+
139
163
  async function readSupportLightHistory(patientId, {
140
164
  service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
141
165
  } = {}) {
@@ -146,14 +170,7 @@ async function readSupportLightHistory(patientId, {
146
170
  EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
147
171
  Model.find(scope).select('patientId service outbox').lean(),
148
172
  ]);
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()]
173
+ return withOutboxEvents(stored, lights)
157
174
  .sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
158
175
  || left.service.localeCompare(right.service))
159
176
  .slice(0, bounded);
@@ -190,8 +207,70 @@ async function readSupportLightBoard({ service = null, color = null, isPendingOn
190
207
  ]).option({ maxTimeMS: 10000, allowDiskUse: true });
191
208
  }
192
209
 
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.aggregate([
221
+ { $match: { ...(service ? { service } : {}), outbox: { $elemMatch: { at: { $gte: from }, ...filters } } } },
222
+ { $unwind: '$outbox' },
223
+ { $match: { 'outbox.at': { $gte: from }, ...Object.fromEntries(Object.entries(filters).map(([field, value]) => [`outbox.${field}`, value])) } },
224
+ { $sort: { 'outbox.at': 1, patientId: 1, service: 1, 'outbox.revision': 1 } },
225
+ { $limit: bounded },
226
+ { $project: { _id: 0, patientId: 1, service: 1, outbox: ['$outbox'] } },
227
+ ]),
228
+ ]);
229
+ return withOutboxEvents(stored, lights).sort(byTimeThenIdentity).slice(0, bounded);
230
+ }
231
+
232
+ function chatReading(recommendation, decision) {
233
+ const color = decision[RISK_FIELD[decision.service]];
234
+ if (!color) return null;
235
+ const summaries = decision.evidence.map((item) => item.summary).filter(Boolean);
236
+ const reason = (summaries.length ? summaries : decision.reasonCodes).join('; ').slice(0, MAX_CHAT_REASON_CHARS) || null;
237
+ return {
238
+ patientId: recommendation.patientId,
239
+ service: decision.service,
240
+ color,
241
+ source: 'ai',
242
+ reason,
243
+ evidence: decision.evidence.map((item) => ({ source: 'chat', sourceId: item.sourceId, summary: item.summary ?? item.code ?? null })),
244
+ };
245
+ }
246
+
247
+ async function applyChatSupportReadings(recommendation, {
248
+ acceptedServices = null, isTurnLive = () => true, now = new Date(), isLive = supportLightFromChatLive, apply = applySupportLight,
249
+ } = {}) {
250
+ if (!isLive()) return [];
251
+ const results = [];
252
+ const decisions = (recommendation.decisions || []).filter((decision) => !acceptedServices || acceptedServices.includes(decision.service));
253
+ for (const decision of decisions) {
254
+ const reading = chatReading(recommendation, decision);
255
+ if (!reading) continue;
256
+ if (!isTurnLive()) break;
257
+ try {
258
+ const { light, outcome } = await apply({ ...reading, now });
259
+ results.push({ service: reading.service, color: reading.color, outcome, revision: light?.revision ?? null });
260
+ } catch (error) {
261
+ logger.error('[supportLight] chat reading not applied', {
262
+ code: recommendation.patientId, service: reading.service, error: error.message, stack: error.stack,
263
+ });
264
+ results.push({ service: reading.service, color: reading.color, outcome: 'error', revision: null });
265
+ }
266
+ }
267
+ return results;
268
+ }
269
+
193
270
  module.exports = {
271
+ applyChatSupportReadings,
194
272
  applySupportLight,
273
+ readSupportLightEvents,
195
274
  readSupportLightBoard,
196
275
  resolvePendingImprovement,
197
276
  readSupportLights,
@@ -1,6 +1,7 @@
1
1
  const { ZodError } = require('zod');
2
2
 
3
3
  const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
4
+ const { applyChatSupportReadings } = require('../services/supportLightService');
4
5
  const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
5
6
 
6
7
  const decisionProperties = {
@@ -43,7 +44,7 @@ const decisionProperties = {
43
44
 
44
45
  const definition = {
45
46
  name: 'submitSupportRoutingRecommendation',
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.',
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.',
47
48
  strict: false,
48
49
  parameters: {
49
50
  type: 'object',
@@ -116,6 +117,11 @@ async function handler(args = {}, context = {}) {
116
117
  });
117
118
  if (!isRuntimeLive(runtime)) return inactiveTurn();
118
119
  const candidates = await recordSupportRoutingRecommendation(recommendation);
120
+ const lights = isRuntimeLive(runtime)
121
+ ? await applyChatSupportReadings(recommendation, {
122
+ acceptedServices: candidates.map((candidate) => candidate.service), isTurnLive: () => isRuntimeLive(runtime),
123
+ })
124
+ : [];
119
125
  runtime.trace?.setSignals?.({
120
126
  supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
121
127
  });
@@ -128,6 +134,7 @@ async function handler(args = {}, context = {}) {
128
134
  service: candidate.service,
129
135
  disposition: candidate.disposition,
130
136
  })),
137
+ lights,
131
138
  invitation_sent: false,
132
139
  },
133
140
  });
@@ -12,7 +12,6 @@ const {
12
12
  listEscalationReviews,
13
13
  openEscalationReview,
14
14
  recordDoctorDecision,
15
- requestBotDraft,
16
15
  sendApprovedIndications,
17
16
  setReviewCases,
18
17
  suggestDraft,
@@ -125,16 +124,6 @@ const suggestEscalationReviewDraftController = async (req, res) => {
125
124
  }
126
125
  };
127
126
 
128
- const requestEscalationReviewDraftController = async (req, res) => {
129
- try {
130
- const { triggeredBy } = req.body || {};
131
- const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
132
- res.status(202).json({ success: true, review });
133
- } catch (error) {
134
- respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
135
- }
136
- };
137
-
138
127
  const suggestEscalationReviewQuestionsController = async (req, res) => {
139
128
  try {
140
129
  const { triggeredBy } = req.body || {};
@@ -260,7 +249,6 @@ module.exports = {
260
249
  closeEscalationReviewController,
261
250
  getEscalationReviewController,
262
251
  getReviewTimelineController,
263
- requestEscalationReviewDraftController,
264
252
  handOffEscalationReviewController,
265
253
  listEscalationReviewsController,
266
254
  listReviewBoardController,
package/lib/index.d.ts CHANGED
@@ -1006,6 +1006,18 @@ 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?: { acceptedServices?: SupportService[] | null; isTurnLive?: () => boolean; now?: Date; isLive?: () => boolean; apply?: unknown }): Promise<Array<{
1016
+ service: SupportService;
1017
+ color: SupportLightColor;
1018
+ outcome: SupportLightOutcome | 'stale' | 'error';
1019
+ revision: number | null;
1020
+ }>>;
1009
1021
  };
1010
1022
 
1011
1023
  export const supportInvitability: {
@@ -127,7 +127,6 @@ const escalationReviewRouteDefinitions = {
127
127
  'POST /:id/cases': 'setEscalationReviewCasesController',
128
128
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
129
129
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
130
- 'POST /:id/draft-requests': 'requestEscalationReviewDraftController',
131
130
  'POST /:id/key-questions': 'suggestEscalationReviewQuestionsController',
132
131
  'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
133
132
  'POST /:id/drafts': 'addEscalationReviewDraftController',
@@ -300,7 +299,6 @@ const builtInControllers = {
300
299
  listReviewBoardController: escalationReviewController.listReviewBoardController,
301
300
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
302
301
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
303
- requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
304
302
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
305
303
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
306
304
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
@@ -580,13 +580,7 @@ async function openEscalationReview({
580
580
  if (!patient) throw httpError(404, 'Patient not found');
581
581
 
582
582
  const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
583
- const fields = {
584
- patientCode,
585
- openedBy: operator,
586
- patientCaseRecordIds: recordIds,
587
- assistantPausedByReview: false,
588
- draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS),
589
- };
583
+ const fields = { patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: false };
590
584
 
591
585
  const EscalationReview = getEscalationReview();
592
586
  let review;
@@ -622,35 +616,6 @@ async function openEscalationReview({
622
616
  return { review, created: true };
623
617
  }
624
618
 
625
- async function requestBotDraft({ id, requestedBy, requestId = null } = {}) {
626
- const reviewId = reviewIdOf(id);
627
- const operator = requiredText(requestedBy, 'requestedBy');
628
- const review = await loadReview(reviewId);
629
- if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
630
- if ((review.drafts ?? []).at(-1)?.writtenBy && review.drafts.at(-1).writtenBy !== DRAFT_OPERATOR) {
631
- throw httpError(409, 'The latest draft was written by the team; edit it instead of asking for a new one');
632
- }
633
- const now = new Date();
634
- if (review.draftDueAt && new Date(review.draftDueAt) > now) return review;
635
- const scheduled = await getEscalationReview().findOneAndUpdate(
636
- {
637
- _id: reviewId,
638
- status: { $in: DOCUMENTING_STATUSES },
639
- drafts: { $size: (review.drafts ?? []).length },
640
- $or: [{ draftDueAt: null }, { draftDueAt: { $lte: now } }],
641
- },
642
- { $set: { draftDueAt: now, draftAttempts: 0 } },
643
- { new: true },
644
- ).lean();
645
- if (!scheduled) {
646
- const latest = await loadReview(reviewId);
647
- if (latest.draftDueAt && new Date(latest.draftDueAt) > now) return latest;
648
- throw httpError(409, STATUS_CONFLICT);
649
- }
650
- await audit(scheduled, operator, requestId, { action: 'draft_requested' });
651
- return scheduled;
652
- }
653
-
654
619
  async function isEscalationApprover(operator) {
655
620
  try {
656
621
  return Boolean(await getEscalationApprover(operator));
@@ -744,29 +709,34 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
744
709
  if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
745
710
 
746
711
  const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
747
- const casesChanged = {
748
- $not: [{
749
- $setEquals: [
750
- {
751
- $ifNull: [
752
- '$patientCaseRecordIds',
753
- { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
754
- ],
755
- },
756
- recordIds,
757
- ],
758
- }],
759
- };
760
- const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
761
712
 
762
713
  const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
763
714
  $set: {
764
715
  patientCaseRecordIds: recordIds,
765
- status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
766
- ...(isBotDraft && {
767
- draftDueAt: { $cond: [casesChanged, new Date(Date.now() + DRAFT_DEBOUNCE_MS), '$draftDueAt'] },
768
- draftAttempts: { $cond: [casesChanged, 0, '$draftAttempts'] },
769
- }),
716
+ status: {
717
+ $cond: [
718
+ {
719
+ $and: [
720
+ { $eq: ['$status', 'draft_ready'] },
721
+ {
722
+ $not: [{
723
+ $setEquals: [
724
+ {
725
+ $ifNull: [
726
+ '$patientCaseRecordIds',
727
+ { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
728
+ ],
729
+ },
730
+ recordIds,
731
+ ],
732
+ }],
733
+ },
734
+ ],
735
+ },
736
+ 'documenting',
737
+ '$status',
738
+ ],
739
+ },
770
740
  pendingCaseMirrors: {
771
741
  $filter: {
772
742
  input: { $ifNull: ['$pendingCaseMirrors', []] },
@@ -1793,7 +1763,6 @@ module.exports = {
1793
1763
  recordDoctorDecision,
1794
1764
  sendScheduledDoctorAlert,
1795
1765
  recordReviewUpdate,
1796
- requestBotDraft,
1797
1766
  sendApprovedIndications,
1798
1767
  setReviewCases,
1799
1768
  suggestDraft,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.62.2",
3
+ "version": "5.63.0-dev.11427",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",