@peopl-health/nexus 5.63.0 → 5.64.0-dev.11516

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', 'true')).trim().toLowerCase() !== 'false';
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,69 @@ 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
+ // Outbox first: settling writes the event before clearing the outbox, so an event moving mid-read lands in the second query.
218
+ const lights = await Model.aggregate([
219
+ { $match: { ...(service ? { service } : {}), outbox: { $elemMatch: { at: { $gte: from }, ...filters } } } },
220
+ { $unwind: '$outbox' },
221
+ { $match: { 'outbox.at': { $gte: from }, ...Object.fromEntries(Object.entries(filters).map(([field, value]) => [`outbox.${field}`, value])) } },
222
+ { $sort: { 'outbox.at': 1, patientId: 1, service: 1, 'outbox.revision': 1 } },
223
+ { $limit: bounded },
224
+ { $project: { _id: 0, patientId: 1, service: 1, outbox: ['$outbox'] } },
225
+ ]);
226
+ const stored = await EventModel.find({ at: { $gte: from }, ...(service ? { service } : {}), ...filters })
227
+ .sort({ at: 1, patientId: 1, service: 1, revision: 1 }).limit(bounded).lean();
228
+ return withOutboxEvents(stored, lights).sort(byTimeThenIdentity).slice(0, bounded);
229
+ }
230
+
231
+ function chatReading(recommendation, decision) {
232
+ const color = decision[RISK_FIELD[decision.service]];
233
+ if (!color) return null;
234
+ const summaries = decision.evidence.map((item) => item.summary).filter(Boolean);
235
+ const reason = (summaries.length ? summaries : decision.reasonCodes).join('; ').slice(0, MAX_CHAT_REASON_CHARS) || null;
236
+ return {
237
+ patientId: recommendation.patientId,
238
+ service: decision.service,
239
+ color,
240
+ source: 'ai',
241
+ reason,
242
+ evidence: decision.evidence.map((item) => ({ source: 'chat', sourceId: item.sourceId, summary: item.summary ?? item.code ?? null })),
243
+ };
244
+ }
245
+
246
+ async function applyChatSupportReadings(recommendation, {
247
+ acceptedServices = null, isTurnLive = () => true, now = new Date(), isLive = supportLightFromChatLive, apply = applySupportLight,
248
+ } = {}) {
249
+ if (!isLive()) return [];
250
+ const results = [];
251
+ const decisions = (recommendation.decisions || []).filter((decision) => !acceptedServices || acceptedServices.includes(decision.service));
252
+ for (const decision of decisions) {
253
+ const reading = chatReading(recommendation, decision);
254
+ if (!reading) continue;
255
+ if (!isTurnLive()) break;
256
+ try {
257
+ const { light, outcome } = await apply({ ...reading, now });
258
+ results.push({ service: reading.service, color: reading.color, outcome, revision: light?.revision ?? null });
259
+ } catch (error) {
260
+ logger.error('[supportLight] chat reading not applied', {
261
+ code: recommendation.patientId, service: reading.service, error: error.message, stack: error.stack,
262
+ });
263
+ results.push({ service: reading.service, color: reading.color, outcome: 'error', revision: null });
264
+ }
265
+ }
266
+ return results;
267
+ }
268
+
193
269
  module.exports = {
270
+ applyChatSupportReadings,
194
271
  applySupportLight,
272
+ readSupportLightEvents,
195
273
  readSupportLightBoard,
196
274
  resolvePendingImprovement,
197
275
  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
  });
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: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.63.0",
3
+ "version": "5.64.0-dev.11516",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",