@peopl-health/nexus 6.4.21 → 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/clinical/AssistantProcessor.js +3 -1
- package/lib/clinical/services/bridgeService.js +2 -2
- package/lib/clinical/services/checkInDueService.js +1 -2
- package/lib/controllers/assistantController.js +5 -2
- package/lib/controllers/messageController.js +5 -6
- package/lib/core/NexusMessaging.js +16 -18
- package/lib/helpers/caregiverHelper.js +8 -0
- package/lib/index.d.ts +3 -3
- package/lib/services/assistantMessageService.js +11 -6
- package/package.json +1 -1
|
@@ -163,6 +163,7 @@ class AssistantProcessor {
|
|
|
163
163
|
traceId: ctx?.trace?._id ? String(ctx.trace._id) : null,
|
|
164
164
|
shouldContinue: runOptions.shouldContinue,
|
|
165
165
|
sendMessage: this.sendMessage,
|
|
166
|
+
...(runOptions.contactCode && { contactCode: runOptions.contactCode, contactRole: runOptions.contactRole }),
|
|
166
167
|
});
|
|
167
168
|
return bridgeDecision;
|
|
168
169
|
};
|
|
@@ -294,6 +295,7 @@ class AssistantProcessor {
|
|
|
294
295
|
outreachCarrier: runOptions.outreachCarrier || null,
|
|
295
296
|
outreachStartedAt: runOptions.outreachStartedAt || null,
|
|
296
297
|
triggeredBy: runOptions.triggeredBy || null,
|
|
298
|
+
...(runOptions.contactCode && { contactCode: runOptions.contactCode, contactRole: runOptions.contactRole }),
|
|
297
299
|
run,
|
|
298
300
|
predictionTimeMs,
|
|
299
301
|
retries: runResult?.retries || 0,
|
|
@@ -395,7 +397,7 @@ class AssistantProcessor {
|
|
|
395
397
|
const outreachCarrier = result.outreachCarrier
|
|
396
398
|
? { ...result.outreachCarrier, utilityBasis: result.signals?.outreachDecision?.utilityBasis || result.outreachCarrier.utilityBasis || null }
|
|
397
399
|
: null;
|
|
398
|
-
sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt });
|
|
400
|
+
sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt, ...(result.contactCode && { contactCode: result.contactCode, contactRole: result.contactRole }) });
|
|
399
401
|
result.delivery = sent || null;
|
|
400
402
|
} catch (error) {
|
|
401
403
|
if (directive) {
|
|
@@ -32,7 +32,7 @@ function buildDedupNote(bridgeText) {
|
|
|
32
32
|
'clínico. El mensaje final es la SEGUNDA burbuja que verá el paciente, no la primera.';
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage }) {
|
|
35
|
+
function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage, contactCode = null, contactRole = null }) {
|
|
36
36
|
const authored = typeof bridgeText === 'string' && bridgeText.trim() ? bridgeText : null;
|
|
37
37
|
|
|
38
38
|
if (!isBridgeEnabled()) return { sent: false, reason: 'disabled', proposed: Boolean(authored) };
|
|
@@ -67,7 +67,7 @@ function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false
|
|
|
67
67
|
if (entry.clearWhenDelivered && bridgeTimestamps.get(code) === entry) bridgeTimestamps.delete(code);
|
|
68
68
|
};
|
|
69
69
|
try {
|
|
70
|
-
Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId }))
|
|
70
|
+
Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId, ...(contactCode && { contactCode, contactRole }) }))
|
|
71
71
|
.then(delivered)
|
|
72
72
|
.catch(failed);
|
|
73
73
|
} catch (err) {
|
|
@@ -2,7 +2,6 @@ const moment = require('moment-timezone');
|
|
|
2
2
|
|
|
3
3
|
const { TRIAGE_RESULT_MARKER } = require('../helpers/triageResultMessageHelper');
|
|
4
4
|
const { getMessages } = require('../../services/messageService');
|
|
5
|
-
const { replyContactFor } = require('../../helpers/caregiverHelper');
|
|
6
5
|
const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
|
|
7
6
|
const { checkInsPausedUntil } = require('../../services/threadService');
|
|
8
7
|
const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
|
|
@@ -76,7 +75,7 @@ async function recentExchange(code, now) {
|
|
|
76
75
|
lastMessage(code, now, false),
|
|
77
76
|
lastMessage(code, now, true),
|
|
78
77
|
getMessages({ numero: code, from_me: true, ...OWN_WRITTEN, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
|
|
79
|
-
|
|
78
|
+
isWithin24HourWindow(code),
|
|
80
79
|
]);
|
|
81
80
|
return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
|
|
82
81
|
}
|
|
@@ -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');
|
|
@@ -519,10 +519,6 @@ class NexusMessaging {
|
|
|
519
519
|
|
|
520
520
|
async sendAssistantReply(messageData) {
|
|
521
521
|
if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
|
|
522
|
-
if (!messageData.contactCode && (messageData.outreachCarrier?.replyToContact || (!messageData.preemptiveWindowRoute && !messageData.outreachStartedAt))) {
|
|
523
|
-
const contact = await replyContactFor(messageData.code);
|
|
524
|
-
if (contact) messageData = { ...messageData, ...contact };
|
|
525
|
-
}
|
|
526
522
|
if (messageData.outreachStartedAt) {
|
|
527
523
|
const patientActivity = await getMessages({
|
|
528
524
|
numero: messageData.code,
|
|
@@ -740,7 +736,7 @@ class NexusMessaging {
|
|
|
740
736
|
if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
|
|
741
737
|
|
|
742
738
|
try {
|
|
743
|
-
const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true } }));
|
|
739
|
+
const result = await this._processMessages(from, async () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true, ...(await replyContactFor(from)) } }));
|
|
744
740
|
await this.assistantProcessor.sendResponse(from, result);
|
|
745
741
|
} catch (error) {
|
|
746
742
|
logger.error('Error in handleMessageWithAssistant', { error: error.message });
|
|
@@ -753,7 +749,7 @@ class NexusMessaging {
|
|
|
753
749
|
if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
|
|
754
750
|
|
|
755
751
|
try {
|
|
756
|
-
const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true } }));
|
|
752
|
+
const result = await this._processMessages(from, async () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true, ...(await replyContactFor(from)) } }));
|
|
757
753
|
await this.assistantProcessor.sendResponse(from, result);
|
|
758
754
|
} catch (error) {
|
|
759
755
|
logger.error('Error in handleMediaWithAssistant', { error: error.message });
|
|
@@ -858,7 +854,7 @@ class NexusMessaging {
|
|
|
858
854
|
|
|
859
855
|
const result = await this.assistantProcessor.executeLLM(
|
|
860
856
|
resolved.thread, resolved.assistant,
|
|
861
|
-
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
|
|
857
|
+
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId), ...(await replyContactFor(chatId)) },
|
|
862
858
|
preProcessed.messages[0]
|
|
863
859
|
);
|
|
864
860
|
|
|
@@ -886,8 +882,8 @@ class NexusMessaging {
|
|
|
886
882
|
* batch, and is marked processed when vetoed or refused by a draining instance, so it can only ever
|
|
887
883
|
* run behind its own gate.
|
|
888
884
|
*/
|
|
889
|
-
async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0 } = {}) {
|
|
890
|
-
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)) {
|
|
891
887
|
logger.info('[processInstruction] Identical instruction already answered; skipping the resend', { code, triggeredBy: triggeredBy || null });
|
|
892
888
|
return { outcome: 'duplicate' };
|
|
893
889
|
}
|
|
@@ -903,6 +899,7 @@ class NexusMessaging {
|
|
|
903
899
|
raw: beforeRun ? { role, gated: true } : { role },
|
|
904
900
|
triggeredBy: triggeredBy || null,
|
|
905
901
|
silent: true,
|
|
902
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
906
903
|
};
|
|
907
904
|
|
|
908
905
|
beginInstruction(code);
|
|
@@ -950,13 +947,13 @@ class NexusMessaging {
|
|
|
950
947
|
return null;
|
|
951
948
|
}
|
|
952
949
|
}
|
|
953
|
-
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id)) {
|
|
950
|
+
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id, contactCode)) {
|
|
954
951
|
logger.info('[processInstruction] Identical instruction answered while this one waited; skipping it', { code, triggeredBy: triggeredBy || null });
|
|
955
952
|
duplicate = true;
|
|
956
953
|
await markOwnProcessed();
|
|
957
954
|
return null;
|
|
958
955
|
}
|
|
959
|
-
const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
|
|
956
|
+
const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt, contactCode);
|
|
960
957
|
if (!batch.length) {
|
|
961
958
|
logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
|
|
962
959
|
alreadyAnswered = true;
|
|
@@ -970,6 +967,7 @@ class NexusMessaging {
|
|
|
970
967
|
additionalInstructions: batch.map(m => m.body).join('\n\n'),
|
|
971
968
|
toolChoice: 'none',
|
|
972
969
|
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
970
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
973
971
|
runId,
|
|
974
972
|
shouldContinue,
|
|
975
973
|
signal: this.batchingManager.getAbortSignal(runId),
|
|
@@ -1020,7 +1018,7 @@ class NexusMessaging {
|
|
|
1020
1018
|
}
|
|
1021
1019
|
}
|
|
1022
1020
|
|
|
1023
|
-
async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null) {
|
|
1021
|
+
async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null, contactCode = null) {
|
|
1024
1022
|
try {
|
|
1025
1023
|
const rows = await getMessages(
|
|
1026
1024
|
{
|
|
@@ -1028,6 +1026,7 @@ class NexusMessaging {
|
|
|
1028
1026
|
origin: 'instruction',
|
|
1029
1027
|
message_id: /^instruction_/,
|
|
1030
1028
|
plainBody: instruction,
|
|
1029
|
+
contact_code: contactCode,
|
|
1031
1030
|
processed: true,
|
|
1032
1031
|
'raw.gated': { $ne: true },
|
|
1033
1032
|
createdAt: { $gte: new Date(Date.now() - windowMs) },
|
|
@@ -1042,7 +1041,7 @@ class NexusMessaging {
|
|
|
1042
1041
|
}
|
|
1043
1042
|
}
|
|
1044
1043
|
|
|
1045
|
-
async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
|
|
1044
|
+
async _pendingInstructionBatch(code, ownId, ownBody, receivedAt, contactCode = null) {
|
|
1046
1045
|
if (!ownId) return [{ _id: null, body: ownBody }];
|
|
1047
1046
|
try {
|
|
1048
1047
|
const rows = await getMessages(
|
|
@@ -1050,7 +1049,7 @@ class NexusMessaging {
|
|
|
1050
1049
|
numero: code,
|
|
1051
1050
|
origin: 'instruction',
|
|
1052
1051
|
message_id: /^instruction_/,
|
|
1053
|
-
$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) } }],
|
|
1054
1053
|
},
|
|
1055
1054
|
{ sort: { _id: 1 }, select: '_id body processed' },
|
|
1056
1055
|
);
|
|
@@ -1078,7 +1077,6 @@ class NexusMessaging {
|
|
|
1078
1077
|
firstName = null,
|
|
1079
1078
|
reminderType = 'seguimiento',
|
|
1080
1079
|
reminderPrefix = null,
|
|
1081
|
-
replyToContact = false,
|
|
1082
1080
|
allowFollowUp = true,
|
|
1083
1081
|
dryRun = false,
|
|
1084
1082
|
} = {}) {
|
|
@@ -1112,7 +1110,7 @@ class NexusMessaging {
|
|
|
1112
1110
|
turnKind: TURN_KIND.PROACTIVE_OUTREACH,
|
|
1113
1111
|
outreachBrief: brief,
|
|
1114
1112
|
preemptiveWindowRoute: true,
|
|
1115
|
-
outreachCarrier: { reminderType, reminderPrefix, firstName
|
|
1113
|
+
outreachCarrier: { reminderType, reminderPrefix, firstName },
|
|
1116
1114
|
outreachAllowsFollowUp: allowFollowUp,
|
|
1117
1115
|
outreachStartedAt,
|
|
1118
1116
|
// Stamped on the outbound so a delivered message joins back to the row that surfaced her.
|
|
@@ -1250,7 +1248,7 @@ class NexusMessaging {
|
|
|
1250
1248
|
const sent = outcome === 'sent' || outcome === 'unknown';
|
|
1251
1249
|
result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
|
|
1252
1250
|
} else {
|
|
1253
|
-
const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName
|
|
1251
|
+
const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName });
|
|
1254
1252
|
result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
|
|
1255
1253
|
}
|
|
1256
1254
|
|
|
@@ -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,9 +275,9 @@ 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>;
|
|
280
|
-
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean;
|
|
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
|
+
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>;
|
|
283
283
|
isConnected(): boolean;
|
|
@@ -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),
|