@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20073
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/config/planTextsConfig.js +41 -0
- package/lib/clinical/flags/escalationFlags.js +15 -0
- package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
- package/lib/clinical/helpers/legacyContextHelper.js +6 -2
- package/lib/clinical/helpers/planTextHelper.js +9 -2
- package/lib/clinical/protocols/treatmentFormulary.js +3 -3
- package/lib/clinical/services/bridgeService.js +2 -2
- package/lib/clinical/services/checkInDueService.js +3 -2
- package/lib/clinical/services/clinicalAirtableService.js +3 -2
- package/lib/clinical/services/clinicalExtractionService.js +9 -2
- package/lib/clinical/services/contingencyDispatchService.js +8 -4
- package/lib/clinical/services/doctorPlanService.js +27 -11
- package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
- package/lib/config/awsConfig.js +1 -1
- package/lib/controllers/assistantController.js +5 -2
- package/lib/controllers/escalationReviewController.js +16 -3
- package/lib/controllers/messageController.js +5 -6
- package/lib/core/NexusMessaging.js +16 -18
- package/lib/fhir/constants/escalationCaseStatus.js +1 -1
- package/lib/helpers/caregiverHelper.js +8 -0
- package/lib/helpers/templateFlowControllerHelper.js +9 -48
- package/lib/index.d.ts +3 -3
- package/lib/models/escalationReviewModel.js +32 -2
- package/lib/services/assistantMessageService.js +11 -6
- package/lib/services/caseFollowUpService.js +226 -0
- package/lib/services/caseFollowUpSweepService.js +89 -0
- package/lib/services/characterizationOutcomeService.js +25 -9
- package/lib/services/escalationCaseStateService.js +68 -0
- package/lib/services/escalationReviewService.js +90 -27
- package/lib/services/flowDataExchangeService.js +6 -35
- package/lib/services/reviewAlertSweepService.js +19 -1
- package/lib/services/reviewBoardService.js +24 -6
- package/lib/services/reviewDeadlineService.js +1 -1
- package/lib/services/untakenAlertService.js +9 -7
- package/lib/services/watchExpiryService.js +162 -0
- package/lib/utils/textMatchUtils.js +52 -18
- package/package.json +1 -1
|
@@ -9,6 +9,7 @@ const { logger } = require('../../utils/logger');
|
|
|
9
9
|
const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
|
|
10
10
|
const { botIsPaused } = require('../../helpers/pausedThreadHelper');
|
|
11
11
|
const { setCheckInsPausedUntil, checkInsPausedUntil } = require('../../services/threadService');
|
|
12
|
+
const { caseFollowUpMoveRefusal, isCaseFollowUpId, recordCaseFollowUpMoved } = require('../../services/caseFollowUpService');
|
|
12
13
|
|
|
13
14
|
const definition = {
|
|
14
15
|
name: 'schedulePatientReminder',
|
|
@@ -152,6 +153,10 @@ async function handler(args = {}, context = {}) {
|
|
|
152
153
|
if (actionType === 'update' && targetId && runtime.patientCode && !await isReminderPending({ code: runtime.patientCode, reminderId: targetId })) {
|
|
153
154
|
return JSON.stringify({ success: false, error: 'reminder_not_active — that reminder already went out or was stood down, so it cannot be updated. If a check is still needed, create a new one.', data: { reminder_id: targetId } });
|
|
154
155
|
}
|
|
156
|
+
if (actionType === 'update' && targetId && isCaseFollowUpId(targetId) && runtime.patientCode) {
|
|
157
|
+
const refusal = await caseFollowUpMoveRefusal({ code: runtime.patientCode, reminderId: targetId, fireAt: fireMoment.toDate() });
|
|
158
|
+
if (refusal) return JSON.stringify({ success: false, error: refusal, data: { reminder_id: targetId } });
|
|
159
|
+
}
|
|
155
160
|
if (isRoutineOutreach && actionType === 'create' && runtime.patientCode) {
|
|
156
161
|
if (await botIsPaused(runtime.patientCode, { label: '[schedulePatientReminder]' })) {
|
|
157
162
|
return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
|
|
@@ -215,6 +220,7 @@ async function handler(args = {}, context = {}) {
|
|
|
215
220
|
}
|
|
216
221
|
return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
|
|
217
222
|
}
|
|
223
|
+
if (actionType === 'update' && isCaseFollowUpId(reminderId)) await recordCaseFollowUpMoved({ code: runtime.patientCode, reminderId, dueAt: fireMoment.toDate() });
|
|
218
224
|
}
|
|
219
225
|
|
|
220
226
|
trace.setSignals({ reminderIntents: [...existing, intent] });
|
|
@@ -258,7 +264,7 @@ async function pauseCheckIns(args, runtime) {
|
|
|
258
264
|
}
|
|
259
265
|
if (patientCode && !isShadowRun()) {
|
|
260
266
|
await setCheckInsPausedUntil(patientCode, until.toDate());
|
|
261
|
-
if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused' })) {
|
|
267
|
+
if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused', includeCaseFollowUp: true })) {
|
|
262
268
|
logger.warn('[schedulePatientReminder] pending seguimientos were not retired on pause', { patientCode });
|
|
263
269
|
}
|
|
264
270
|
}
|
|
@@ -274,6 +280,9 @@ async function cancelSeguimiento(args, runtime) {
|
|
|
274
280
|
}
|
|
275
281
|
const { patientCode, trace } = runtime;
|
|
276
282
|
const notPending = () => JSON.stringify({ success: false, error: 'not_pending — only a pending seguimiento listed under «Seguimientos ya programados» can be cancelled.', data: { reminder_id: reminderId } });
|
|
283
|
+
if (isCaseFollowUpId(reminderId)) {
|
|
284
|
+
return JSON.stringify({ success: false, error: 'case_follow_up — this seguimiento follows up the doctor\'s indications and ends when the case closes, not when the patient replies. If she asked to be written at another time, move it with update.', data: { reminder_id: reminderId } });
|
|
285
|
+
}
|
|
277
286
|
if (!reminderId.startsWith('followup_')) return notPending();
|
|
278
287
|
if (patientCode) {
|
|
279
288
|
const pending = await readPendingFollowUpsForPatient({ code: patientCode });
|
package/lib/config/awsConfig.js
CHANGED
|
@@ -91,7 +91,7 @@ async function generatePresignedUrl(bucketName, key, expiration = 3000) {
|
|
|
91
91
|
|
|
92
92
|
try {
|
|
93
93
|
const url = await s3.getSignedUrlPromise('getObject', params);
|
|
94
|
-
logger.info(
|
|
94
|
+
logger.info('Presigned URL generated');
|
|
95
95
|
return url;
|
|
96
96
|
} catch (error) {
|
|
97
97
|
logger.error(`Error generating presigned URL: ${error.message}`);
|
|
@@ -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
|
}
|
|
@@ -23,6 +23,8 @@ const {
|
|
|
23
23
|
syncEscalationReviewCase,
|
|
24
24
|
} = require('../services/escalationReviewService');
|
|
25
25
|
const { listReviewBoard } = require('../services/reviewBoardService');
|
|
26
|
+
const { caseStateOf } = require('../services/escalationCaseStateService');
|
|
27
|
+
const { responseDeadlinePolicy } = require('../services/reviewDeadlineService');
|
|
26
28
|
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
27
29
|
|
|
28
30
|
const respondWithError = (res, error, action, context) => {
|
|
@@ -34,6 +36,12 @@ const respondWithError = (res, error, action, context) => {
|
|
|
34
36
|
res.status(error.statusCode || 500).json({ success: false, error: error.message, ...(error.errorCode && { errorCode: error.errorCode }) });
|
|
35
37
|
};
|
|
36
38
|
|
|
39
|
+
// The review still reads when its case state cannot be worked out.
|
|
40
|
+
const safeCaseStateOf = (review) => caseStateOf(review, { policy: responseDeadlinePolicy() }).catch((error) => {
|
|
41
|
+
logger.warn('[EscalationReview] Could not read the case state', { escalationReviewId: String(review?._id), error: redactDirectIdentifiers(String(error?.message || error)) });
|
|
42
|
+
return null;
|
|
43
|
+
});
|
|
44
|
+
|
|
37
45
|
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
38
46
|
|
|
39
47
|
const openEscalationReviewController = async (req, res) => {
|
|
@@ -55,7 +63,8 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
55
63
|
const getEscalationReviewController = async (req, res) => {
|
|
56
64
|
try {
|
|
57
65
|
const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
|
|
58
|
-
|
|
66
|
+
const caseState = await safeCaseStateOf(review);
|
|
67
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers });
|
|
59
68
|
} catch (error) {
|
|
60
69
|
respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
|
|
61
70
|
}
|
|
@@ -63,7 +72,7 @@ const getEscalationReviewController = async (req, res) => {
|
|
|
63
72
|
|
|
64
73
|
const previewEscalationReviewPlanController = async (req, res) => {
|
|
65
74
|
try {
|
|
66
|
-
const instructions = previewPlanInstructions({ id: req.params.id, plan: req.body?.plan });
|
|
75
|
+
const instructions = await previewPlanInstructions({ id: req.params.id, plan: req.body?.plan });
|
|
67
76
|
res.status(200).json({ success: true, instructions });
|
|
68
77
|
} catch (error) {
|
|
69
78
|
respondWithError(res, error, 'previewing the plan instructions', { reviewId: req.params?.id });
|
|
@@ -82,7 +91,11 @@ const getReviewTimelineController = async (req, res) => {
|
|
|
82
91
|
const listEscalationReviewsController = async (req, res) => {
|
|
83
92
|
try {
|
|
84
93
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
85
|
-
|
|
94
|
+
// Only the open review gets its state, so the panel's poll stays fresh without reading the review as seen.
|
|
95
|
+
const listed = await Promise.all(reviews.map(async (review) => (review.closedAt
|
|
96
|
+
? withCaseStatus(review)
|
|
97
|
+
: { ...withCaseStatus(review), caseState: await safeCaseStateOf(review) })));
|
|
98
|
+
res.status(200).json({ success: true, reviews: listed });
|
|
86
99
|
} catch (error) {
|
|
87
100
|
respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
|
|
88
101
|
}
|
|
@@ -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
|
|
|
@@ -15,7 +15,7 @@ const CASE_STATUS_BY_REVIEW_STATUS = Object.freeze({
|
|
|
15
15
|
approved: POR_ENVIAR,
|
|
16
16
|
sending: POR_ENVIAR,
|
|
17
17
|
needs_intervention: CASE('in-progress', 'requiere-valoracion', 'Requiere valoración'),
|
|
18
|
-
indications_queued: CASE('on-hold', '
|
|
18
|
+
indications_queued: CASE('on-hold', 'indicacion-en-cola', 'Indicación en cola'),
|
|
19
19
|
indications_sent: CASE('in-progress', 'indicaciones-dadas', 'Indicaciones dadas'),
|
|
20
20
|
monitoring: CASE('in-progress', 'en-vigilancia', 'En vigilancia'),
|
|
21
21
|
closed: CASE('completed', 'cerrado', 'Cerrado'),
|
|
@@ -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,
|
|
@@ -38,21 +38,6 @@ const storeFlowConditionalRules = async (flowId, contentSid, flowFirstPageId, ru
|
|
|
38
38
|
}
|
|
39
39
|
};
|
|
40
40
|
|
|
41
|
-
const getAnyFlowConditionalRules = async () => {
|
|
42
|
-
const iter = flowConditionalRules.values().next();
|
|
43
|
-
if (!iter.done) return iter.value;
|
|
44
|
-
try {
|
|
45
|
-
const doc = await FlowRouting.findOne({}, {}, { sort: { updatedAt: -1 } }).lean();
|
|
46
|
-
if (doc) {
|
|
47
|
-
flowConditionalRules.set(doc.flowId, doc);
|
|
48
|
-
return doc;
|
|
49
|
-
}
|
|
50
|
-
} catch (err) {
|
|
51
|
-
console.warn('[FlowRouting] Failed to load latest rules', err.message);
|
|
52
|
-
}
|
|
53
|
-
return null;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
41
|
const getFlowConditionalRules = async (flowId) => {
|
|
57
42
|
if (!flowId) return null;
|
|
58
43
|
if (flowConditionalRules.has(flowId)) return flowConditionalRules.get(flowId);
|
|
@@ -68,35 +53,13 @@ const getFlowConditionalRules = async (flowId) => {
|
|
|
68
53
|
return null;
|
|
69
54
|
};
|
|
70
55
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
if (doc) {
|
|
79
|
-
flowConditionalRules.set(doc.flowId, doc);
|
|
80
|
-
return doc;
|
|
81
|
-
}
|
|
82
|
-
} catch (err) {
|
|
83
|
-
console.warn('[FlowRouting] Failed to load rules by flowToken', err.message);
|
|
84
|
-
}
|
|
85
|
-
return null;
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
const attachFlowToken = async (flowId, flowToken) => {
|
|
89
|
-
if (!flowId || !flowToken) return;
|
|
90
|
-
const cached = flowConditionalRules.get(flowId);
|
|
91
|
-
if (cached) {
|
|
92
|
-
cached.flowToken = flowToken;
|
|
93
|
-
flowConditionalRules.set(flowId, cached);
|
|
94
|
-
}
|
|
95
|
-
try {
|
|
96
|
-
await FlowRouting.findOneAndUpdate({ flowId }, { flowToken }, { new: true });
|
|
97
|
-
} catch (err) {
|
|
98
|
-
console.warn('[FlowRouting] Failed to attach flowToken', err.message);
|
|
99
|
-
}
|
|
56
|
+
// Tokens are minted as `<flowId>:<uuid>` so the answer routes back to its own flow without a lookup table.
|
|
57
|
+
const FLOW_TOKEN_SEPARATOR = ':';
|
|
58
|
+
const buildFlowToken = (flowId) => `${flowId}${FLOW_TOKEN_SEPARATOR}${uuidv4()}`;
|
|
59
|
+
const flowIdFromToken = (flowToken) => {
|
|
60
|
+
if (typeof flowToken !== 'string') return null;
|
|
61
|
+
const index = flowToken.indexOf(FLOW_TOKEN_SEPARATOR);
|
|
62
|
+
return index > 0 ? flowToken.slice(0, index) : null;
|
|
100
63
|
};
|
|
101
64
|
|
|
102
65
|
const deleteFlowConditionalRules = (contentSid) => {
|
|
@@ -152,7 +115,7 @@ const ensureFlowTokenInVariables = async (contentSid, existingVariables = null)
|
|
|
152
115
|
const flowRouting = await FlowRouting.findOne({ contentSid }).lean();
|
|
153
116
|
if (!flowRouting) return existingVariables;
|
|
154
117
|
|
|
155
|
-
const flowToken =
|
|
118
|
+
const flowToken = buildFlowToken(flowRouting.flowId);
|
|
156
119
|
logger.info('[ensureFlowTokenInVariables] Meta Flow template detected', {
|
|
157
120
|
contentSid,
|
|
158
121
|
flowId: flowRouting.flowId,
|
|
@@ -170,10 +133,8 @@ const ensureFlowTokenInVariables = async (contentSid, existingVariables = null)
|
|
|
170
133
|
|
|
171
134
|
module.exports = {
|
|
172
135
|
storeFlowConditionalRules,
|
|
173
|
-
getAnyFlowConditionalRules,
|
|
174
136
|
getFlowConditionalRules,
|
|
175
|
-
|
|
176
|
-
attachFlowToken,
|
|
137
|
+
flowIdFromToken,
|
|
177
138
|
deleteFlowConditionalRules,
|
|
178
139
|
buildFlowTemplatePayload,
|
|
179
140
|
generateUniqueFriendlyName,
|
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;
|
|
@@ -13,7 +13,8 @@ const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
|
13
13
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
14
14
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
15
15
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'plan_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
16
|
-
const PLAN_FOLLOW_UPS = ['none', 'check_in', 'vigilancia'];
|
|
16
|
+
const PLAN_FOLLOW_UPS = ['none', 'auto', 'check_in', 'vigilancia'];
|
|
17
|
+
const PLAN_DURATIONS = Object.freeze(['days', 'as_needed', 'continuous', 'unspecified']);
|
|
17
18
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
18
19
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
19
20
|
|
|
@@ -31,6 +32,7 @@ const alarmSchema = new mongoose.Schema({
|
|
|
31
32
|
clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
32
33
|
emergencyRecordId: { type: String, default: null },
|
|
33
34
|
appliedLevel: { type: String, default: null },
|
|
35
|
+
isHeldInFollowUp: { type: Boolean, default: undefined },
|
|
34
36
|
raisedAt: { type: Date, required: true },
|
|
35
37
|
}, { _id: false });
|
|
36
38
|
|
|
@@ -91,6 +93,16 @@ const quietReminderSchema = new mongoose.Schema({
|
|
|
91
93
|
delivered: { type: Boolean, default: null },
|
|
92
94
|
}, { _id: false });
|
|
93
95
|
|
|
96
|
+
const watchNoticeSchema = new mongoose.Schema({
|
|
97
|
+
until: { type: Date, required: true },
|
|
98
|
+
kind: { type: String, enum: ['reminder', 'team'], required: true },
|
|
99
|
+
sentAt: { type: Date, required: true },
|
|
100
|
+
skippedReason: { type: String, default: null },
|
|
101
|
+
// sent | queued (recovery template) | not_sent | skipped | failed (team, tried again); null while in flight.
|
|
102
|
+
outcome: { type: String, default: null },
|
|
103
|
+
status: { type: String, default: null },
|
|
104
|
+
}, { _id: false });
|
|
105
|
+
|
|
94
106
|
const blockingAskSchema = new mongoose.Schema({
|
|
95
107
|
draftAt: { type: Date, required: true },
|
|
96
108
|
question: { type: String, default: null },
|
|
@@ -199,7 +211,8 @@ const planItemSchema = new mongoose.Schema({
|
|
|
199
211
|
strength: { type: String, default: null },
|
|
200
212
|
dose: { type: String, required: true },
|
|
201
213
|
frequency: { type: String, required: true },
|
|
202
|
-
|
|
214
|
+
duration: { type: String, enum: PLAN_DURATIONS, default: 'days' },
|
|
215
|
+
days: { type: Number, default: null },
|
|
203
216
|
position: { type: String, default: null },
|
|
204
217
|
reason: { type: String, default: null },
|
|
205
218
|
formularyKey: { type: String, default: null },
|
|
@@ -285,6 +298,18 @@ const identityBlockSchema = new mongoose.Schema({
|
|
|
285
298
|
blockedBy: { type: String, required: true },
|
|
286
299
|
}, { _id: false });
|
|
287
300
|
|
|
301
|
+
const caseFollowUpSchema = new mongoose.Schema({
|
|
302
|
+
decisionNumber: { type: Number, required: true },
|
|
303
|
+
kind: { type: String, enum: ['auto', 'check_in', 'vigilancia'], required: true },
|
|
304
|
+
attempt: { type: Number, required: true },
|
|
305
|
+
reminderId: { type: String, required: true },
|
|
306
|
+
dueAt: { type: Date, required: true },
|
|
307
|
+
isWritten: { type: Boolean, default: true },
|
|
308
|
+
firstDueAt: { type: Date, required: true },
|
|
309
|
+
nextCheckAt: { type: Date, default: null },
|
|
310
|
+
unansweredAt: { type: Date, default: null },
|
|
311
|
+
}, { _id: false });
|
|
312
|
+
|
|
288
313
|
const escalationReviewSchema = new mongoose.Schema({
|
|
289
314
|
patientCode: { type: String, required: true },
|
|
290
315
|
patientCaseRecordId: { type: String, default: null },
|
|
@@ -333,6 +358,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
333
358
|
digestClaimedAt: { type: Date, default: null },
|
|
334
359
|
digestSentAt: { type: Date, default: null },
|
|
335
360
|
quietReminders: { type: [quietReminderSchema], default: [] },
|
|
361
|
+
monitoringUntil: { type: Date, default: null },
|
|
362
|
+
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
363
|
+
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
336
364
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
337
365
|
feverPromptStartedAt: { type: Date, default: null },
|
|
338
366
|
approverViewedAt: { type: Date, default: null },
|
|
@@ -385,6 +413,7 @@ escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
|
385
413
|
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
386
414
|
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
387
415
|
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
416
|
+
escalationReviewSchema.index({ 'caseFollowUp.nextCheckAt': 1 }, { partialFilterExpression: { 'caseFollowUp.nextCheckAt': { $type: 'date' } } });
|
|
388
417
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
389
418
|
|
|
390
419
|
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
@@ -416,6 +445,7 @@ module.exports = {
|
|
|
416
445
|
DOCTOR_DECISIONS,
|
|
417
446
|
HANDOFF_MODES,
|
|
418
447
|
INTERRUPTED_STATUSES,
|
|
448
|
+
PLAN_DURATIONS,
|
|
419
449
|
PLAN_FOLLOW_UPS,
|
|
420
450
|
FOLLOWUP_STATUSES,
|
|
421
451
|
RETURN_REASONS,
|
|
@@ -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),
|