@peopl-health/nexus 5.60.0-dev.11095 → 5.60.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.
@@ -1,6 +1,6 @@
1
1
  const { mexicoIsoWeek } = require('../../utils/dateUtils');
2
2
 
3
- /* Who may be invited to a collective support session.
3
+ /* Who may be invited to a collective support session, and how a support light may change.
4
4
  *
5
5
  * Lives apart from supportCandidateService and supportActionService because those two are
6
6
  * mocked by each other's tests, and a safety rule that can be mocked away is not a rule.
@@ -23,7 +23,6 @@ const LIGHT_SCALE = Object.freeze({
23
23
  nutrition: Object.freeze(['green', 'yellow', 'red']),
24
24
  psychology: Object.freeze(['green', 'orange', 'red']),
25
25
  });
26
- const LIGHT_SOURCES = Object.freeze(['ai', 'human']);
27
26
 
28
27
  function lightRank(service, color) {
29
28
  return LIGHT_SCALE[service]?.indexOf(color) ?? -1;
@@ -36,7 +35,7 @@ function assertLight(service, color) {
36
35
 
37
36
  function nextLight(current, { service, color, source }) {
38
37
  assertLight(service, color);
39
- if (!LIGHT_SOURCES.includes(source)) throw new Error(`invalid light source: ${source}`);
38
+ if (!['ai', 'human'].includes(source)) throw new Error(`invalid light source: ${source}`);
40
39
  const currentColor = current?.color ?? 'unknown';
41
40
  const pendingColor = current?.pendingImprovement?.color ?? null;
42
41
  if (source === 'human') return { outcome: 'applied', color, source, pendingImprovement: null };
@@ -52,7 +51,7 @@ function nextLight(current, { service, color, source }) {
52
51
  const WEEKLY_COLLECTIVE_LIMIT = Object.freeze({ psychology: 1 });
53
52
 
54
53
  function collectiveOffer({
55
- service, color = 'unknown', invitationPaused = false, invitedThisWeek = false,
54
+ service, color = 'unknown', isInvitationPaused = false, hasInvitationThisWeek = false,
56
55
  collectivesThisWeek = 0, hasCapacity = false,
57
56
  }) {
58
57
  assertLight(service, color);
@@ -60,8 +59,8 @@ function collectiveOffer({
60
59
  if (color === 'red') return refuse('light_red');
61
60
  if (service === 'psychology' && color === 'orange') return refuse('light_orange');
62
61
  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');
62
+ if (isInvitationPaused) return refuse('invitation_paused');
63
+ if (hasInvitationThisWeek) return refuse('already_invited_this_week');
65
64
  const limit = WEEKLY_COLLECTIVE_LIMIT[service];
66
65
  if (limit != null && collectivesThisWeek >= limit) return refuse('weekly_limit');
67
66
  if (!hasCapacity) return refuse('no_capacity');
@@ -76,8 +75,6 @@ module.exports = {
76
75
  GROUP_INVITABLE,
77
76
  isSafeGroupCandidate,
78
77
  LIGHT_SCALE,
79
- LIGHT_SOURCES,
80
- WEEKLY_COLLECTIVE_LIMIT,
81
78
  nextLight,
82
79
  collectiveOffer,
83
80
  supportWeek,
@@ -10,12 +10,6 @@ function requireText(value, name) {
10
10
  if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
11
11
  }
12
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
13
  function actorFor(source, actor) {
20
14
  if (source === 'ai') return actor || AI_ACTOR;
21
15
  requireText(actor, 'actor');
@@ -87,7 +81,9 @@ async function applySupportLight({
87
81
  requireText(patientId, 'patientId');
88
82
  const who = actorFor(source, actor);
89
83
  const isHuman = source === 'human';
90
- if (isHuman) requireReviewedRevision(reviewedRevision);
84
+ if (isHuman && reviewedRevision !== null && !(Number.isInteger(reviewedRevision) && reviewedRevision >= 0)) {
85
+ throw new Error('reviewedRevision is required: the revision the specialist saw, or null for no light yet');
86
+ }
91
87
  const at = new Date(now);
92
88
  const query = { patientId, service };
93
89
  for (let attempt = 0; attempt < 5; attempt += 1) {
@@ -111,11 +107,11 @@ async function applySupportLight({
111
107
  }
112
108
 
113
109
  async function resolvePendingImprovement({
114
- patientId, service, accept, actor, reviewedRevision, now = new Date(),
110
+ patientId, service, isAccepted, actor, reviewedRevision, now = new Date(),
115
111
  }, { Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
116
112
  requireText(patientId, 'patientId');
117
113
  requireText(actor, 'actor');
118
- if (typeof accept !== 'boolean') throw new Error('accept must be a boolean');
114
+ if (typeof isAccepted !== 'boolean') throw new Error('isAccepted must be a boolean');
119
115
  if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
120
116
  const at = new Date(now);
121
117
  const query = { patientId, service, revision: reviewedRevision, pendingImprovement: { $ne: null } };
@@ -123,11 +119,11 @@ async function resolvePendingImprovement({
123
119
  if (!existing?.pendingImprovement) return null;
124
120
  await flushOutbox(EventModel, existing);
125
121
  const pending = existing.pendingImprovement;
126
- const patch = accept
122
+ const patch = isAccepted
127
123
  ? { color: pending.color, source: 'human', setBy: actor, setAt: at, evidence: pending.evidence || [], reason: pending.reason ?? null, pendingImprovement: null }
128
124
  : { pendingImprovement: null };
129
125
  const event = {
130
- outcome: accept ? 'accepted' : 'rejected', from: existing.color, to: pending.color, source: 'human', actor,
126
+ outcome: isAccepted ? 'accepted' : 'rejected', from: existing.color, to: pending.color, source: 'human', actor,
131
127
  evidence: pending.evidence || [], reason: pending.reason ?? null, at, revision: reviewedRevision + 1,
132
128
  };
133
129
  const light = await Model.findOneAndUpdate(query, { $set: { ...patch, outbox: [event] }, $inc: { revision: 1 } }, { new: true, lean: true });
@@ -163,14 +159,6 @@ async function readSupportLightHistory(patientId, {
163
159
  .slice(0, bounded);
164
160
  }
165
161
 
166
- function boardFilter({ service = null, color = null, pendingOnly = false } = {}) {
167
- return {
168
- ...(service ? { service } : {}),
169
- ...(color ? { color } : {}),
170
- ...(pendingOnly ? { pendingImprovement: { $ne: null } } : {}),
171
- };
172
- }
173
-
174
162
  const BOARD_RANK = {
175
163
  $switch: {
176
164
  branches: [
@@ -182,11 +170,17 @@ const BOARD_RANK = {
182
170
  },
183
171
  };
184
172
 
185
- async function readSupportLightBoard(filters = {}, { limit = BOARD_LIMIT, offset = 0, Model = getSupportLightModel() } = {}) {
173
+ async function readSupportLightBoard({ service = null, color = null, isPendingOnly = false } = {}, { limit = BOARD_LIMIT, offset = 0, Model = getSupportLightModel() } = {}) {
186
174
  const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, BOARD_LIMIT) : BOARD_LIMIT;
187
175
  const skipped = Number.isInteger(offset) && offset > 0 ? offset : 0;
188
176
  return Model.aggregate([
189
- { $match: boardFilter(filters) },
177
+ {
178
+ $match: {
179
+ ...(service ? { service } : {}),
180
+ ...(color ? { color } : {}),
181
+ ...(isPendingOnly ? { pendingImprovement: { $ne: null } } : {}),
182
+ },
183
+ },
190
184
  { $project: { _id: 0, outbox: 0, evidence: 0, 'pendingImprovement.evidence': 0 } },
191
185
  { $set: { boardRank: BOARD_RANK } },
192
186
  { $sort: { boardRank: 1, setAt: -1, patientId: 1, service: 1 } },
@@ -197,8 +191,6 @@ async function readSupportLightBoard(filters = {}, { limit = BOARD_LIMIT, offset
197
191
  }
198
192
 
199
193
  module.exports = {
200
- BOARD_LIMIT,
201
- HISTORY_READ_LIMIT,
202
194
  applySupportLight,
203
195
  readSupportLightBoard,
204
196
  resolvePendingImprovement,
@@ -2,6 +2,7 @@ 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');
5
6
 
6
7
  const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
7
8
 
@@ -65,15 +66,14 @@ const addInsAssistantController = async (req, res) => {
65
66
  };
66
67
 
67
68
  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
-
71
69
  try {
72
- await processSystemMessage(code, messages, role, { reply, triggeredBy });
70
+ await injectAssistantMessages(req.body, processSystemMessage);
73
71
  return res.status(200).json({ success: true, message: 'Message added to assistant' });
74
72
  } catch (error) {
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' });
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 });
77
77
  }
78
78
  };
79
79
 
@@ -27,6 +27,7 @@ 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');
30
31
  const { beginInstruction, endInstruction } = require('../services/instructionInFlightService');
31
32
  const { QueueReconciliationService } = require('../services/queueReconciliationService');
32
33
  const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMessageService');
@@ -1134,59 +1135,15 @@ class NexusMessaging {
1134
1135
  return result;
1135
1136
  }
1136
1137
 
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
- );
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
+ });
1190
1147
  }
1191
1148
 
1192
1149
  async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
package/lib/index.d.ts CHANGED
@@ -982,7 +982,7 @@ declare module '@peopl-health/nexus' {
982
982
  resolvePendingImprovement(request: {
983
983
  patientId: string;
984
984
  service: SupportService;
985
- accept: boolean;
985
+ isAccepted: boolean;
986
986
  actor: string;
987
987
  reviewedRevision: number;
988
988
  now?: Date;
@@ -991,28 +991,24 @@ declare module '@peopl-health/nexus' {
991
991
  readSupportLightBoard(filters?: {
992
992
  service?: SupportService | null;
993
993
  color?: SupportLightColor | null;
994
- pendingOnly?: boolean;
994
+ isPendingOnly?: boolean;
995
995
  }, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
996
- BOARD_LIMIT: number;
997
- HISTORY_READ_LIMIT: number;
998
996
  readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
999
997
  };
1000
998
 
1001
999
  export const supportInvitability: {
1002
1000
  LIGHT_SCALE: Readonly<Record<SupportService, readonly SupportLightColor[]>>;
1003
- LIGHT_SOURCES: readonly SupportLightSource[];
1004
- WEEKLY_COLLECTIVE_LIMIT: Readonly<Partial<Record<SupportService, number>>>;
1005
1001
  GROUP_INVITABLE: readonly Readonly<Record<string, unknown>>[];
1006
1002
  isSafeGroupCandidate(candidate: Partial<SupportCandidateRecord>): boolean;
1007
1003
  nextLight(
1008
- current: { color?: SupportLightColor | null } | null | undefined,
1004
+ current: { color?: SupportLightColor | null; pendingImprovement?: { color: SupportLightColor } | null } | null | undefined,
1009
1005
  proposal: { service: SupportService; color: SupportLightColor; source: SupportLightSource },
1010
1006
  ): { outcome: SupportLightOutcome; color?: SupportLightColor; source?: SupportLightSource; pendingImprovement?: { color: SupportLightColor } | null };
1011
1007
  collectiveOffer(request: {
1012
1008
  service: SupportService;
1013
1009
  color?: SupportLightColor;
1014
- invitationPaused?: boolean;
1015
- invitedThisWeek?: boolean;
1010
+ isInvitationPaused?: boolean;
1011
+ hasInvitationThisWeek?: boolean;
1016
1012
  collectivesThisWeek?: number;
1017
1013
  hasCapacity?: boolean;
1018
1014
  }): { allowed: boolean; reason: CollectiveRefusal | null };
@@ -39,6 +39,16 @@ 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
+
42
52
  async function withAirtableRetry(operation, label, { retryNetworkErrors = true } = {}) {
43
53
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
44
54
  try {
@@ -51,7 +61,7 @@ async function withAirtableRetry(operation, label, { retryNetworkErrors = true }
51
61
  throw error;
52
62
  }
53
63
  const baseDelay = error.statusCode === RATE_LIMITED_STATUS ? RATE_LIMIT_DELAY_MS : RETRY_BASE_DELAY_MS;
54
- logger.warn(`[${label}] Airtable unavailable, retrying`, { statusCode: error.statusCode, errorCode: error.code, attempt, maxAttempts: MAX_ATTEMPTS, delayMs: baseDelay * attempt });
64
+ logger.warn(`[${label}] Airtable unavailable, retrying`, { ...safeAirtableFailure(error), attempt, maxAttempts: MAX_ATTEMPTS, delayMs: baseDelay * attempt });
55
65
  await delay(baseDelay * attempt);
56
66
  }
57
67
  }
@@ -112,7 +122,7 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
112
122
  'getRecordByFilter'
113
123
  );
114
124
  } catch (error) {
115
- logger.error('[getRecordByFilter] Failed', { tableName, filter, fields, error: error.message });
125
+ logger.error('[getRecordByFilter] Failed', safeAirtableFailure(error));
116
126
  throw error;
117
127
  }
118
128
  }
@@ -0,0 +1,140 @@
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.60.0-dev.11095",
3
+ "version": "5.60.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",