@peopl-health/nexus 5.59.8 → 5.59.10

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.
@@ -17,6 +17,7 @@ const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
17
17
  const { getRecordByFilter } = require('../../services/airtableService');
18
18
  const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
19
19
  const { getMessages, countMessages } = require('../../services/messageService');
20
+ const { hasInstructionInFlight } = require('../../services/instructionInFlightService');
20
21
  const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
21
22
  const { CURRENT_TURN } = require('../promptPlacement');
22
23
 
@@ -40,6 +41,8 @@ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
40
41
 
41
42
  const inline = (value) => sanitizeInlineText(value, Infinity);
42
43
 
44
+ const PENDING_INSTRUCTION_NOTE = `${OPERATOR_TURN_PREFIX} Hay un mensaje del sistema en curso para el paciente (por ejemplo, la confirmación de los botones que acaba de tocar) que se le enviará por separado. No lo anticipes ni lo confirmes tú; responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
45
+
43
46
  const deliveredWhileWaitingNote = (text) =>
44
47
  `${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
45
48
 
@@ -130,6 +133,10 @@ class DefaultMemoryManager extends MemoryManager {
130
133
  }
131
134
  }
132
135
 
136
+ if (this._hasPendingInstruction(thread.code, beforeCheckpoint, config)) {
137
+ context.push({ [CURRENT_TURN]: true, role: 'user', content: PENDING_INSTRUCTION_NOTE, type: 'message' });
138
+ }
139
+
133
140
  return [...context, ...additional];
134
141
  } catch (error) {
135
142
  logger.error('[DefaultMemoryManager] Context building failed', { threadCode: thread.code, error: error.message });
@@ -137,6 +144,10 @@ class DefaultMemoryManager extends MemoryManager {
137
144
  }
138
145
  }
139
146
 
147
+ _hasPendingInstruction(code, beforeCheckpoint, config) {
148
+ return Boolean(beforeCheckpoint) && !config.beforeCheckpoint && hasInstructionInFlight(code);
149
+ }
150
+
140
151
  async _outboundTail(code, beforeCheckpoint, config) {
141
152
  const upperBound = config.tailUpperBound ?? (config.beforeCheckpoint ? null : new Date());
142
153
  if (!beforeCheckpoint || !upperBound) return [];
@@ -0,0 +1,4 @@
1
+ const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
2
+ const DEFAULT_INSTRUCTION_SETTLE_MS = 2500;
3
+
4
+ module.exports = { PENDING_INSTRUCTION_WINDOW_MS, DEFAULT_INSTRUCTION_SETTLE_MS };
@@ -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
 
@@ -63,6 +63,10 @@ class BatchingManager {
63
63
  return (current === undefined || current === runId) && !this.abandonedRuns.has(runId);
64
64
  }
65
65
 
66
+ isAbandoned(runId) {
67
+ return this.abandonedRuns.has(runId);
68
+ }
69
+
66
70
  getAbortSignal(runId) {
67
71
  return this.abortControllers.get(runId)?.signal;
68
72
  }
@@ -4,6 +4,7 @@ const { airtable } = require('../config/airtableConfig');
4
4
  const { connect } = require('../config/mongoConfig');
5
5
  const { setMetaConfig } = require('../config/metaConfig');
6
6
  const runtimeConfig = require('../config/runtimeConfig');
7
+ const { DEFAULT_INSTRUCTION_SETTLE_MS, PENDING_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig');
7
8
  const { decodeUnicodeEscapes, decodeUnicodeEscapesDeep } = require('../utils/sanitizerUtils');
8
9
  const { runInShadowScope } = require('../utils/shadowScope');
9
10
 
@@ -26,6 +27,8 @@ const { ensureThreadExists } = require('../services/threadService');
26
27
 
27
28
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
28
29
  const { getMessages, updateMessage } = require('../services/messageService');
30
+ const { processAssistantSystemMessage } = require('../services/assistantMessageService');
31
+ const { beginInstruction, endInstruction } = require('../services/instructionInFlightService');
29
32
  const { QueueReconciliationService } = require('../services/queueReconciliationService');
30
33
  const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMessageService');
31
34
 
@@ -53,8 +56,6 @@ const { invokeInteractiveRoute } = require('./interactiveRouteService');
53
56
 
54
57
  const { PhiProcessor } = require('./PhiProcessor');
55
58
 
56
- const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
57
-
58
59
  const unbatchedRoutes = {
59
60
  __proto__: null,
60
61
  flow: 'handleFlow',
@@ -113,6 +114,7 @@ class NexusMessaging {
113
114
  abortOnNewMessage: config.messageBatching?.abortOnNewMessage ?? true,
114
115
  immediateRestart: config.messageBatching?.immediateRestart ?? true,
115
116
  typingIndicator: config.messageBatching?.typingIndicator ?? false,
117
+ instructionSettleMs: config.messageBatching?.instructionSettleMs ?? DEFAULT_INSTRUCTION_SETTLE_MS,
116
118
  hooks: config.messageBatching?.hooks || {},
117
119
  };
118
120
 
@@ -698,7 +700,7 @@ class NexusMessaging {
698
700
  * PROCESSING PIPELINE
699
701
  */
700
702
 
701
- async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSent = null } = {}) {
703
+ async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSendSettled = null } = {}) {
702
704
  let capturedResult = null;
703
705
  const discardResponseFn = async (result) => {
704
706
  await this.assistantProcessor.discardResponse(chatId, result);
@@ -721,8 +723,13 @@ class NexusMessaging {
721
723
  await discardResponseFn(result);
722
724
  return;
723
725
  }
724
- await this.assistantProcessor.sendResponse(chatId, result);
725
- if (onSent && result?.delivery && deliveryOutcome(result.delivery) !== 'known_not_sent') await onSent(result);
726
+ try {
727
+ await this.assistantProcessor.sendResponse(chatId, result);
728
+ } catch (error) {
729
+ await onSendSettled?.('threw');
730
+ throw error;
731
+ }
732
+ await onSendSettled?.(result?.delivery ? deliveryOutcome(result.delivery) : 'not_sent');
726
733
  };
727
734
 
728
735
  const admission = mode === 'queue'
@@ -810,6 +817,7 @@ class NexusMessaging {
810
817
  }
811
818
 
812
819
  async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
820
+ const receivedAt = Date.now();
813
821
  const messageData = {
814
822
  pushName: 'Instruction',
815
823
  code,
@@ -823,50 +831,77 @@ class NexusMessaging {
823
831
  silent: true,
824
832
  };
825
833
 
826
- await this.phiProcessor.inData(
827
- messageData,
828
- this._saveMessageFn,
829
- async ({ body, _id }) => {
830
- let answered = [];
831
- const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
832
- async (preProcessResult, shouldContinue, runId) => {
833
- const batch = await this._pendingInstructionBatch(code, _id, body);
834
- if (!batch.length) {
835
- logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
836
- return null;
837
- }
838
- const result = await this.assistantProcessor.process({
839
- code,
840
- runOptions: {
841
- prePromptResult: preProcessResult,
842
- additionalInstructions: batch.map(m => m.body).join('\n\n'),
843
- toolChoice: 'none',
844
- turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
845
- runId,
846
- shouldContinue,
847
- signal: this.batchingManager.getAbortSignal(runId),
848
- }
849
- });
850
- answered = batch.map(m => m._id).filter(Boolean);
851
- return result;
852
- },
853
- {
854
- onSent: async () => {
855
- if (!answered.length) return;
856
- try {
857
- await updateMessage({ _id: { $in: answered } }, { $set: { processed: true } });
858
- } catch (err) {
859
- logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
860
- }
861
- },
862
- },
863
- );
864
- return runResult;
865
- },
866
- );
834
+ beginInstruction(code);
835
+ try {
836
+ await this.phiProcessor.inData(
837
+ messageData,
838
+ this._saveMessageFn,
839
+ async ({ body, _id }) => {
840
+ if (this.batchingConfig.instructionSettleMs > 0 && !this.batchingManager.isDraining()) {
841
+ await new Promise(resolve => setTimeout(resolve, this.batchingConfig.instructionSettleMs));
842
+ }
843
+ let batchIds = [];
844
+ let outcome = null;
845
+ let runId = null;
846
+ const answerPending = () => {
847
+ batchIds = [];
848
+ outcome = null;
849
+ runId = null;
850
+ return this._executeWithPipeline(code, 'instruction', 'queue',
851
+ async (preProcessResult, shouldContinue, currentRunId) => {
852
+ runId = currentRunId;
853
+ const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
854
+ if (!batch.length) {
855
+ logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
856
+ return null;
857
+ }
858
+ batchIds = batch.map(m => m._id).filter(Boolean);
859
+ return this.assistantProcessor.process({
860
+ code,
861
+ runOptions: {
862
+ prePromptResult: preProcessResult,
863
+ additionalInstructions: batch.map(m => m.body).join('\n\n'),
864
+ toolChoice: 'none',
865
+ turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
866
+ runId,
867
+ shouldContinue,
868
+ signal: this.batchingManager.getAbortSignal(runId),
869
+ }
870
+ });
871
+ },
872
+ {
873
+ onSendSettled: async (settled) => {
874
+ outcome = settled;
875
+ if (!batchIds.length || (settled !== 'sent' && settled !== 'unknown')) return;
876
+ try {
877
+ await updateMessage({ _id: { $in: batchIds } }, { $set: { processed: true } });
878
+ } catch (err) {
879
+ logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
880
+ }
881
+ },
882
+ },
883
+ );
884
+ };
885
+ const needsAnotherTurn = () => batchIds.length > 0
886
+ && ((outcome === null && this.batchingManager.isAbandoned(runId)) || outcome === 'known_not_sent');
887
+
888
+ let runResult = await answerPending();
889
+ if (needsAnotherTurn()) {
890
+ logger.warn('[processInstruction] Instruction reply was not sent; queueing one more turn', { code, outcome });
891
+ runResult = await answerPending();
892
+ }
893
+ if (batchIds.length && outcome !== 'sent' && outcome !== 'unknown') {
894
+ logger.error('[processInstruction] Instruction left unanswered', { code, outcome, instructionIds: batchIds.map(String) });
895
+ }
896
+ return runResult;
897
+ },
898
+ );
899
+ } finally {
900
+ endInstruction(code);
901
+ }
867
902
  }
868
903
 
869
- async _pendingInstructionBatch(code, ownId, ownBody) {
904
+ async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
870
905
  if (!ownId) return [{ _id: null, body: ownBody }];
871
906
  try {
872
907
  const rows = await getMessages(
@@ -874,7 +909,7 @@ class NexusMessaging {
874
909
  numero: code,
875
910
  origin: 'instruction',
876
911
  message_id: /^instruction_/,
877
- $or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(Date.now() - PENDING_INSTRUCTION_WINDOW_MS) } }],
912
+ $or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
878
913
  },
879
914
  { sort: { _id: 1 }, select: '_id body processed' },
880
915
  );
@@ -1100,59 +1135,15 @@ class NexusMessaging {
1100
1135
  return result;
1101
1136
  }
1102
1137
 
1103
- async processSystemMessage(code, messages, role = 'system', { triggeredBy, reply = true } = {}) {
1104
- const thread = await Thread.findOne({ code }).lean();
1105
- if (!thread) return;
1106
-
1107
- // Dropped rather than stored: these now emit message:new and would render as an empty bubble.
1108
- const requestedMessages = Array.isArray(messages) ? messages : [messages];
1109
- const normalizedMessages = requestedMessages.filter(body => typeof body === 'string' && body.trim());
1110
- if (normalizedMessages.length !== requestedMessages.length) {
1111
- logger.warn('[processSystemMessage] Ignoring blank message entries', {
1112
- code,
1113
- ignored: requestedMessages.length - normalizedMessages.length,
1114
- });
1115
- }
1116
- // Every entry was blank: nothing to store, and so nothing for the agent to reply to.
1117
- if (!normalizedMessages.length) return null;
1118
-
1119
- for (let i = 0; i < normalizedMessages.length; i++) {
1120
- try {
1121
- const messageData = {
1122
- pushName: 'System',
1123
- code,
1124
- body: normalizedMessages[i],
1125
- messageId: `system_${Date.now()}_${i}_${Math.random().toString(36).substring(7)}`,
1126
- fromMe: true,
1127
- processed: true,
1128
- origin: 'system',
1129
- raw: { role, replyRequested: reply },
1130
- triggeredBy: triggeredBy || null,
1131
- // No `silent`: it suppresses the message:new event an interface renders from. Instructions keep it.
1132
- };
1133
- await this.phiProcessor.inData(messageData, this._saveMessageFn, () => {});
1134
- } catch (err) {
1135
- logger.error('[processSystemMessage] Error saving system message', { error: err.message, code, index: i });
1136
- }
1137
- }
1138
-
1139
- if (!reply) return;
1140
-
1141
- await this._executeWithPipeline(code, 'system', 'queue',
1142
- async (preProcessResult, shouldContinue, runId) => {
1143
- return await this.assistantProcessor.process({
1144
- code,
1145
- runOptions: {
1146
- prePromptResult: preProcessResult,
1147
- toolChoice: 'none',
1148
- turnKind: TURN_KIND.SYSTEM,
1149
- runId,
1150
- shouldContinue,
1151
- signal: this.batchingManager.getAbortSignal(runId),
1152
- }
1153
- });
1154
- }
1155
- );
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
+ });
1156
1147
  }
1157
1148
 
1158
1149
  async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
package/lib/index.d.ts CHANGED
@@ -924,6 +924,7 @@ declare module '@peopl-health/nexus' {
924
924
  abortOnNewMessage?: boolean;
925
925
  immediateRestart?: boolean;
926
926
  typingIndicator?: boolean;
927
+ instructionSettleMs?: number;
927
928
  hooks?: Record<string, Function | Function[]>;
928
929
  }
929
930
 
@@ -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 };
@@ -0,0 +1,17 @@
1
+ const inFlight = new Map();
2
+
3
+ function beginInstruction(code) {
4
+ inFlight.set(code, (inFlight.get(code) || 0) + 1);
5
+ }
6
+
7
+ function endInstruction(code) {
8
+ const remaining = (inFlight.get(code) || 0) - 1;
9
+ if (remaining > 0) inFlight.set(code, remaining);
10
+ else inFlight.delete(code);
11
+ }
12
+
13
+ function hasInstructionInFlight(code) {
14
+ return inFlight.has(code);
15
+ }
16
+
17
+ module.exports = { beginInstruction, endInstruction, hasInstructionInFlight };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.8",
3
+ "version": "5.59.10",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",