@peopl-health/nexus 6.4.22 → 6.4.23
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.
- package/lib/controllers/assistantController.js +5 -2
- package/lib/controllers/messageController.js +5 -6
- package/lib/core/NexusMessaging.js +11 -8
- package/lib/helpers/caregiverHelper.js +8 -0
- package/lib/index.d.ts +2 -2
- package/lib/services/assistantMessageService.js +11 -6
- package/package.json +1 -1
|
@@ -4,6 +4,7 @@ const { DUPLICATE_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig
|
|
|
4
4
|
|
|
5
5
|
const { logger } = require('../utils/logger');
|
|
6
6
|
const { isArchivedPatientCode } = require('../helpers/twilioHelper');
|
|
7
|
+
const { registeredCaregiverCode } = require('../helpers/caregiverHelper');
|
|
7
8
|
const { AssistantMessageError, injectAssistantMessages } = require('../services/assistantMessageService');
|
|
8
9
|
|
|
9
10
|
const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
|
|
@@ -60,11 +61,13 @@ const doNotAlertController = async (req, res) => {
|
|
|
60
61
|
};
|
|
61
62
|
|
|
62
63
|
const addInsAssistantController = async (req, res) => {
|
|
63
|
-
const { code, instruction, triggeredBy } = req.body;
|
|
64
|
+
const { code, instruction, triggeredBy, contactCode } = req.body;
|
|
64
65
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
65
66
|
|
|
66
67
|
try {
|
|
67
|
-
const
|
|
68
|
+
const caregiverCode = contactCode ? await registeredCaregiverCode(code, contactCode) : null;
|
|
69
|
+
if (contactCode && !caregiverCode) return res.status(400).json({ success: false, error: 'contactCode is not a registered caregiver of this patient' });
|
|
70
|
+
const result = await processInstruction(code, instruction, 'developer', { triggeredBy, dedupeWithinMs: DUPLICATE_INSTRUCTION_WINDOW_MS, ...(caregiverCode && { contactCode: caregiverCode }) });
|
|
68
71
|
if (result?.outcome === 'duplicate') {
|
|
69
72
|
return res.status(200).json({ success: true, duplicate: true, message: 'Instruction already answered' });
|
|
70
73
|
}
|
|
@@ -9,9 +9,9 @@ const { ScheduledMessage } = require('../models/agendaMessageModel.js');
|
|
|
9
9
|
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
|
|
10
10
|
const { FlowRouting } = require('../models/flowRoutingModel.js');
|
|
11
11
|
|
|
12
|
-
const { ensureWhatsAppFormat,
|
|
12
|
+
const { ensureWhatsAppFormat, isArchivedPatientCode } = require('../helpers/twilioHelper');
|
|
13
13
|
const { ensureFlowTokenInVariables } = require('../helpers/templateFlowControllerHelper');
|
|
14
|
-
const { CAREGIVER_ROLE,
|
|
14
|
+
const { CAREGIVER_ROLE, registeredCaregiverCode } = require('../helpers/caregiverHelper');
|
|
15
15
|
|
|
16
16
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
17
17
|
const { getMessages } = require('../services/messageService');
|
|
@@ -105,12 +105,11 @@ const sendMessageController = async (req, res) => {
|
|
|
105
105
|
if (sendTime) {
|
|
106
106
|
return res.status(400).json({ success: false, error: 'contactCode cannot be combined with sendTime' });
|
|
107
107
|
}
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
if (!caregiver || stripWhatsAppFormat(caregiver.patientCode) !== stripWhatsAppFormat(formattedCode)) {
|
|
108
|
+
const caregiverCode = await registeredCaregiverCode(formattedCode, contactCode);
|
|
109
|
+
if (!caregiverCode) {
|
|
111
110
|
return res.status(400).json({ success: false, error: 'contactCode is not a registered caregiver of this patient' });
|
|
112
111
|
}
|
|
113
|
-
contact = { contactCode:
|
|
112
|
+
contact = { contactCode: caregiverCode, contactRole: CAREGIVER_ROLE };
|
|
114
113
|
}
|
|
115
114
|
|
|
116
115
|
const finalVariables = contentSid ? await ensureFlowTokenInVariables(contentSid, variables) : variables;
|
|
@@ -18,7 +18,7 @@ const { Thread } = require('../models/threadModel');
|
|
|
18
18
|
|
|
19
19
|
const { storeRunMetrics } = require('../helpers/metricsHelper');
|
|
20
20
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
21
|
-
const { maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
|
|
21
|
+
const { CAREGIVER_ROLE, maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
|
|
22
22
|
const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
|
|
23
23
|
const { prepareMessageMedia } = require('../helpers/mediaHelper');
|
|
24
24
|
const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
|
|
@@ -882,8 +882,8 @@ class NexusMessaging {
|
|
|
882
882
|
* batch, and is marked processed when vetoed or refused by a draining instance, so it can only ever
|
|
883
883
|
* run behind its own gate.
|
|
884
884
|
*/
|
|
885
|
-
async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0 } = {}) {
|
|
886
|
-
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs)) {
|
|
885
|
+
async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0, contactCode = null } = {}) {
|
|
886
|
+
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, null, contactCode)) {
|
|
887
887
|
logger.info('[processInstruction] Identical instruction already answered; skipping the resend', { code, triggeredBy: triggeredBy || null });
|
|
888
888
|
return { outcome: 'duplicate' };
|
|
889
889
|
}
|
|
@@ -899,6 +899,7 @@ class NexusMessaging {
|
|
|
899
899
|
raw: beforeRun ? { role, gated: true } : { role },
|
|
900
900
|
triggeredBy: triggeredBy || null,
|
|
901
901
|
silent: true,
|
|
902
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
902
903
|
};
|
|
903
904
|
|
|
904
905
|
beginInstruction(code);
|
|
@@ -946,13 +947,13 @@ class NexusMessaging {
|
|
|
946
947
|
return null;
|
|
947
948
|
}
|
|
948
949
|
}
|
|
949
|
-
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id)) {
|
|
950
|
+
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id, contactCode)) {
|
|
950
951
|
logger.info('[processInstruction] Identical instruction answered while this one waited; skipping it', { code, triggeredBy: triggeredBy || null });
|
|
951
952
|
duplicate = true;
|
|
952
953
|
await markOwnProcessed();
|
|
953
954
|
return null;
|
|
954
955
|
}
|
|
955
|
-
const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
|
|
956
|
+
const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt, contactCode);
|
|
956
957
|
if (!batch.length) {
|
|
957
958
|
logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
|
|
958
959
|
alreadyAnswered = true;
|
|
@@ -966,6 +967,7 @@ class NexusMessaging {
|
|
|
966
967
|
additionalInstructions: batch.map(m => m.body).join('\n\n'),
|
|
967
968
|
toolChoice: 'none',
|
|
968
969
|
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
970
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
969
971
|
runId,
|
|
970
972
|
shouldContinue,
|
|
971
973
|
signal: this.batchingManager.getAbortSignal(runId),
|
|
@@ -1016,7 +1018,7 @@ class NexusMessaging {
|
|
|
1016
1018
|
}
|
|
1017
1019
|
}
|
|
1018
1020
|
|
|
1019
|
-
async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null) {
|
|
1021
|
+
async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null, contactCode = null) {
|
|
1020
1022
|
try {
|
|
1021
1023
|
const rows = await getMessages(
|
|
1022
1024
|
{
|
|
@@ -1024,6 +1026,7 @@ class NexusMessaging {
|
|
|
1024
1026
|
origin: 'instruction',
|
|
1025
1027
|
message_id: /^instruction_/,
|
|
1026
1028
|
plainBody: instruction,
|
|
1029
|
+
contact_code: contactCode,
|
|
1027
1030
|
processed: true,
|
|
1028
1031
|
'raw.gated': { $ne: true },
|
|
1029
1032
|
createdAt: { $gte: new Date(Date.now() - windowMs) },
|
|
@@ -1038,7 +1041,7 @@ class NexusMessaging {
|
|
|
1038
1041
|
}
|
|
1039
1042
|
}
|
|
1040
1043
|
|
|
1041
|
-
async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
|
|
1044
|
+
async _pendingInstructionBatch(code, ownId, ownBody, receivedAt, contactCode = null) {
|
|
1042
1045
|
if (!ownId) return [{ _id: null, body: ownBody }];
|
|
1043
1046
|
try {
|
|
1044
1047
|
const rows = await getMessages(
|
|
@@ -1046,7 +1049,7 @@ class NexusMessaging {
|
|
|
1046
1049
|
numero: code,
|
|
1047
1050
|
origin: 'instruction',
|
|
1048
1051
|
message_id: /^instruction_/,
|
|
1049
|
-
$or: [{ _id: ownId }, { processed: false, 'raw.gated': { $ne: true }, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
|
|
1052
|
+
$or: [{ _id: ownId }, { processed: false, 'raw.gated': { $ne: true }, contact_code: contactCode, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
|
|
1050
1053
|
},
|
|
1051
1054
|
{ sort: { _id: 1 }, select: '_id body processed' },
|
|
1052
1055
|
);
|
|
@@ -79,6 +79,13 @@ async function resolveCaregiver(code, { strict = false } = {}) {
|
|
|
79
79
|
return resolved;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
async function registeredCaregiverCode(patientCode, contactCode) {
|
|
83
|
+
const formatted = ensureWhatsAppFormat(contactCode);
|
|
84
|
+
const caregiver = await resolveCaregiver(formatted, { strict: true });
|
|
85
|
+
if (!caregiver || stripWhatsAppFormat(caregiver.patientCode) !== stripWhatsAppFormat(patientCode)) return null;
|
|
86
|
+
return formatted;
|
|
87
|
+
}
|
|
88
|
+
|
|
82
89
|
async function remapCaregiverSender(messageData) {
|
|
83
90
|
if (!messageData?.code || messageData.fromMe !== false || messageData.contactCode) return messageData;
|
|
84
91
|
const caregiver = await resolveCaregiver(messageData.code);
|
|
@@ -129,6 +136,7 @@ module.exports = {
|
|
|
129
136
|
contactOf,
|
|
130
137
|
listedCaregivers,
|
|
131
138
|
maskCaregiverLabel,
|
|
139
|
+
registeredCaregiverCode,
|
|
132
140
|
remapCaregiverSender,
|
|
133
141
|
replyContactFor,
|
|
134
142
|
resolveCaregiver,
|
package/lib/index.d.ts
CHANGED
|
@@ -275,8 +275,8 @@ declare module '@peopl-health/nexus' {
|
|
|
275
275
|
getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
|
|
276
276
|
initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
|
|
277
277
|
getWorkflowRunner(): WorkflowRunner;
|
|
278
|
-
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
279
|
-
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<{ delivery: Record<string, unknown> | null; sendThrew: boolean; reply: string | null } | undefined>;
|
|
278
|
+
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number; contactCode?: string | null }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
279
|
+
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean; contactCode?: string | null }): Promise<{ delivery: Record<string, unknown> | null; sendThrew: boolean; reply: string | null } | undefined>;
|
|
280
280
|
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
|
|
281
281
|
processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
|
|
282
282
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { Monitoreo_ID: monitoreoId } = require('../config/airtableConfig');
|
|
2
2
|
const { logger } = require('../utils/logger');
|
|
3
3
|
const { Thread } = require('../models/threadModel');
|
|
4
|
+
const { CAREGIVER_ROLE, registeredCaregiverCode } = require('../helpers/caregiverHelper');
|
|
4
5
|
const { requirePatientIdentity } = require('../clinical/services/patientIdentityService');
|
|
5
6
|
const { TURN_KIND } = require('../clinical/context/turnContext');
|
|
6
7
|
|
|
@@ -14,6 +15,7 @@ const ASSISTANT_MESSAGE_FAILURES = {
|
|
|
14
15
|
INVALID_ROLE: [400, 'role must be system or developer'],
|
|
15
16
|
INVALID_REPLY: [400, 'reply must be a boolean'],
|
|
16
17
|
INVALID_OPTIONS: [400, 'options must be an object'],
|
|
18
|
+
INVALID_CONTACT: [400, 'contactCode is not a registered caregiver of this patient'],
|
|
17
19
|
PATIENT_IDENTITY_INVALID: [400, 'Invalid patient identity'],
|
|
18
20
|
PATIENT_IDENTITY_MISSING: [404, 'Patient identity not found'],
|
|
19
21
|
PATIENT_IDENTITY_AMBIGUOUS: [409, 'Patient identity is ambiguous'],
|
|
@@ -39,7 +41,7 @@ function validateAssistantMessages(body, { shouldReplyByDefault = false } = {})
|
|
|
39
41
|
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new AssistantMessageError('INVALID_BODY');
|
|
40
42
|
if (Object.hasOwn(body, 'instruction')) throw new AssistantMessageError('UNSUPPORTED_INSTRUCTION_ALIAS');
|
|
41
43
|
if (Object.hasOwn(body, 'codes')) throw new AssistantMessageError('UNSUPPORTED_CODES_ALIAS');
|
|
42
|
-
const { code, messages, role = 'system', reply = shouldReplyByDefault, triggeredBy } = body;
|
|
44
|
+
const { code, messages, role = 'system', reply = shouldReplyByDefault, triggeredBy, contactCode = null } = body;
|
|
43
45
|
if (typeof code !== 'string' || !code.trim()) throw new AssistantMessageError('INVALID_CODE');
|
|
44
46
|
// Copy the batch so later caller mutation cannot invalidate entries during awaited saves.
|
|
45
47
|
const batch = Array.isArray(messages) ? Array.from(messages) : [messages];
|
|
@@ -49,11 +51,11 @@ function validateAssistantMessages(body, { shouldReplyByDefault = false } = {})
|
|
|
49
51
|
const normalizedRole = typeof role === 'string' ? role.trim().toLowerCase() : null;
|
|
50
52
|
if (!['system', 'developer'].includes(normalizedRole)) throw new AssistantMessageError('INVALID_ROLE');
|
|
51
53
|
if (typeof reply !== 'boolean') throw new AssistantMessageError('INVALID_REPLY');
|
|
52
|
-
return { code, messages: batch, role: normalizedRole, reply, triggeredBy };
|
|
54
|
+
return { code, messages: batch, role: normalizedRole, reply, triggeredBy, contactCode };
|
|
53
55
|
}
|
|
54
56
|
|
|
55
57
|
async function injectAssistantMessages(body, processSystemMessage) {
|
|
56
|
-
const { code, messages, role, reply, triggeredBy } = validateAssistantMessages(body);
|
|
58
|
+
const { code, messages, role, reply, triggeredBy, contactCode } = validateAssistantMessages(body);
|
|
57
59
|
try {
|
|
58
60
|
await requirePatientIdentity(monitoreoId, code);
|
|
59
61
|
} catch (error) {
|
|
@@ -61,13 +63,15 @@ async function injectAssistantMessages(body, processSystemMessage) {
|
|
|
61
63
|
? error.code : 'PATIENT_IDENTITY_UNAVAILABLE';
|
|
62
64
|
throw new AssistantMessageError(reasonCode);
|
|
63
65
|
}
|
|
64
|
-
|
|
66
|
+
const caregiverCode = contactCode ? await registeredCaregiverCode(code, contactCode) : null;
|
|
67
|
+
if (contactCode && !caregiverCode) throw new AssistantMessageError('INVALID_CONTACT');
|
|
68
|
+
return processSystemMessage(code, messages, role, { reply, triggeredBy, ...(caregiverCode && { contactCode: caregiverCode }) });
|
|
65
69
|
}
|
|
66
70
|
|
|
67
71
|
async function processAssistantSystemMessage(code, messages, role = 'system', options = {}, dependencies) {
|
|
68
72
|
if (!options || typeof options !== 'object' || Array.isArray(options)) throw new AssistantMessageError('INVALID_OPTIONS');
|
|
69
73
|
const input = validateAssistantMessages({ ...options, code, messages, role }, { shouldReplyByDefault: true });
|
|
70
|
-
const { triggeredBy, reply } = input;
|
|
74
|
+
const { triggeredBy, reply, contactCode } = input;
|
|
71
75
|
let thread;
|
|
72
76
|
try {
|
|
73
77
|
thread = await Thread.findOne({ code }).lean();
|
|
@@ -115,7 +119,7 @@ async function processAssistantSystemMessage(code, messages, role = 'system', op
|
|
|
115
119
|
}
|
|
116
120
|
|
|
117
121
|
if (!reply) return;
|
|
118
|
-
recordPatientSend?.({ code, channel: 'assistant_instruction', sentBy: triggeredBy, text: input.messages.join('\n') });
|
|
122
|
+
if (!contactCode) recordPatientSend?.({ code, channel: 'assistant_instruction', sentBy: triggeredBy, text: input.messages.join('\n') });
|
|
119
123
|
|
|
120
124
|
let turn;
|
|
121
125
|
let settled = null;
|
|
@@ -128,6 +132,7 @@ async function processAssistantSystemMessage(code, messages, role = 'system', op
|
|
|
128
132
|
prePromptResult: preProcessResult,
|
|
129
133
|
toolChoice: 'none',
|
|
130
134
|
turnKind: TURN_KIND.SYSTEM,
|
|
135
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
131
136
|
runId,
|
|
132
137
|
shouldContinue,
|
|
133
138
|
signal: getAbortSignal(runId),
|