@peopl-health/nexus 5.59.9 → 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.
|
@@ -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
|
|
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
|
-
|
|
76
|
-
|
|
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',
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
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) {
|
|
@@ -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`, {
|
|
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',
|
|
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 };
|