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

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.
@@ -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,8 +55,6 @@ 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 },
@@ -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,
@@ -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: {
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.0",
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 };