@peopl-health/nexus 5.59.10 → 5.60.0-dev.11094

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,72 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const { clinicalConnection } = require('../config/connection');
4
+
5
+ const lightEvidenceSchema = new mongoose.Schema({
6
+ source: { type: String, required: true, enum: ['triage', 'chat', 'specialist', 'sweep'] },
7
+ sourceId: { type: String, required: true },
8
+ summary: { type: String, default: null, maxlength: 1000 },
9
+ }, { _id: false });
10
+
11
+ const lightEventSchema = new mongoose.Schema({
12
+ outcome: { type: String, required: true, enum: ['applied', 'pending', 'withdrawn', 'accepted', 'rejected'] },
13
+ from: { type: String, default: null },
14
+ to: { type: String, required: true },
15
+ source: { type: String, required: true, enum: ['ai', 'human'] },
16
+ actor: { type: String, required: true },
17
+ evidence: { type: [lightEvidenceSchema], default: [] },
18
+ reason: { type: String, default: null, maxlength: 1000 },
19
+ revision: { type: Number, required: true },
20
+ at: { type: Date, required: true },
21
+ }, { _id: false });
22
+
23
+ const supportLightSchema = new mongoose.Schema({
24
+ patientId: { type: String, required: true },
25
+ service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
26
+ color: { type: String, required: true },
27
+ source: { type: String, required: true, enum: ['ai', 'human'] },
28
+ setBy: { type: String, required: true },
29
+ setAt: { type: Date, required: true },
30
+ evidence: { type: [lightEvidenceSchema], default: [] },
31
+ reason: { type: String, default: null, maxlength: 1000 },
32
+ pendingImprovement: {
33
+ type: new mongoose.Schema({
34
+ color: { type: String, required: true },
35
+ proposedBy: { type: String, required: true },
36
+ proposedAt: { type: Date, required: true },
37
+ evidence: { type: [lightEvidenceSchema], default: [] },
38
+ reason: { type: String, default: null, maxlength: 1000 },
39
+ }, { _id: false }),
40
+ default: null,
41
+ },
42
+ outbox: { type: [lightEventSchema], default: [] },
43
+ revision: { type: Number, default: 0 },
44
+ }, { timestamps: true });
45
+
46
+ supportLightSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_light_per_service' });
47
+ supportLightSchema.index({ service: 1, color: 1 });
48
+ supportLightSchema.index({ 'pendingImprovement.proposedAt': 1 }, { sparse: true });
49
+
50
+ const supportLightEventSchema = new mongoose.Schema({
51
+ patientId: { type: String, required: true },
52
+ service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
53
+ ...lightEventSchema.obj,
54
+ });
55
+
56
+ supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
57
+ supportLightEventSchema.index({ patientId: 1, at: -1 });
58
+
59
+ function getSupportLightModel() {
60
+ const conn = clinicalConnection();
61
+ return conn.models.SupportLight || conn.model('SupportLight', supportLightSchema, 'supportLights');
62
+ }
63
+
64
+ function getSupportLightEventModel() {
65
+ const conn = clinicalConnection();
66
+ return conn.models.SupportLightEvent
67
+ || conn.model('SupportLightEvent', supportLightEventSchema, 'supportLightEvents');
68
+ }
69
+
70
+ module.exports = {
71
+ getSupportLightModel, getSupportLightEventModel, supportLightSchema, supportLightEventSchema,
72
+ };
@@ -1,3 +1,5 @@
1
+ const { mexicoIsoWeek } = require('../../utils/dateUtils');
2
+
1
3
  /* Who may be invited to a collective support session.
2
4
  *
3
5
  * Lives apart from supportCandidateService and supportActionService because those two are
@@ -17,4 +19,66 @@ function isSafeGroupCandidate(candidate) {
17
19
  .every(([field, value]) => candidate[field] === value));
18
20
  }
19
21
 
20
- module.exports = { GROUP_INVITABLE, isSafeGroupCandidate };
22
+ const LIGHT_SCALE = Object.freeze({
23
+ nutrition: Object.freeze(['green', 'yellow', 'red']),
24
+ psychology: Object.freeze(['green', 'orange', 'red']),
25
+ });
26
+ const LIGHT_SOURCES = Object.freeze(['ai', 'human']);
27
+
28
+ function lightRank(service, color) {
29
+ return LIGHT_SCALE[service]?.indexOf(color) ?? -1;
30
+ }
31
+
32
+ function assertLight(service, color) {
33
+ if (!LIGHT_SCALE[service]) throw new Error(`invalid support service: ${service}`);
34
+ if (color !== 'unknown' && lightRank(service, color) === -1) throw new Error(`invalid ${service} light: ${color}`);
35
+ }
36
+
37
+ function nextLight(current, { service, color, source }) {
38
+ assertLight(service, color);
39
+ if (!LIGHT_SOURCES.includes(source)) throw new Error(`invalid light source: ${source}`);
40
+ const currentColor = current?.color ?? 'unknown';
41
+ const pendingColor = current?.pendingImprovement?.color ?? null;
42
+ if (source === 'human') return { outcome: 'applied', color, source, pendingImprovement: null };
43
+ if (color === 'unknown') return { outcome: 'unchanged' };
44
+ if (color === currentColor) return pendingColor ? { outcome: 'withdrawn', pendingImprovement: null } : { outcome: 'unchanged' };
45
+ if (currentColor === 'unknown' || lightRank(service, color) > lightRank(service, currentColor)) {
46
+ return { outcome: 'applied', color, source, pendingImprovement: null };
47
+ }
48
+ if (color === pendingColor) return { outcome: 'unchanged' };
49
+ return { outcome: 'pending', pendingImprovement: { color } };
50
+ }
51
+
52
+ const WEEKLY_COLLECTIVE_LIMIT = Object.freeze({ psychology: 1 });
53
+
54
+ function collectiveOffer({
55
+ service, color = 'unknown', invitationPaused = false, invitedThisWeek = false,
56
+ collectivesThisWeek = 0, hasCapacity = false,
57
+ }) {
58
+ assertLight(service, color);
59
+ const refuse = (reason) => ({ allowed: false, reason });
60
+ if (color === 'red') return refuse('light_red');
61
+ if (service === 'psychology' && color === 'orange') return refuse('light_orange');
62
+ if (service === 'psychology' && color === 'unknown') return refuse('light_unconfirmed');
63
+ if (invitationPaused) return refuse('invitation_paused');
64
+ if (invitedThisWeek) return refuse('already_invited_this_week');
65
+ const limit = WEEKLY_COLLECTIVE_LIMIT[service];
66
+ if (limit != null && collectivesThisWeek >= limit) return refuse('weekly_limit');
67
+ if (!hasCapacity) return refuse('no_capacity');
68
+ return { allowed: true, reason: null };
69
+ }
70
+
71
+ function supportWeek(date) {
72
+ return mexicoIsoWeek(date);
73
+ }
74
+
75
+ module.exports = {
76
+ GROUP_INVITABLE,
77
+ isSafeGroupCandidate,
78
+ LIGHT_SCALE,
79
+ LIGHT_SOURCES,
80
+ WEEKLY_COLLECTIVE_LIMIT,
81
+ nextLight,
82
+ collectiveOffer,
83
+ supportWeek,
84
+ };
@@ -0,0 +1,204 @@
1
+ const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
2
+ const { logger } = require('../../utils/logger');
3
+ const { nextLight } = require('./supportInvitability');
4
+
5
+ const AI_ACTOR = 'ai';
6
+ const BOARD_LIMIT = 2000;
7
+ const HISTORY_READ_LIMIT = 200;
8
+
9
+ function requireText(value, name) {
10
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
11
+ }
12
+
13
+ function requireReviewedRevision(value) {
14
+ if (value !== null && !(Number.isInteger(value) && value >= 0)) {
15
+ throw new Error('reviewedRevision is required: the revision the specialist saw, or null for no light yet');
16
+ }
17
+ }
18
+
19
+ function actorFor(source, actor) {
20
+ if (source === 'ai') return actor || AI_ACTOR;
21
+ requireText(actor, 'actor');
22
+ return actor;
23
+ }
24
+
25
+ function lightPatch(change, { actor, evidence, reason, now }) {
26
+ if (change.outcome === 'pending') {
27
+ return { pendingImprovement: { ...change.pendingImprovement, proposedBy: actor, proposedAt: now, evidence, reason } };
28
+ }
29
+ if (change.outcome === 'withdrawn') return { pendingImprovement: null };
30
+ return {
31
+ color: change.color, source: change.source, setBy: actor, setAt: now,
32
+ evidence, reason, pendingImprovement: null,
33
+ };
34
+ }
35
+
36
+ async function flushOutbox(EventModel, light) {
37
+ for (const event of light?.outbox || []) {
38
+ const key = { patientId: light.patientId, service: light.service, revision: event.revision };
39
+ try {
40
+ await EventModel.updateOne(key, { $setOnInsert: { ...event, ...key } }, { upsert: true });
41
+ } catch (error) {
42
+ if (error?.code !== 11000) throw error;
43
+ }
44
+ }
45
+ }
46
+
47
+ async function settleOutbox(Model, EventModel, light) {
48
+ try {
49
+ await flushOutbox(EventModel, light);
50
+ await Model.updateOne(
51
+ { patientId: light.patientId, service: light.service, revision: light.revision },
52
+ { $set: { outbox: [] } },
53
+ );
54
+ } catch (error) {
55
+ logger.warn('[supportLight] history entry left in the outbox', {
56
+ code: light.patientId, service: light.service, revision: light.revision, error: error.message, stack: error.stack,
57
+ });
58
+ }
59
+ }
60
+
61
+ async function writeLight(Model, query, existing, patch, event) {
62
+ const owner = existing ? { ...query, revision: existing.revision } : { ...query, setAt: { $exists: false } };
63
+ const revision = (existing?.revision ?? 0) + 1;
64
+ try {
65
+ return await Model.findOneAndUpdate(owner, {
66
+ $set: { ...patch, outbox: [{ ...event, revision }] },
67
+ ...(!existing ? { $setOnInsert: query } : {}),
68
+ $inc: { revision: 1 },
69
+ }, { new: true, upsert: !existing, setDefaultsOnInsert: true, lean: true });
70
+ } catch (error) {
71
+ if (error?.code === 11000) return null;
72
+ throw error;
73
+ }
74
+ }
75
+
76
+ function eventFor(change, existing, { color, source, actor, evidence, reason, at }) {
77
+ const pendingColor = existing?.pendingImprovement?.color ?? null;
78
+ if (change.outcome === 'withdrawn') {
79
+ return { outcome: 'withdrawn', from: existing.color, to: pendingColor, source, actor, evidence, reason, at };
80
+ }
81
+ return { outcome: change.outcome, from: existing?.color ?? null, to: color, source, actor, evidence, reason, at };
82
+ }
83
+
84
+ async function applySupportLight({
85
+ patientId, service, color, source, actor = null, evidence = [], reason = null, now = new Date(), reviewedRevision,
86
+ }, { Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
87
+ requireText(patientId, 'patientId');
88
+ const who = actorFor(source, actor);
89
+ const isHuman = source === 'human';
90
+ if (isHuman) requireReviewedRevision(reviewedRevision);
91
+ const at = new Date(now);
92
+ const query = { patientId, service };
93
+ for (let attempt = 0; attempt < 5; attempt += 1) {
94
+ const existing = await Model.findOne(query).lean();
95
+ if (isHuman && (existing?.revision ?? null) !== reviewedRevision) return { light: existing, outcome: 'stale' };
96
+ const change = nextLight(existing, { service, color, source });
97
+ if (change.outcome === 'unchanged') return { light: existing, outcome: 'unchanged' };
98
+ await flushOutbox(EventModel, existing);
99
+ const event = eventFor(change, existing, { color, source, actor: who, evidence, reason, at });
100
+ const light = await writeLight(Model, query, existing, lightPatch(change, { actor: who, evidence, reason, now: at }), event);
101
+ if (light) {
102
+ await settleOutbox(Model, EventModel, light);
103
+ return { light, outcome: change.outcome };
104
+ }
105
+ if (isHuman) return { light: await Model.findOne(query).lean(), outcome: 'stale' };
106
+ }
107
+ throw new Error('support light changed repeatedly during update');
108
+ }
109
+
110
+ async function resolvePendingImprovement({
111
+ patientId, service, accept, actor, reviewedRevision, now = new Date(),
112
+ }, { Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
113
+ requireText(patientId, 'patientId');
114
+ requireText(actor, 'actor');
115
+ if (typeof accept !== 'boolean') throw new Error('accept must be a boolean');
116
+ if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
117
+ const at = new Date(now);
118
+ const query = { patientId, service, revision: reviewedRevision, pendingImprovement: { $ne: null } };
119
+ const existing = await Model.findOne(query).lean();
120
+ if (!existing?.pendingImprovement) return null;
121
+ await flushOutbox(EventModel, existing);
122
+ const pending = existing.pendingImprovement;
123
+ const patch = accept
124
+ ? { color: pending.color, source: 'human', setBy: actor, setAt: at, evidence: pending.evidence || [], reason: pending.reason ?? null, pendingImprovement: null }
125
+ : { pendingImprovement: null };
126
+ const event = {
127
+ outcome: accept ? 'accepted' : 'rejected', from: existing.color, to: pending.color, source: 'human', actor,
128
+ evidence: pending.evidence || [], reason: pending.reason ?? null, at, revision: reviewedRevision + 1,
129
+ };
130
+ const light = await Model.findOneAndUpdate(query, { $set: { ...patch, outbox: [event] }, $inc: { revision: 1 } }, { new: true, lean: true });
131
+ if (light) await settleOutbox(Model, EventModel, light);
132
+ return light;
133
+ }
134
+
135
+ async function readSupportLights(patientId, { Model = getSupportLightModel() } = {}) {
136
+ requireText(patientId, 'patientId');
137
+ return Model.find({ patientId }).select('-outbox').lean();
138
+ }
139
+
140
+ async function readSupportLightHistory(patientId, {
141
+ service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
142
+ } = {}) {
143
+ requireText(patientId, 'patientId');
144
+ const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, HISTORY_READ_LIMIT) : HISTORY_READ_LIMIT;
145
+ const scope = { patientId, ...(service ? { service } : {}) };
146
+ const [stored, lights] = await Promise.all([
147
+ EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
148
+ Model.find(scope).select('patientId service outbox').lean(),
149
+ ]);
150
+ const byKey = new Map(stored.map((event) => [`${event.service}:${event.revision}`, event]));
151
+ for (const light of lights) {
152
+ for (const event of light.outbox || []) {
153
+ const key = `${light.service}:${event.revision}`;
154
+ if (!byKey.has(key)) byKey.set(key, { ...event, patientId: light.patientId, service: light.service });
155
+ }
156
+ }
157
+ return [...byKey.values()]
158
+ .sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
159
+ || left.service.localeCompare(right.service))
160
+ .slice(0, bounded);
161
+ }
162
+
163
+ function boardFilter({ service = null, color = null, pendingOnly = false } = {}) {
164
+ return {
165
+ ...(service ? { service } : {}),
166
+ ...(color ? { color } : {}),
167
+ ...(pendingOnly ? { pendingImprovement: { $ne: null } } : {}),
168
+ };
169
+ }
170
+
171
+ const BOARD_RANK = {
172
+ $switch: {
173
+ branches: [
174
+ { case: { $eq: ['$color', 'red'] }, then: 0 },
175
+ { case: { $ne: [{ $ifNull: ['$pendingImprovement', null] }, null] }, then: 1 },
176
+ { case: { $in: ['$color', ['orange', 'unknown']] }, then: 2 },
177
+ ],
178
+ default: 3,
179
+ },
180
+ };
181
+
182
+ async function readSupportLightBoard(filters = {}, { limit = BOARD_LIMIT, offset = 0, Model = getSupportLightModel() } = {}) {
183
+ const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, BOARD_LIMIT) : BOARD_LIMIT;
184
+ const skipped = Number.isInteger(offset) && offset > 0 ? offset : 0;
185
+ return Model.aggregate([
186
+ { $match: boardFilter(filters) },
187
+ { $project: { _id: 0, outbox: 0, evidence: 0, 'pendingImprovement.evidence': 0 } },
188
+ { $set: { boardRank: BOARD_RANK } },
189
+ { $sort: { boardRank: 1, setAt: -1, patientId: 1, service: 1 } },
190
+ { $skip: skipped },
191
+ { $limit: bounded },
192
+ { $unset: 'boardRank' },
193
+ ]).option({ maxTimeMS: 10000, allowDiskUse: true });
194
+ }
195
+
196
+ module.exports = {
197
+ BOARD_LIMIT,
198
+ HISTORY_READ_LIMIT,
199
+ applySupportLight,
200
+ readSupportLightBoard,
201
+ resolvePendingImprovement,
202
+ readSupportLights,
203
+ readSupportLightHistory,
204
+ };
@@ -2,7 +2,6 @@ const { Config_ID } = require('../config/airtableConfig');
2
2
  const runtimeConfig = require('../config/runtimeConfig');
3
3
 
4
4
  const { logger } = require('../utils/logger');
5
- const { AssistantMessageError, injectAssistantMessages } = require('../services/assistantMessageService');
6
5
 
7
6
  const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
8
7
 
@@ -66,14 +65,15 @@ const addInsAssistantController = async (req, res) => {
66
65
  };
67
66
 
68
67
  const addMsgAssistantController = async (req, res) => {
68
+ const { code, messages, role = 'system', reply = false, triggeredBy } = req.body;
69
+ if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
70
+
69
71
  try {
70
- await injectAssistantMessages(req.body, processSystemMessage);
72
+ await processSystemMessage(code, messages, role, { reply, triggeredBy });
71
73
  return res.status(200).json({ success: true, message: 'Message added to assistant' });
72
74
  } catch (error) {
73
- const failure = error instanceof AssistantMessageError ? error : new AssistantMessageError('MESSAGE_INJECTION_FAILED');
74
- const { reasonCode, acceptedCount, statusCode } = failure;
75
- logger.error('[AssistantController] Add message error', { reasonCode, acceptedCount });
76
- return res.status(statusCode).json({ success: false, error: failure.message, reasonCode, acceptedCount });
75
+ logger.error('[AssistantController] Add message error', { error: error.message, code, role });
76
+ res.status(500).json({ success: false, error: 'Failed to add message to assistant' });
77
77
  }
78
78
  };
79
79
 
@@ -27,7 +27,6 @@ const { ensureThreadExists } = require('../services/threadService');
27
27
 
28
28
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
29
29
  const { getMessages, updateMessage } = require('../services/messageService');
30
- const { processAssistantSystemMessage } = require('../services/assistantMessageService');
31
30
  const { beginInstruction, endInstruction } = require('../services/instructionInFlightService');
32
31
  const { QueueReconciliationService } = require('../services/queueReconciliationService');
33
32
  const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMessageService');
@@ -1135,15 +1134,59 @@ class NexusMessaging {
1135
1134
  return result;
1136
1135
  }
1137
1136
 
1138
- async processSystemMessage(code, messages, role = 'system', options = {}) {
1139
- return processAssistantSystemMessage(code, messages, role, options, {
1140
- messageStorage: this.messageStorage,
1141
- saveMessage: this._saveMessageFn.bind(this),
1142
- phiProcessor: this.phiProcessor,
1143
- executeWithPipeline: this._executeWithPipeline.bind(this),
1144
- assistantProcessor: this.assistantProcessor,
1145
- getAbortSignal: this.batchingManager.getAbortSignal.bind(this.batchingManager),
1146
- });
1137
+ async processSystemMessage(code, messages, role = 'system', { triggeredBy, reply = true } = {}) {
1138
+ const thread = await Thread.findOne({ code }).lean();
1139
+ if (!thread) return;
1140
+
1141
+ // Dropped rather than stored: these now emit message:new and would render as an empty bubble.
1142
+ const requestedMessages = Array.isArray(messages) ? messages : [messages];
1143
+ const normalizedMessages = requestedMessages.filter(body => typeof body === 'string' && body.trim());
1144
+ if (normalizedMessages.length !== requestedMessages.length) {
1145
+ logger.warn('[processSystemMessage] Ignoring blank message entries', {
1146
+ code,
1147
+ ignored: requestedMessages.length - normalizedMessages.length,
1148
+ });
1149
+ }
1150
+ // Every entry was blank: nothing to store, and so nothing for the agent to reply to.
1151
+ if (!normalizedMessages.length) return null;
1152
+
1153
+ for (let i = 0; i < normalizedMessages.length; i++) {
1154
+ try {
1155
+ const messageData = {
1156
+ pushName: 'System',
1157
+ code,
1158
+ body: normalizedMessages[i],
1159
+ messageId: `system_${Date.now()}_${i}_${Math.random().toString(36).substring(7)}`,
1160
+ fromMe: true,
1161
+ processed: true,
1162
+ origin: 'system',
1163
+ raw: { role, replyRequested: reply },
1164
+ triggeredBy: triggeredBy || null,
1165
+ // No `silent`: it suppresses the message:new event an interface renders from. Instructions keep it.
1166
+ };
1167
+ await this.phiProcessor.inData(messageData, this._saveMessageFn, () => {});
1168
+ } catch (err) {
1169
+ logger.error('[processSystemMessage] Error saving system message', { error: err.message, code, index: i });
1170
+ }
1171
+ }
1172
+
1173
+ if (!reply) return;
1174
+
1175
+ await this._executeWithPipeline(code, 'system', 'queue',
1176
+ async (preProcessResult, shouldContinue, runId) => {
1177
+ return await this.assistantProcessor.process({
1178
+ code,
1179
+ runOptions: {
1180
+ prePromptResult: preProcessResult,
1181
+ toolChoice: 'none',
1182
+ turnKind: TURN_KIND.SYSTEM,
1183
+ runId,
1184
+ shouldContinue,
1185
+ signal: this.batchingManager.getAbortSignal(runId),
1186
+ }
1187
+ });
1188
+ }
1189
+ );
1147
1190
  }
1148
1191
 
1149
1192
  async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
package/lib/index.d.ts CHANGED
@@ -918,6 +918,107 @@ declare module '@peopl-health/nexus' {
918
918
  }, options?: { Model?: unknown }): Promise<SupportActionResult | null>;
919
919
  };
920
920
 
921
+ export type SupportLightColor = 'green' | 'yellow' | 'orange' | 'red' | 'unknown';
922
+ export type SupportLightSource = 'ai' | 'human';
923
+ export type SupportLightOutcome = 'applied' | 'pending' | 'withdrawn' | 'unchanged';
924
+ export type CollectiveRefusal = 'light_red' | 'light_orange' | 'light_unconfirmed' | 'invitation_paused'
925
+ | 'already_invited_this_week' | 'weekly_limit' | 'no_capacity';
926
+
927
+ export interface SupportLightEvidence {
928
+ source: 'triage' | 'chat' | 'specialist' | 'sweep';
929
+ sourceId: string;
930
+ summary?: string | null;
931
+ }
932
+
933
+ export interface SupportLightRecord {
934
+ patientId: string;
935
+ service: SupportService;
936
+ color: SupportLightColor;
937
+ source: SupportLightSource;
938
+ setBy: string;
939
+ setAt: Date;
940
+ evidence: SupportLightEvidence[];
941
+ reason: string | null;
942
+ pendingImprovement: {
943
+ color: SupportLightColor;
944
+ proposedBy: string;
945
+ proposedAt: Date;
946
+ evidence: SupportLightEvidence[];
947
+ reason: string | null;
948
+ } | null;
949
+ revision: number;
950
+ }
951
+
952
+ export type SupportLightBoardRecord = Omit<SupportLightRecord, 'evidence' | 'pendingImprovement'> & {
953
+ pendingImprovement: Omit<NonNullable<SupportLightRecord['pendingImprovement']>, 'evidence'> | null;
954
+ };
955
+
956
+ export interface SupportLightEventRecord {
957
+ patientId: string;
958
+ service: SupportService;
959
+ outcome: 'applied' | 'pending' | 'withdrawn' | 'accepted' | 'rejected';
960
+ from: SupportLightColor | null;
961
+ to: SupportLightColor;
962
+ source: SupportLightSource;
963
+ actor: string;
964
+ evidence: SupportLightEvidence[];
965
+ reason: string | null;
966
+ revision: number;
967
+ at: Date;
968
+ }
969
+
970
+ export const supportLightService: {
971
+ applySupportLight(request: {
972
+ patientId: string;
973
+ service: SupportService;
974
+ color: SupportLightColor;
975
+ source: SupportLightSource;
976
+ actor?: string | null;
977
+ evidence?: SupportLightEvidence[];
978
+ reason?: string | null;
979
+ now?: Date;
980
+ reviewedRevision?: number | null;
981
+ }, options?: { Model?: unknown; EventModel?: unknown }): Promise<{ light: SupportLightRecord | null; outcome: SupportLightOutcome | 'stale' }>;
982
+ resolvePendingImprovement(request: {
983
+ patientId: string;
984
+ service: SupportService;
985
+ accept: boolean;
986
+ actor: string;
987
+ reviewedRevision: number;
988
+ now?: Date;
989
+ }, options?: { Model?: unknown; EventModel?: unknown }): Promise<SupportLightRecord | null>;
990
+ readSupportLights(patientId: string, options?: { Model?: unknown }): Promise<SupportLightRecord[]>;
991
+ readSupportLightBoard(filters?: {
992
+ service?: SupportService | null;
993
+ color?: SupportLightColor | null;
994
+ pendingOnly?: boolean;
995
+ }, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
996
+ BOARD_LIMIT: number;
997
+ HISTORY_READ_LIMIT: number;
998
+ readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
999
+ };
1000
+
1001
+ export const supportInvitability: {
1002
+ LIGHT_SCALE: Readonly<Record<SupportService, readonly SupportLightColor[]>>;
1003
+ LIGHT_SOURCES: readonly SupportLightSource[];
1004
+ WEEKLY_COLLECTIVE_LIMIT: Readonly<Partial<Record<SupportService, number>>>;
1005
+ GROUP_INVITABLE: readonly Readonly<Record<string, unknown>>[];
1006
+ isSafeGroupCandidate(candidate: Partial<SupportCandidateRecord>): boolean;
1007
+ nextLight(
1008
+ current: { color?: SupportLightColor | null } | null | undefined,
1009
+ proposal: { service: SupportService; color: SupportLightColor; source: SupportLightSource },
1010
+ ): { outcome: SupportLightOutcome; color?: SupportLightColor; source?: SupportLightSource; pendingImprovement?: { color: SupportLightColor } | null };
1011
+ collectiveOffer(request: {
1012
+ service: SupportService;
1013
+ color?: SupportLightColor;
1014
+ invitationPaused?: boolean;
1015
+ invitedThisWeek?: boolean;
1016
+ collectivesThisWeek?: number;
1017
+ hasCapacity?: boolean;
1018
+ }): { allowed: boolean; reason: CollectiveRefusal | null };
1019
+ supportWeek(date: Date | string): string | null;
1020
+ };
1021
+
921
1022
  // BatchingManager — per-chatId concurrency control
922
1023
  export interface BatchingConfig {
923
1024
  enabled?: boolean;
package/lib/index.js CHANGED
@@ -48,6 +48,8 @@ const { MapCache } = require('./utils/MapCache');
48
48
  const supportCandidateService = require('./clinical/services/supportCandidateService');
49
49
  const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
50
50
  const supportActionService = require('./clinical/services/supportActionService');
51
+ const supportLightService = require('./clinical/services/supportLightService');
52
+ const supportInvitability = require('./clinical/services/supportInvitability');
51
53
  const {
52
54
  NutritionSafetyDecision,
53
55
  FINDING_CODES,
@@ -355,6 +357,8 @@ module.exports = {
355
357
  supportCandidateService,
356
358
  registerDashboardProvider,
357
359
  supportActionService,
360
+ supportLightService,
361
+ supportInvitability,
358
362
  NutritionSafetyDecision,
359
363
  FINDING_CODES,
360
364
  FINDING_VALUES,
@@ -39,16 +39,6 @@ function isTransientNetworkError(error) {
39
39
  return TRANSIENT_ERROR_CODES.includes(error?.code) || error?.name === 'AbortError';
40
40
  }
41
41
 
42
- // Provider messages, arbitrary codes, and query context can contain patient data.
43
- // Classify only for logging; retry decisions and thrown errors remain unchanged.
44
- function safeAirtableFailure(error) {
45
- const statusCode = Number.isInteger(error?.statusCode) && error.statusCode >= 100 && error.statusCode <= 599
46
- ? error.statusCode : null;
47
- const errorCode = TRANSIENT_ERROR_CODES.includes(error?.code)
48
- ? error.code : error?.name === 'AbortError' ? 'ABORT_ERR' : 'UNKNOWN';
49
- return { statusCode, errorCode };
50
- }
51
-
52
42
  async function withAirtableRetry(operation, label, { retryNetworkErrors = true } = {}) {
53
43
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
54
44
  try {
@@ -61,7 +51,7 @@ async function withAirtableRetry(operation, label, { retryNetworkErrors = true }
61
51
  throw error;
62
52
  }
63
53
  const baseDelay = error.statusCode === RATE_LIMITED_STATUS ? RATE_LIMIT_DELAY_MS : RETRY_BASE_DELAY_MS;
64
- logger.warn(`[${label}] Airtable unavailable, retrying`, { ...safeAirtableFailure(error), attempt, maxAttempts: MAX_ATTEMPTS, delayMs: baseDelay * attempt });
54
+ logger.warn(`[${label}] Airtable unavailable, retrying`, { statusCode: error.statusCode, errorCode: error.code, attempt, maxAttempts: MAX_ATTEMPTS, delayMs: baseDelay * attempt });
65
55
  await delay(baseDelay * attempt);
66
56
  }
67
57
  }
@@ -122,7 +112,7 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
122
112
  'getRecordByFilter'
123
113
  );
124
114
  } catch (error) {
125
- logger.error('[getRecordByFilter] Failed', safeAirtableFailure(error));
115
+ logger.error('[getRecordByFilter] Failed', { tableName, filter, fields, error: error.message });
126
116
  throw error;
127
117
  }
128
118
  }
@@ -47,6 +47,12 @@ const mexicoDay = (value) => {
47
47
  return at.isValid() ? at.format('YYYY-MM-DD') : null;
48
48
  };
49
49
 
50
+ const mexicoIsoWeek = (value) => {
51
+ if (value === null || value === undefined || value === '') return null;
52
+ const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
53
+ return at.isValid() ? at.format('GGGG-[W]WW') : null;
54
+ };
55
+
50
56
  const daysSince = (from, now = Date.now()) => {
51
57
  const at = Date.parse(from);
52
58
  return Number.isNaN(at) ? null : Math.max(0, Math.floor((now - at) / 86400000));
@@ -60,6 +66,7 @@ module.exports = {
60
66
  ageInYears,
61
67
  isoDay,
62
68
  mexicoDay,
69
+ mexicoIsoWeek,
63
70
  mexicoStamp,
64
71
  daysSince
65
72
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.10",
3
+ "version": "5.60.0-dev.11094",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,140 +0,0 @@
1
- const { Monitoreo_ID: monitoreoId } = require('../config/airtableConfig');
2
- const { logger } = require('../utils/logger');
3
- const { Thread } = require('../models/threadModel');
4
- const { requirePatientIdentity } = require('../clinical/services/patientIdentityService');
5
- const { TURN_KIND } = require('../clinical/context/turnContext');
6
-
7
- // Public failure details are fixed here; never forward provider messages or identifiers.
8
- const ASSISTANT_MESSAGE_FAILURES = {
9
- INVALID_BODY: [400, 'Body must be an object'],
10
- UNSUPPORTED_INSTRUCTION_ALIAS: [400, 'Use messages instead of instruction'],
11
- UNSUPPORTED_CODES_ALIAS: [400, 'Use one code instead of codes'],
12
- INVALID_CODE: [400, 'code must be a nonblank string'],
13
- INVALID_MESSAGES: [400, 'messages must be a nonblank string or a nonempty array of nonblank strings'],
14
- INVALID_ROLE: [400, 'role must be system or developer'],
15
- INVALID_REPLY: [400, 'reply must be a boolean'],
16
- INVALID_OPTIONS: [400, 'options must be an object'],
17
- PATIENT_IDENTITY_INVALID: [400, 'Invalid patient identity'],
18
- PATIENT_IDENTITY_MISSING: [404, 'Patient identity not found'],
19
- PATIENT_IDENTITY_AMBIGUOUS: [409, 'Patient identity is ambiguous'],
20
- PATIENT_IDENTITY_UNAVAILABLE: [502, 'Patient identity unavailable'],
21
- CONVERSATION_NOT_FOUND: [404, 'Conversation not found'],
22
- CONVERSATION_UNAVAILABLE: [502, 'Conversation unavailable'],
23
- MESSAGE_PERSISTENCE_FAILED: [502, 'Could not persist assistant messages'],
24
- MESSAGE_REPLY_FAILED: [502, 'Assistant reply failed after messages were persisted'],
25
- MESSAGE_INJECTION_FAILED: [502, 'Assistant message injection failed'],
26
- };
27
-
28
- class AssistantMessageError extends Error {
29
- constructor(reasonCode, acceptedCount = 0) {
30
- const [statusCode, message] = ASSISTANT_MESSAGE_FAILURES[reasonCode];
31
- super(message);
32
- this.reasonCode = reasonCode;
33
- this.statusCode = statusCode;
34
- this.acceptedCount = acceptedCount;
35
- }
36
- }
37
-
38
- function validateAssistantMessages(body, { shouldReplyByDefault = false } = {}) {
39
- if (!body || typeof body !== 'object' || Array.isArray(body)) throw new AssistantMessageError('INVALID_BODY');
40
- if (Object.hasOwn(body, 'instruction')) throw new AssistantMessageError('UNSUPPORTED_INSTRUCTION_ALIAS');
41
- if (Object.hasOwn(body, 'codes')) throw new AssistantMessageError('UNSUPPORTED_CODES_ALIAS');
42
- const { code, messages, role = 'system', reply = shouldReplyByDefault, triggeredBy } = body;
43
- if (typeof code !== 'string' || !code.trim()) throw new AssistantMessageError('INVALID_CODE');
44
- // Copy the batch so later caller mutation cannot invalidate entries during awaited saves.
45
- const batch = Array.isArray(messages) ? Array.from(messages) : [messages];
46
- if (!batch.length || batch.some(message => typeof message !== 'string' || !message.trim())) {
47
- throw new AssistantMessageError('INVALID_MESSAGES');
48
- }
49
- const normalizedRole = typeof role === 'string' ? role.trim().toLowerCase() : null;
50
- if (!['system', 'developer'].includes(normalizedRole)) throw new AssistantMessageError('INVALID_ROLE');
51
- if (typeof reply !== 'boolean') throw new AssistantMessageError('INVALID_REPLY');
52
- return { code, messages: batch, role: normalizedRole, reply, triggeredBy };
53
- }
54
-
55
- async function injectAssistantMessages(body, processSystemMessage) {
56
- const { code, messages, role, reply, triggeredBy } = validateAssistantMessages(body);
57
- try {
58
- await requirePatientIdentity(monitoreoId, code);
59
- } catch (error) {
60
- const reasonCode = ['PATIENT_IDENTITY_INVALID', 'PATIENT_IDENTITY_MISSING', 'PATIENT_IDENTITY_AMBIGUOUS'].includes(error?.code)
61
- ? error.code : 'PATIENT_IDENTITY_UNAVAILABLE';
62
- throw new AssistantMessageError(reasonCode);
63
- }
64
- return processSystemMessage(code, messages, role, { reply, triggeredBy });
65
- }
66
-
67
- async function processAssistantSystemMessage(code, messages, role = 'system', options = {}, dependencies) {
68
- if (!options || typeof options !== 'object' || Array.isArray(options)) throw new AssistantMessageError('INVALID_OPTIONS');
69
- const input = validateAssistantMessages({ ...options, code, messages, role }, { shouldReplyByDefault: true });
70
- const { triggeredBy, reply } = input;
71
- let thread;
72
- try {
73
- thread = await Thread.findOne({ code }).lean();
74
- } catch {
75
- throw new AssistantMessageError('CONVERSATION_UNAVAILABLE');
76
- }
77
- if (!thread) throw new AssistantMessageError('CONVERSATION_NOT_FOUND');
78
- const { messageStorage, saveMessage, phiProcessor, executeWithPipeline, assistantProcessor, getAbortSignal } = dependencies;
79
- if (typeof messageStorage?.saveMessage !== 'function') throw new AssistantMessageError('MESSAGE_PERSISTENCE_FAILED');
80
-
81
- let acceptedCount = 0;
82
- let stage;
83
- const saveConfirmedMessage = async messageData => {
84
- stage = 'storage';
85
- const saved = await saveMessage(messageData);
86
- stage = 'acknowledgment';
87
- if (!saved?._id || !String(saved._id).trim()) throw new AssistantMessageError('MESSAGE_PERSISTENCE_FAILED');
88
- acceptedCount++;
89
- return saved;
90
- };
91
- for (let i = 0; i < input.messages.length; i++) {
92
- // The real PHI path encodes before invoking the storage callback. These fixed
93
- // stages diagnose the failing boundary without retaining an unsafe cause.
94
- stage = 'encoding';
95
- try {
96
- const messageData = {
97
- pushName: 'System',
98
- code,
99
- body: input.messages[i],
100
- messageId: `system_${Date.now()}_${i}_${Math.random().toString(36).substring(7)}`,
101
- fromMe: true,
102
- processed: true,
103
- origin: 'system',
104
- raw: { role: input.role, replyRequested: reply },
105
- triggeredBy: triggeredBy || null,
106
- // No `silent`: it suppresses the message:new event an interface renders from. Instructions keep it.
107
- };
108
- await phiProcessor.inData(messageData, saveConfirmedMessage, () => {});
109
- stage = 'acknowledgment';
110
- if (acceptedCount !== i + 1) throw new AssistantMessageError('MESSAGE_PERSISTENCE_FAILED');
111
- } catch {
112
- logger.error('[processSystemMessage] Error saving system message', { reasonCode: 'MESSAGE_PERSISTENCE_FAILED', acceptedCount, stage });
113
- throw new AssistantMessageError('MESSAGE_PERSISTENCE_FAILED', acceptedCount);
114
- }
115
- }
116
-
117
- if (!reply) return;
118
-
119
- try {
120
- await executeWithPipeline(code, 'system', 'queue',
121
- async (preProcessResult, shouldContinue, runId) => {
122
- return await assistantProcessor.process({
123
- code,
124
- runOptions: {
125
- prePromptResult: preProcessResult,
126
- toolChoice: 'none',
127
- turnKind: TURN_KIND.SYSTEM,
128
- runId,
129
- shouldContinue,
130
- signal: getAbortSignal(runId),
131
- }
132
- });
133
- }
134
- );
135
- } catch {
136
- throw new AssistantMessageError('MESSAGE_REPLY_FAILED', acceptedCount);
137
- }
138
- }
139
-
140
- module.exports = { AssistantMessageError, injectAssistantMessages, processAssistantSystemMessage };