@peopl-health/nexus 5.52.0-dev.7675 → 5.52.0-dev.7678
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/providers/GatewayProvider.js +2 -2
- package/lib/clinical/services/assistantService.js +1 -16
- package/lib/clinical/services/clinicalAirtableService.js +1 -3
- package/lib/clinical/services/triageRecommendationService.js +97 -18
- package/lib/config/lifecycle.js +0 -6
- package/lib/core/NexusMessaging.js +1 -5
- package/lib/helpers/patientTaskRulesHelper.js +0 -2
- package/lib/index.d.ts +1 -7
- package/lib/index.js +0 -12
- package/lib/services/patientTaskService.js +1 -3
- package/lib/services/queueReconciliationService.js +6 -19
- package/package.json +1 -1
- package/lib/clinical/config/safetyNetConfig.js +0 -62
- package/lib/clinical/services/pausedSafetyNetService.js +0 -267
- package/lib/clinical/services/safetyNetPledgeService.js +0 -100
- package/lib/core/interactiveRouteService.js +0 -58
- package/lib/models/safetyNetPledgeModel.js +0 -20
|
@@ -60,7 +60,7 @@ class GatewayProvider extends BaseLLMProvider {
|
|
|
60
60
|
sessionManager: this.sessionManager,
|
|
61
61
|
});
|
|
62
62
|
} catch (err) {
|
|
63
|
-
throw new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`);
|
|
63
|
+
throw Object.assign(new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`), { permanent: true });
|
|
64
64
|
}
|
|
65
65
|
return this._subs[vendor];
|
|
66
66
|
}
|
|
@@ -80,7 +80,7 @@ class GatewayProvider extends BaseLLMProvider {
|
|
|
80
80
|
}
|
|
81
81
|
const { vendor, model: routedModel } = this._route(model);
|
|
82
82
|
if (vendor !== 'openai' && vendor !== 'anthropic') {
|
|
83
|
-
throw new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`);
|
|
83
|
+
throw Object.assign(new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`), { permanent: true });
|
|
84
84
|
}
|
|
85
85
|
return this._sub(vendor).runStructured({ ...params, model: routedModel });
|
|
86
86
|
}
|
|
@@ -16,19 +16,9 @@ const { getMessages, countMessages } = require('../../services/messageService');
|
|
|
16
16
|
|
|
17
17
|
const { getAssistantById } = require('./assistantResolver');
|
|
18
18
|
const { recordPausedThreadMessage } = require('./clinicalAirtableService');
|
|
19
|
-
const { offerSafetyNet } = require('./pausedSafetyNetService');
|
|
20
19
|
|
|
21
20
|
const MEDIA_BACKLOG_LIMIT = 10;
|
|
22
21
|
|
|
23
|
-
const pausedAlertText = async (code, newest) => {
|
|
24
|
-
if (!newest.interactive_type) return newest.plainBody || newest.body;
|
|
25
|
-
const [written] = await getMessages(
|
|
26
|
-
{ numero: code, from_me: false, interactive_type: null, createdAt: { $lte: newest.createdAt } },
|
|
27
|
-
{ sort: { createdAt: -1 }, limit: 1 }
|
|
28
|
-
);
|
|
29
|
-
return written ? written.plainBody || written.body : null;
|
|
30
|
-
};
|
|
31
|
-
|
|
32
22
|
const fetchMediaBacklog = async (code, trigger) => {
|
|
33
23
|
const [lastOutbound] = await getMessages(
|
|
34
24
|
{ numero: code, from_me: true, createdAt: { $lt: trigger.createdAt } },
|
|
@@ -122,12 +112,7 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
|
|
|
122
112
|
return { shouldProcess: false, messages: null, timings, pendingMediaUpdates: [] };
|
|
123
113
|
}
|
|
124
114
|
|
|
125
|
-
if (thread.stopped) {
|
|
126
|
-
await Promise.allSettled([
|
|
127
|
-
recordPausedThreadMessage({ code, text: await pausedAlertText(code, lastMessage[0]) }),
|
|
128
|
-
offerSafetyNet({ code })
|
|
129
|
-
]);
|
|
130
|
-
}
|
|
115
|
+
if (thread.stopped) await recordPausedThreadMessage({ code, text: lastMessage[0].plainBody || lastMessage[0].body });
|
|
131
116
|
|
|
132
117
|
const backlog = await fetchMediaBacklog(code, lastMessage[0]);
|
|
133
118
|
const replies = [...backlog, ...lastMessage];
|
|
@@ -14,7 +14,6 @@ const recentIntakeCache = new WriteClaimStore({ namespace: 'intake', ttlMs: INTA
|
|
|
14
14
|
const EMERGENCY_MERGE_WINDOW_MS = 5 * 60 * 1000;
|
|
15
15
|
const EMERGENCY_URGENCY_RANK = { routine: 0, urgent: 1, asap: 2, stat: 3 };
|
|
16
16
|
const recentEmergencyCache = new WriteClaimStore({ namespace: 'emergency', ttlMs: EMERGENCY_MERGE_WINDOW_MS, maxSize: 500 });
|
|
17
|
-
const PAUSED_THREAD_DETAILS_PREFIX = 'Bot en pausa:';
|
|
18
17
|
const PAUSED_ALERT_WINDOW_MS = 4 * 60 * 60 * 1000;
|
|
19
18
|
const recentPausedAlertCache = new WriteClaimStore({ namespace: 'paused-alert', ttlMs: PAUSED_ALERT_WINDOW_MS, maxSize: 1000 });
|
|
20
19
|
const UNRESOLVED_WINDOW_MS = 30 * 60 * 1000;
|
|
@@ -120,7 +119,7 @@ async function recordPausedThreadMessage({ code, text }) {
|
|
|
120
119
|
code,
|
|
121
120
|
trace: null,
|
|
122
121
|
question: text || 'El paciente envió un archivo sin texto.',
|
|
123
|
-
details:
|
|
122
|
+
details: `Bot en pausa: el paciente ${code} escribió y nadie ha respondido. Revisar la conversación.`,
|
|
124
123
|
category: 'contact_team_member',
|
|
125
124
|
urgency: 'soon',
|
|
126
125
|
});
|
|
@@ -502,7 +501,6 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
|
|
|
502
501
|
}
|
|
503
502
|
|
|
504
503
|
module.exports = {
|
|
505
|
-
PAUSED_THREAD_DETAILS_PREFIX,
|
|
506
504
|
recordUnresolvedRequest,
|
|
507
505
|
recordPausedThreadMessage,
|
|
508
506
|
recordEmergency,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { Types } = require('mongoose');
|
|
1
2
|
const { getTriageGate, getTriagePlan } = require('../config/subAgentsConfig');
|
|
2
3
|
const { getSafetyFlagPatterns, getRedFlagMinRoutes } = require('../config/divergenceConfig');
|
|
3
4
|
const { requireGatewayProvider } = require('../config/llmConfig');
|
|
@@ -19,6 +20,8 @@ const {
|
|
|
19
20
|
hasActionableFindings,
|
|
20
21
|
} = require('../helpers/triageCaseBaseHelper');
|
|
21
22
|
const { buildLegacyStep1, buildLegacyStep2, buildLegacyStep3 } = require('../helpers/legacyRecommendationFormatHelper');
|
|
23
|
+
|
|
24
|
+
const runtimeConfig = require('../../config/runtimeConfig');
|
|
22
25
|
const { triageRecommendationLive } = require('../flags/triageRecommendationFlags');
|
|
23
26
|
const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
24
27
|
const { TRIAGE_RUN_PREFIX } = require('../../fhir/helpers/recommendationIds');
|
|
@@ -67,6 +70,8 @@ const { prepareSupportAction } = require('./supportActionService');
|
|
|
67
70
|
const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
|
|
68
71
|
const GATE_MAX_ATTEMPTS = 2;
|
|
69
72
|
const PLAN_MAX_ATTEMPTS = 2;
|
|
73
|
+
const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
|
|
74
|
+
const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
|
|
70
75
|
const RAW_EXCERPT_MAX = 2000;
|
|
71
76
|
const PRIOR_TRIAGE_RX = /^rec[A-Za-z0-9]{14,}$/;
|
|
72
77
|
const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_recommendations)';
|
|
@@ -147,23 +152,94 @@ function defaultRunId(payload) {
|
|
|
147
152
|
return `${TRIAGE_RUN_PREFIX}${payload.triageRecordId}`;
|
|
148
153
|
}
|
|
149
154
|
|
|
155
|
+
function sleep(ms, { keepAlive = false } = {}) {
|
|
156
|
+
return new Promise((resolve) => {
|
|
157
|
+
const t = setTimeout(resolve, ms);
|
|
158
|
+
if (!keepAlive) t.unref?.();
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isPermanentProviderError(error) {
|
|
163
|
+
if (error?.permanent === true) return true;
|
|
164
|
+
const status = Number(error?.status ?? error?.statusCode);
|
|
165
|
+
return Number.isFinite(status) && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function alreadyRetriedByProvider(error) {
|
|
169
|
+
return error?.originalError !== undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function jittered(ms) {
|
|
173
|
+
return Math.round(ms * (0.75 + (Math.random() * 0.5)));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function backoffSchedule(key, fallback) {
|
|
177
|
+
const raw = runtimeConfig.get(key);
|
|
178
|
+
if (raw == null) return fallback;
|
|
179
|
+
if (String(raw).trim() === '') return [];
|
|
180
|
+
const pieces = String(raw).split(',').map((piece) => piece.trim());
|
|
181
|
+
if (pieces.some((piece) => piece === '')) return fallback;
|
|
182
|
+
const parsed = pieces.map(Number);
|
|
183
|
+
if (!parsed.length || parsed.some((ms) => !Number.isFinite(ms) || ms < 0)) return fallback;
|
|
184
|
+
return parsed;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function newIdempotentEventId() {
|
|
188
|
+
return new Types.ObjectId();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function settleLossIsCritical(status) {
|
|
192
|
+
return status !== 'success' && status !== 'skipped' && status !== 'skipped_duplicate';
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function newTransientBudget() {
|
|
196
|
+
return { schedule: backoffSchedule('TRIAGE_PROVIDER_RETRY_BACKOFF_MS', DEFAULT_PROVIDER_RETRY_BACKOFF_MS), used: 0 };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function callProviderWithBackoff(run, { code, rid, stage, attempt, budget }) {
|
|
200
|
+
for (;;) {
|
|
201
|
+
try {
|
|
202
|
+
return await run();
|
|
203
|
+
} catch (err) {
|
|
204
|
+
const permanent = isPermanentProviderError(err) || alreadyRetriedByProvider(err);
|
|
205
|
+
const waitMs = permanent ? null : budget.schedule[budget.used];
|
|
206
|
+
logger.warn(`[triageRecommendation] ${stage} provider call failed`, {
|
|
207
|
+
code, runId: rid, attempt, transientRetriesUsed: budget.used, retryInMs: waitMs ?? null, permanent, error: err?.message,
|
|
208
|
+
});
|
|
209
|
+
if (waitMs == null) throw err;
|
|
210
|
+
budget.used += 1;
|
|
211
|
+
await sleep(jittered(waitMs));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
150
216
|
async function recordSettleEvent({ payload, trigger, totalLatencyMs, ...settle }) {
|
|
151
217
|
const event = { patientCode: payload.patientCode, triageRecordId: payload.triageRecordId, trigger };
|
|
152
218
|
if (totalLatencyMs != null) event.totalLatencyMs = totalLatencyMs;
|
|
153
219
|
for (const [key, value] of Object.entries(settle)) {
|
|
154
220
|
if (value != null) event[key] = value;
|
|
155
221
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
222
|
+
event._id = newIdempotentEventId();
|
|
223
|
+
let lastError;
|
|
224
|
+
const settleSchedule = backoffSchedule('TRIAGE_SETTLE_WRITE_BACKOFF_MS', DEFAULT_SETTLE_WRITE_BACKOFF_MS);
|
|
225
|
+
for (let tries = 0; tries <= settleSchedule.length; tries += 1) {
|
|
226
|
+
try {
|
|
227
|
+
await getTriageRecommendationEventModel().create(event);
|
|
228
|
+
return;
|
|
229
|
+
} catch (err) {
|
|
230
|
+
if (err?.code === 11000) return;
|
|
231
|
+
lastError = err;
|
|
232
|
+
const waitMs = settleSchedule[tries];
|
|
233
|
+
if (waitMs == null) break;
|
|
234
|
+
await sleep(jittered(waitMs), { keepAlive: true });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const lost = { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: event.status, reason: event.reason, error: lastError?.message };
|
|
238
|
+
if (!settleLossIsCritical(event.status)) {
|
|
239
|
+
logger.warn('[triageRecommendation] settle event write failed', lost);
|
|
240
|
+
return;
|
|
166
241
|
}
|
|
242
|
+
logger.error('[triageRecommendation] failure lost before it was recorded', lost);
|
|
167
243
|
}
|
|
168
244
|
|
|
169
245
|
async function generateTriageRecommendations({ payload, provider, runId = null, supportRouting = {} }) {
|
|
@@ -655,6 +731,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
655
731
|
let gateRepairs = [];
|
|
656
732
|
let accepted = null;
|
|
657
733
|
let priorIssues = null;
|
|
734
|
+
const budget = newTransientBudget();
|
|
658
735
|
for (let attempt = 1; attempt <= GATE_MAX_ATTEMPTS; attempt += 1) {
|
|
659
736
|
attempts = attempt;
|
|
660
737
|
const last = attempt === GATE_MAX_ATTEMPTS;
|
|
@@ -662,13 +739,12 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
662
739
|
if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues) });
|
|
663
740
|
let result;
|
|
664
741
|
try {
|
|
665
|
-
result = await provider.runStructured({
|
|
742
|
+
result = await callProviderWithBackoff(() => provider.runStructured({
|
|
666
743
|
presetId,
|
|
667
744
|
input,
|
|
668
745
|
metadata: { subAgent: 'triage-gate', runId: rid },
|
|
669
|
-
});
|
|
670
|
-
} catch
|
|
671
|
-
logger.warn('[triageRecommendation] gate provider call failed', { code, runId: rid, attempt, error: err?.message });
|
|
746
|
+
}), { code, rid, stage: 'gate', attempt, budget });
|
|
747
|
+
} catch {
|
|
672
748
|
if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_provider_failed' } };
|
|
673
749
|
continue;
|
|
674
750
|
}
|
|
@@ -772,6 +848,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
772
848
|
let rankReordered = 0;
|
|
773
849
|
let deniedCardsDropped = 0;
|
|
774
850
|
let deniedTargetsStripped = 0;
|
|
851
|
+
const budget = newTransientBudget();
|
|
775
852
|
for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
|
|
776
853
|
const content = attempt === 1 || !lastIssues.length
|
|
777
854
|
? planInput
|
|
@@ -779,13 +856,12 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
779
856
|
const last = attempt === PLAN_MAX_ATTEMPTS;
|
|
780
857
|
let result;
|
|
781
858
|
try {
|
|
782
|
-
result = await provider.runStructured({
|
|
859
|
+
result = await callProviderWithBackoff(() => provider.runStructured({
|
|
783
860
|
presetId,
|
|
784
861
|
input: [{ role: 'user', content }],
|
|
785
862
|
metadata: { subAgent: 'triage-plan', runId: rid },
|
|
786
|
-
});
|
|
787
|
-
} catch
|
|
788
|
-
logger.warn('[triageRecommendation] plan provider call failed', { code, runId: rid, attempt, error: err?.message });
|
|
863
|
+
}), { code, rid, stage: 'plan', attempt, budget });
|
|
864
|
+
} catch {
|
|
789
865
|
lastIssues = [];
|
|
790
866
|
if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } });
|
|
791
867
|
continue;
|
|
@@ -987,6 +1063,9 @@ async function recordTriageAdherence({ code, entries, patientRecordId, priorReso
|
|
|
987
1063
|
}
|
|
988
1064
|
|
|
989
1065
|
module.exports = {
|
|
1066
|
+
recordSettleEvent,
|
|
1067
|
+
backoffSchedule,
|
|
1068
|
+
settleLossIsCritical,
|
|
990
1069
|
handleTriageCompleted,
|
|
991
1070
|
generateTriageRecommendations,
|
|
992
1071
|
};
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -3,10 +3,7 @@ const { _resetMetaConfig } = require('../config/metaConfig');
|
|
|
3
3
|
const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
|
|
4
4
|
const { setPreprocessingHandler } = require('../services/preprocessingService');
|
|
5
5
|
const { clearTriageHistoryCache } = require('../services/triageHistoryService');
|
|
6
|
-
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
7
6
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
8
|
-
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
9
|
-
const { _resetSafetyNetState } = require('../clinical/services/pausedSafetyNetService');
|
|
10
7
|
const { _clearRecentIntakeCache } = require('../clinical/services/clinicalAirtableService');
|
|
11
8
|
const { _clearExtractorConfigCache } = require('../clinical/services/clinicalExtractionService');
|
|
12
9
|
const { _resetRegistry } = require('../clinical/services/assistantResolver');
|
|
@@ -17,9 +14,6 @@ function resetAll() {
|
|
|
17
14
|
_resetRegistry();
|
|
18
15
|
_resetLLMState();
|
|
19
16
|
setPreprocessingHandler(null);
|
|
20
|
-
clearInteractiveRoutes();
|
|
21
|
-
_resetSafetyNetConfig();
|
|
22
|
-
_resetSafetyNetState();
|
|
23
17
|
_resetOverrides();
|
|
24
18
|
_resetMetaConfig();
|
|
25
19
|
_clearClinicalContextCache();
|
|
@@ -30,7 +30,6 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
|
|
|
30
30
|
|
|
31
31
|
const { BatchingManager } = require('../core/BatchingManager');
|
|
32
32
|
const { ProcessingPipeline } = require('../core/ProcessingPipeline');
|
|
33
|
-
const { sweepSafetyNetPledges } = require('../clinical/services/safetyNetPledgeService');
|
|
34
33
|
const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
|
|
35
34
|
const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
|
|
36
35
|
const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
|
|
@@ -46,7 +45,6 @@ const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
|
|
|
46
45
|
const { createQueueAdapter } = require('../queue');
|
|
47
46
|
const { ScheduledMessageJob } = require('../jobs/ScheduledMessageJob');
|
|
48
47
|
const { TemplateApprovalJob } = require('../jobs/TemplateApprovalJob');
|
|
49
|
-
const { invokeInteractiveRoute } = require('./interactiveRouteService');
|
|
50
48
|
|
|
51
49
|
const { PhiProcessor } = require('./PhiProcessor');
|
|
52
50
|
|
|
@@ -171,8 +169,7 @@ class NexusMessaging {
|
|
|
171
169
|
...(config.queueReconciliation || {}),
|
|
172
170
|
scheduleMessage: (options) => this.scheduledMessageJob.schedule(options),
|
|
173
171
|
scheduleTemplateApproval: (options) => this.scheduleTemplateApproval(options),
|
|
174
|
-
sweepHeldMessages: () => sweepHeldMessages()
|
|
175
|
-
sweepSafetyNetPledges
|
|
172
|
+
sweepHeldMessages: () => sweepHeldMessages()
|
|
176
173
|
});
|
|
177
174
|
|
|
178
175
|
this._providerStores = false;
|
|
@@ -583,7 +580,6 @@ class NexusMessaging {
|
|
|
583
580
|
}
|
|
584
581
|
|
|
585
582
|
async handleInteractive(messageData) {
|
|
586
|
-
await invokeInteractiveRoute(messageData);
|
|
587
583
|
if (this.handlers.onInteractive) return await this.handlers.onInteractive(messageData, this);
|
|
588
584
|
}
|
|
589
585
|
|
|
@@ -14,7 +14,6 @@ const ATTENTION_OPERATIONS_STATUS = 'pendiente';
|
|
|
14
14
|
const ATTENTION_CASE_WINDOW_DAYS = 14;
|
|
15
15
|
const ATTENTION_CASE_WINDOW_MS = ATTENTION_CASE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
|
|
16
16
|
const URGENT_REQUEST_URGENCY = 'urgent';
|
|
17
|
-
const REQUEST_URGENCIES = ['routine', 'soon', 'urgent'];
|
|
18
17
|
const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
|
|
19
18
|
|
|
20
19
|
const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
|
|
@@ -41,7 +40,6 @@ module.exports = {
|
|
|
41
40
|
ATTENTION_CASE_WINDOW_DAYS,
|
|
42
41
|
ATTENTION_OPERATIONS_STATUS,
|
|
43
42
|
ATTENTION_REQUEST_STATUS,
|
|
44
|
-
REQUEST_URGENCIES,
|
|
45
43
|
isCaseOpen,
|
|
46
44
|
isCaseUrgent,
|
|
47
45
|
isRequestOpen,
|
package/lib/index.d.ts
CHANGED
|
@@ -22,14 +22,8 @@ declare module '@peopl-health/nexus' {
|
|
|
22
22
|
type?: 'message' | 'interactive' | 'media' | 'command' | 'keyword' | 'flow' | 'empty';
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
export function registerInteractiveRoute(
|
|
26
|
-
prefix: string,
|
|
27
|
-
handler: (tap: { code: string; payload: string | null; title: string | null; messageData: unknown }) => unknown
|
|
28
|
-
): void;
|
|
29
|
-
export function clearInteractiveRoutes(): void;
|
|
30
|
-
|
|
31
25
|
export interface InteractiveData {
|
|
32
|
-
type: 'button' | 'list' | 'flow'
|
|
26
|
+
type: 'button' | 'list' | 'flow';
|
|
33
27
|
payload?: string;
|
|
34
28
|
title?: string;
|
|
35
29
|
description?: string;
|
package/lib/index.js
CHANGED
|
@@ -26,9 +26,6 @@ const { setModelDatabases, setModelDatabase, getModelDatabase, connect: mongoCon
|
|
|
26
26
|
const { TwilioProvider } = require('./adapters/TwilioProvider');
|
|
27
27
|
const { BaileysProvider } = require('./adapters/BaileysProvider');
|
|
28
28
|
const { setPreprocessingHandler, hasPreprocessingHandler, invokePreprocessingHandler } = require('./services/preprocessingService');
|
|
29
|
-
const { registerInteractiveRoute, clearInteractiveRoutes } = require('./core/interactiveRouteService');
|
|
30
|
-
const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
|
|
31
|
-
const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
|
|
32
29
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
33
30
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
34
31
|
const { createWorkflowRunner } = require('./core/workflowRunner');
|
|
@@ -187,13 +184,6 @@ class Nexus {
|
|
|
187
184
|
logger.warn('Warning: failed to register clinical tools:', e?.message || e);
|
|
188
185
|
}
|
|
189
186
|
|
|
190
|
-
try {
|
|
191
|
-
configureSafetyNet(options.safetyNet || {});
|
|
192
|
-
if (registerSafetyNetRoutes()) logger.info('[Nexus] paused-thread safety net armed');
|
|
193
|
-
} catch (e) {
|
|
194
|
-
logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
187
|
await this.messaging.initializeLlmMonitor();
|
|
198
188
|
|
|
199
189
|
this.isInitialized = true;
|
|
@@ -290,8 +280,6 @@ module.exports = {
|
|
|
290
280
|
setPreprocessingHandler,
|
|
291
281
|
hasPreprocessingHandler,
|
|
292
282
|
invokePreprocessingHandler,
|
|
293
|
-
registerInteractiveRoute,
|
|
294
|
-
clearInteractiveRoutes,
|
|
295
283
|
routes,
|
|
296
284
|
syncClinicalContext,
|
|
297
285
|
runProactiveOutreachSweep,
|
|
@@ -4,7 +4,6 @@ const { httpError } = require('../utils/httpErrorUtils');
|
|
|
4
4
|
|
|
5
5
|
const { escapeFormulaValue, fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
6
6
|
const {
|
|
7
|
-
REQUEST_URGENCIES,
|
|
8
7
|
isCaseOpen,
|
|
9
8
|
isCaseUrgent,
|
|
10
9
|
isRequestOpen,
|
|
@@ -110,7 +109,6 @@ const TASK_KINDS = {
|
|
|
110
109
|
toTask: toRequest,
|
|
111
110
|
writable: {
|
|
112
111
|
status: { field: 'status', options: REQUEST_STATUSES },
|
|
113
|
-
urgency: { field: 'urgency', options: REQUEST_URGENCIES },
|
|
114
112
|
note: { field: 'Observaciones' },
|
|
115
113
|
},
|
|
116
114
|
},
|
|
@@ -172,7 +170,7 @@ async function getPatientTasks(code) {
|
|
|
172
170
|
requests: requests.attentionCount,
|
|
173
171
|
isUrgent: requests.isUrgent || cases.isUrgent,
|
|
174
172
|
},
|
|
175
|
-
options: { requestStatus: REQUEST_STATUSES,
|
|
173
|
+
options: { requestStatus: REQUEST_STATUSES, caseStatus: CASE_STATUSES, operationsStatus: OPERATIONS_STATUSES },
|
|
176
174
|
};
|
|
177
175
|
}
|
|
178
176
|
|
|
@@ -13,7 +13,6 @@ class QueueReconciliationService {
|
|
|
13
13
|
scheduleMessage,
|
|
14
14
|
scheduleTemplateApproval,
|
|
15
15
|
sweepHeldMessages,
|
|
16
|
-
sweepSafetyNetPledges,
|
|
17
16
|
intervalMs = DEFAULT_INTERVAL_MS,
|
|
18
17
|
lookbackMs = DEFAULT_LOOKBACK_MS,
|
|
19
18
|
staleAfterMs = DEFAULT_STALE_AFTER_MS,
|
|
@@ -22,7 +21,6 @@ class QueueReconciliationService {
|
|
|
22
21
|
this.scheduleMessage = scheduleMessage;
|
|
23
22
|
this.scheduleTemplateApproval = scheduleTemplateApproval;
|
|
24
23
|
this.sweepHeldMessages = sweepHeldMessages;
|
|
25
|
-
this.sweepSafetyNetPledges = sweepSafetyNetPledges;
|
|
26
24
|
this.intervalMs = intervalMs;
|
|
27
25
|
this.lookbackMs = lookbackMs;
|
|
28
26
|
this.staleAfterMs = staleAfterMs;
|
|
@@ -62,20 +60,19 @@ class QueueReconciliationService {
|
|
|
62
60
|
}
|
|
63
61
|
|
|
64
62
|
async runOnce() {
|
|
65
|
-
if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0
|
|
63
|
+
if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0 };
|
|
66
64
|
const since = new Date(Date.now() - this.lookbackMs);
|
|
67
|
-
const [scheduledMessages, recoveries, heldMessages
|
|
65
|
+
const [scheduledMessages, recoveries, heldMessages] = await Promise.all([
|
|
68
66
|
this._reEnqueueScheduledMessages(since),
|
|
69
67
|
this._reArmTemplateApprovals(since),
|
|
70
|
-
this._releaseHeldMessages()
|
|
71
|
-
this._resolveSafetyNetPledges()
|
|
68
|
+
this._releaseHeldMessages()
|
|
72
69
|
]);
|
|
73
70
|
|
|
74
|
-
if (scheduledMessages || recoveries || heldMessages
|
|
75
|
-
logger.warn('[QueueReconciliation] Re-armed dropped jobs', { scheduledMessages, recoveries, heldMessages
|
|
71
|
+
if (scheduledMessages || recoveries || heldMessages) {
|
|
72
|
+
logger.warn('[QueueReconciliation] Re-armed dropped jobs', { scheduledMessages, recoveries, heldMessages });
|
|
76
73
|
}
|
|
77
74
|
|
|
78
|
-
return { scheduledMessages, recoveries, heldMessages
|
|
75
|
+
return { scheduledMessages, recoveries, heldMessages };
|
|
79
76
|
}
|
|
80
77
|
|
|
81
78
|
async _releaseHeldMessages() {
|
|
@@ -88,16 +85,6 @@ class QueueReconciliationService {
|
|
|
88
85
|
}
|
|
89
86
|
}
|
|
90
87
|
|
|
91
|
-
async _resolveSafetyNetPledges() {
|
|
92
|
-
if (typeof this.sweepSafetyNetPledges !== 'function') return 0;
|
|
93
|
-
try {
|
|
94
|
-
return await this.sweepSafetyNetPledges();
|
|
95
|
-
} catch (error) {
|
|
96
|
-
logger.error('[QueueReconciliation] Safety-net pledge sweep failed', { error: error.message });
|
|
97
|
-
return 0;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
88
|
async _reEnqueueScheduledMessages(since) {
|
|
102
89
|
if (typeof this.scheduleMessage !== 'function') return 0;
|
|
103
90
|
|
package/package.json
CHANGED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
const runtimeConfig = require('../../config/runtimeConfig');
|
|
2
|
-
|
|
3
|
-
const DEFAULT_OFFER_WINDOW_MS = 4 * 60 * 60 * 1000;
|
|
4
|
-
const DEFAULT_HUMAN_QUIET_MS = 60 * 60 * 1000;
|
|
5
|
-
const DEFAULT_TAP_WINDOW_MS = 30 * 60 * 1000;
|
|
6
|
-
const DEFAULT_PLEDGE_MS = 30 * 60 * 1000;
|
|
7
|
-
|
|
8
|
-
const CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
|
|
9
|
-
|
|
10
|
-
const SAFETY_NET_SOURCE = 'paused_safety_net';
|
|
11
|
-
|
|
12
|
-
const humanReplyFilter = (code, since) => ({
|
|
13
|
-
numero: code,
|
|
14
|
-
from_me: true,
|
|
15
|
-
content_sid: null,
|
|
16
|
-
origin: { $ne: 'assistant' },
|
|
17
|
-
triggeredBy: { $ne: SAFETY_NET_SOURCE },
|
|
18
|
-
createdAt: { $gt: since }
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
const CHOICE_LABEL_KEYS = {
|
|
22
|
-
urgent: 'PAUSED_SAFETY_NET_URGENT_LABEL',
|
|
23
|
-
callback: 'PAUSED_SAFETY_NET_CALLBACK_LABEL',
|
|
24
|
-
later: 'PAUSED_SAFETY_NET_LATER_LABEL'
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
let injected = {};
|
|
28
|
-
|
|
29
|
-
const configureSafetyNet = (config = {}) => {
|
|
30
|
-
injected = config && typeof config === 'object' ? config : {};
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
const _resetSafetyNetConfig = () => {
|
|
34
|
-
injected = {};
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
const text = (key, envKey) => {
|
|
38
|
-
const raw = injected[key] ?? runtimeConfig.get(envKey);
|
|
39
|
-
const value = String(raw ?? '').trim();
|
|
40
|
-
return value || null;
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const duration = (key, envKey, fallback) => {
|
|
44
|
-
const raw = Number(injected[key] ?? runtimeConfig.get(envKey));
|
|
45
|
-
return Number.isFinite(raw) && raw > 0 ? raw : fallback;
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
module.exports = {
|
|
49
|
-
CONTACT_WINDOW,
|
|
50
|
-
SAFETY_NET_SOURCE,
|
|
51
|
-
humanReplyFilter,
|
|
52
|
-
CHOICE_LABEL_KEYS,
|
|
53
|
-
configureSafetyNet,
|
|
54
|
-
_resetSafetyNetConfig,
|
|
55
|
-
getSafetyNetContentSid: () => text('contentSid', 'PAUSED_SAFETY_NET_CONTENT_SID'),
|
|
56
|
-
getSafetyNetPhone: () => text('phone', 'PAUSED_SAFETY_NET_PHONE'),
|
|
57
|
-
getSafetyNetLabel: (choice) => text(`${choice}Label`, CHOICE_LABEL_KEYS[choice]),
|
|
58
|
-
getOfferWindowMs: () => duration('offerWindowMs', 'PAUSED_SAFETY_NET_WINDOW_MS', DEFAULT_OFFER_WINDOW_MS),
|
|
59
|
-
getHumanQuietMs: () => duration('humanQuietMs', 'SAFETY_NET_HUMAN_QUIET_MS', DEFAULT_HUMAN_QUIET_MS),
|
|
60
|
-
getTapWindowMs: () => duration('tapWindowMs', 'SAFETY_NET_TAP_WINDOW_MS', DEFAULT_TAP_WINDOW_MS),
|
|
61
|
-
getPledgeMs: () => duration('pledgeMs', 'SAFETY_NET_PLEDGE_MS', DEFAULT_PLEDGE_MS)
|
|
62
|
-
};
|
|
@@ -1,267 +0,0 @@
|
|
|
1
|
-
const {
|
|
2
|
-
CONTACT_WINDOW,
|
|
3
|
-
SAFETY_NET_SOURCE,
|
|
4
|
-
getHumanQuietMs,
|
|
5
|
-
getOfferWindowMs,
|
|
6
|
-
getPledgeMs,
|
|
7
|
-
getSafetyNetContentSid,
|
|
8
|
-
getSafetyNetLabel,
|
|
9
|
-
getSafetyNetPhone,
|
|
10
|
-
getTapWindowMs
|
|
11
|
-
} = require('../config/safetyNetConfig');
|
|
12
|
-
const { logger } = require('../../utils/logger');
|
|
13
|
-
|
|
14
|
-
const { acquireSendClaim, completeSendClaim } = require('../../helpers/sendClaimHelper');
|
|
15
|
-
|
|
16
|
-
const { registerInteractiveRoute } = require('../../core/interactiveRouteService');
|
|
17
|
-
const { getPatientTasks, updatePatientTask } = require('../../services/patientTaskService');
|
|
18
|
-
|
|
19
|
-
const { WriteClaimStore } = require('./writeClaimStore');
|
|
20
|
-
const { PAUSED_THREAD_DETAILS_PREFIX, recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
21
|
-
const { humanRepliedSince, openPledge } = require('./safetyNetPledgeService');
|
|
22
|
-
|
|
23
|
-
const getMessaging = () => require('../../core/NexusMessaging');
|
|
24
|
-
|
|
25
|
-
const SOURCE = SAFETY_NET_SOURCE;
|
|
26
|
-
const PAYLOAD_PREFIX = 'peopl_safetynet_';
|
|
27
|
-
const CHOICES = ['urgent', 'callback', 'later'];
|
|
28
|
-
const REQUEST_CATEGORY = 'contact_team_member';
|
|
29
|
-
const CAN_WAIT_NOTE = 'El paciente indicó que su solicitud puede esperar.';
|
|
30
|
-
const ATTENDED_STATUS = 'sin atender';
|
|
31
|
-
|
|
32
|
-
const REQUEST_COPY = {
|
|
33
|
-
urgent: {
|
|
34
|
-
question: 'El paciente indicó que su situación es urgente',
|
|
35
|
-
details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y eligió "urgencia". Se le dio el número para llamar. Revisar la conversación ahora.`
|
|
36
|
-
},
|
|
37
|
-
callback: {
|
|
38
|
-
question: 'El paciente pidió que el equipo lo contacte hoy',
|
|
39
|
-
details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y pidió que lo contacten. Se le prometió contacto; revisar la conversación.`
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
let offerClaimStore = null;
|
|
44
|
-
let tapClaimStore = null;
|
|
45
|
-
let phoneCheckedFor = null;
|
|
46
|
-
|
|
47
|
-
const normalize = (value) => String(value ?? '').trim().toLowerCase();
|
|
48
|
-
|
|
49
|
-
const offerClaims = () => {
|
|
50
|
-
if (!offerClaimStore) offerClaimStore = new WriteClaimStore({ namespace: 'paused-safety-net', ttlMs: getOfferWindowMs() });
|
|
51
|
-
return offerClaimStore;
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
const tapClaims = () => {
|
|
55
|
-
if (!tapClaimStore) tapClaimStore = new WriteClaimStore({ namespace: 'safety-net-choice', ttlMs: getTapWindowMs() });
|
|
56
|
-
return tapClaimStore;
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
const _resetSafetyNetState = () => {
|
|
60
|
-
offerClaimStore = null;
|
|
61
|
-
tapClaimStore = null;
|
|
62
|
-
phoneCheckedFor = null;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
function matchSafetyNetChoice(payload, title) {
|
|
66
|
-
const candidate = normalize(payload);
|
|
67
|
-
if (candidate.startsWith(PAYLOAD_PREFIX)) {
|
|
68
|
-
const suffix = candidate.slice(PAYLOAD_PREFIX.length);
|
|
69
|
-
return CHOICES.find((choice) => choice === suffix) || null;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const label = normalize(title) || candidate;
|
|
73
|
-
if (!label) return null;
|
|
74
|
-
return CHOICES.find((choice) => {
|
|
75
|
-
const configured = normalize(getSafetyNetLabel(choice));
|
|
76
|
-
return configured && configured === label;
|
|
77
|
-
}) || null;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async function warnIfPhoneDiffersFromTemplate(contentSid) {
|
|
81
|
-
const phone = getSafetyNetPhone();
|
|
82
|
-
if (!phone || phoneCheckedFor === contentSid) return;
|
|
83
|
-
phoneCheckedFor = contentSid;
|
|
84
|
-
try {
|
|
85
|
-
const body = await getMessaging().requireProvider().renderTemplate(contentSid);
|
|
86
|
-
const digits = (value) => String(value ?? '').replace(/\D/g, '');
|
|
87
|
-
if (body && !digits(body).includes(digits(phone))) {
|
|
88
|
-
logger.error('[PausedSafetyNet] The configured phone number is absent from the template body', { contentSid });
|
|
89
|
-
}
|
|
90
|
-
} catch (error) {
|
|
91
|
-
phoneCheckedFor = null;
|
|
92
|
-
logger.warn('[PausedSafetyNet] Could not read the template to check the phone number', { contentSid, error: error.message });
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
async function offerSafetyNet({ code }) {
|
|
97
|
-
try {
|
|
98
|
-
const contentSid = getSafetyNetContentSid();
|
|
99
|
-
if (!code || !contentSid) return { sent: false, reason: 'not_configured' };
|
|
100
|
-
if (await offerClaims().get(code)) return { sent: false, reason: 'recent_offer' };
|
|
101
|
-
if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
|
|
102
|
-
|
|
103
|
-
await warnIfPhoneDiffersFromTemplate(contentSid);
|
|
104
|
-
|
|
105
|
-
const result = await getMessaging().sendMessage({ code, contentSid, triggeredBy: SOURCE });
|
|
106
|
-
const sent = result?.success === true || result?.completed === true;
|
|
107
|
-
if (!sent) return { sent: false, reason: result?.status || 'send_failed' };
|
|
108
|
-
|
|
109
|
-
await offerClaims().set(code, true);
|
|
110
|
-
return { sent: true, reason: null };
|
|
111
|
-
} catch (error) {
|
|
112
|
-
logger.error('[PausedSafetyNet] Could not offer the safety net', { code, error: error.message });
|
|
113
|
-
return { sent: false, reason: 'error' };
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async function fileUrgentRequest(code, choice) {
|
|
118
|
-
const copy = REQUEST_COPY[choice];
|
|
119
|
-
return recordUnresolvedRequest({
|
|
120
|
-
code,
|
|
121
|
-
trace: null,
|
|
122
|
-
question: copy.question,
|
|
123
|
-
details: copy.details(code),
|
|
124
|
-
category: REQUEST_CATEGORY,
|
|
125
|
-
urgency: 'urgent'
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
async function markCanWait(code) {
|
|
130
|
-
const { requests = [] } = await getPatientTasks(code);
|
|
131
|
-
const target = requests.find((request) => request.status === ATTENDED_STATUS
|
|
132
|
-
&& request.category === REQUEST_CATEGORY
|
|
133
|
-
&& String(request.details || '').startsWith(PAUSED_THREAD_DETAILS_PREFIX));
|
|
134
|
-
if (!target) return true;
|
|
135
|
-
|
|
136
|
-
await updatePatientTask({
|
|
137
|
-
code,
|
|
138
|
-
kind: 'requests',
|
|
139
|
-
recordId: target.recordId,
|
|
140
|
-
changes: {
|
|
141
|
-
urgency: 'routine',
|
|
142
|
-
note: [target.note, CAN_WAIT_NOTE].filter(Boolean).join('\n')
|
|
143
|
-
},
|
|
144
|
-
updatedBy: SOURCE,
|
|
145
|
-
source: SOURCE
|
|
146
|
-
});
|
|
147
|
-
return true;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
async function applyChoice(code, choice) {
|
|
151
|
-
if (choice === 'later') return { queued: await markCanWait(code), pledge: null };
|
|
152
|
-
|
|
153
|
-
const queued = await fileUrgentRequest(code, choice);
|
|
154
|
-
if (choice !== 'callback') return { queued, pledge: null };
|
|
155
|
-
if (!queued) return { queued, pledge: null };
|
|
156
|
-
|
|
157
|
-
try {
|
|
158
|
-
return { queued, pledge: await openPledge({ code }) };
|
|
159
|
-
} catch (error) {
|
|
160
|
-
logger.error('[PausedSafetyNet] The request was filed but no pledge was opened', { code, error: error.message });
|
|
161
|
-
return { queued, pledge: null };
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
const withPhone = (text, closing) => {
|
|
166
|
-
const phone = getSafetyNetPhone();
|
|
167
|
-
return phone ? `${text} ${closing.replace('{phone}', phone)}` : text;
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
function ackFor(choice, outcome) {
|
|
171
|
-
if (outcome.stale) {
|
|
172
|
-
return withPhone('Recibimos tu respuesta y el equipo va a revisar tu conversación.', 'Si necesitas ayuda ahora, llámanos al {phone}.');
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
if (!outcome.queued) {
|
|
176
|
-
return withPhone('No pudimos registrar tu solicitud.', 'Por favor llámanos al {phone} para que te atendamos.');
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
if (choice === 'urgent') {
|
|
180
|
-
return withPhone('Entendido, ya avisamos al equipo.', 'Si es una urgencia médica, llámanos ahora al {phone}.');
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
if (choice === 'later') {
|
|
184
|
-
return withPhone('Gracias, lo anotamos. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.');
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
if (!outcome.pledge) {
|
|
188
|
-
return withPhone('Listo, ya avisamos al equipo y te van a contactar.', 'Si te sientes peor antes, llámanos al {phone}.');
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
if (outcome.pledge.deferredToWindow) {
|
|
192
|
-
return withPhone(
|
|
193
|
-
`Listo, ya avisamos al equipo. Te van a contactar en cuanto abran, a partir de las ${CONTACT_WINDOW.startHour}:00.`,
|
|
194
|
-
'Si es una urgencia médica, llámanos ahora al {phone}.'
|
|
195
|
-
);
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
const minutes = Math.round(getPledgeMs() / 60000);
|
|
199
|
-
return withPhone(
|
|
200
|
-
`Listo. Un miembro del equipo te va a contactar en los próximos ${minutes} minutos.`,
|
|
201
|
-
'Si te sientes peor antes, llámanos al {phone}.'
|
|
202
|
-
);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async function sendAck(code, choice, outcome) {
|
|
206
|
-
try {
|
|
207
|
-
await getMessaging().sendMessage({ code, body: ackFor(choice, outcome), triggeredBy: SOURCE });
|
|
208
|
-
} catch (error) {
|
|
209
|
-
logger.error('[PausedSafetyNet] Could not acknowledge the tap', { code, choice, error: error.message });
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
async function handleSafetyNetTap({ code, payload, title }) {
|
|
214
|
-
const choice = matchSafetyNetChoice(payload, title);
|
|
215
|
-
if (!choice || !code) return { handled: false };
|
|
216
|
-
|
|
217
|
-
const claim = await acquireSendClaim({ idempotencyKey: `safetynet:${code}:${choice}` });
|
|
218
|
-
if (!claim.acquired) return { handled: true, choice, reason: 'concurrent_tap' };
|
|
219
|
-
|
|
220
|
-
try {
|
|
221
|
-
if (!await offerClaims().get(code)) {
|
|
222
|
-
await sendAck(code, choice, { queued: true, pledge: null, repeated: false, stale: true });
|
|
223
|
-
return { handled: true, choice, queued: false, stale: true };
|
|
224
|
-
}
|
|
225
|
-
await offerClaims().set(code, true);
|
|
226
|
-
|
|
227
|
-
const tapKey = `${code}:${choice}`;
|
|
228
|
-
const repeated = Boolean(await tapClaims().get(tapKey));
|
|
229
|
-
|
|
230
|
-
let outcome = { queued: true, pledge: null, repeated };
|
|
231
|
-
if (!repeated) {
|
|
232
|
-
try {
|
|
233
|
-
outcome = { ...await applyChoice(code, choice), repeated: false };
|
|
234
|
-
await tapClaims().set(tapKey, true);
|
|
235
|
-
} catch (error) {
|
|
236
|
-
logger.error('[PausedSafetyNet] Could not record the tap', { code, choice, error: error.message });
|
|
237
|
-
outcome = { queued: false, pledge: null, repeated: false };
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
await sendAck(code, choice, outcome);
|
|
242
|
-
return { handled: true, choice, ...outcome };
|
|
243
|
-
} finally {
|
|
244
|
-
await completeSendClaim(claim.claimId);
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
function registerSafetyNetRoutes() {
|
|
249
|
-
if (!getSafetyNetContentSid()) return false;
|
|
250
|
-
|
|
251
|
-
registerInteractiveRoute(PAYLOAD_PREFIX, handleSafetyNetTap);
|
|
252
|
-
for (const choice of CHOICES) {
|
|
253
|
-
const label = getSafetyNetLabel(choice);
|
|
254
|
-
if (label) registerInteractiveRoute(label, handleSafetyNetTap);
|
|
255
|
-
}
|
|
256
|
-
return true;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
module.exports = {
|
|
260
|
-
offerSafetyNet,
|
|
261
|
-
handleSafetyNetTap,
|
|
262
|
-
matchSafetyNetChoice,
|
|
263
|
-
registerSafetyNetRoutes,
|
|
264
|
-
_resetSafetyNetState,
|
|
265
|
-
PAYLOAD_PREFIX,
|
|
266
|
-
CHOICES
|
|
267
|
-
};
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
const { CONTACT_WINDOW, getPledgeMs, humanReplyFilter } = require('../config/safetyNetConfig');
|
|
2
|
-
const { logger } = require('../../utils/logger');
|
|
3
|
-
const { clampToHourWindow } = require('../../utils/scheduleUtils');
|
|
4
|
-
|
|
5
|
-
const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
|
|
6
|
-
|
|
7
|
-
const { getMessages } = require('../../services/messageService');
|
|
8
|
-
|
|
9
|
-
const { recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
10
|
-
|
|
11
|
-
const SWEEP_LIMIT = 200;
|
|
12
|
-
const BREACH_CATEGORY = 'contact_team_member';
|
|
13
|
-
const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
|
|
14
|
-
|
|
15
|
-
async function humanRepliedSince(code, since) {
|
|
16
|
-
const [reply] = await getMessages(humanReplyFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
|
|
17
|
-
return Boolean(reply);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function pledgeDueAt(pledgedAt) {
|
|
21
|
-
const target = new Date(pledgedAt.getTime() + getPledgeMs());
|
|
22
|
-
const opened = clampToHourWindow(target, CONTACT_WINDOW);
|
|
23
|
-
if (!opened) return { dueAt: target, deferredToWindow: false };
|
|
24
|
-
return { dueAt: opened, deferredToWindow: opened.getTime() > target.getTime() };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
async function openPledge({ code }) {
|
|
28
|
-
const pledgedAt = new Date();
|
|
29
|
-
const { dueAt, deferredToWindow } = pledgeDueAt(pledgedAt);
|
|
30
|
-
const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt, deferredToWindow });
|
|
31
|
-
logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt, deferredToWindow });
|
|
32
|
-
return { pledgeId: pledge._id, dueAt, deferredToWindow };
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async function reportBreach(pledge) {
|
|
36
|
-
const waitedMinutes = Math.round((Date.now() - new Date(pledge.pledgedAt).getTime()) / 60000);
|
|
37
|
-
return recordUnresolvedRequest({
|
|
38
|
-
code: pledge.code,
|
|
39
|
-
trace: null,
|
|
40
|
-
question: BREACH_QUESTION,
|
|
41
|
-
details: `El paciente ${pledge.code} pidió que lo contactaran y lleva ${waitedMinutes} minutos sin respuesta. Revisar la conversación ahora.`,
|
|
42
|
-
category: BREACH_CATEGORY,
|
|
43
|
-
urgency: 'urgent'
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const REPORT_LEASE_MS = 5 * 60 * 1000;
|
|
48
|
-
|
|
49
|
-
const settle = async (id, from, state) => Boolean(
|
|
50
|
-
await SafetyNetPledge.findOneAndUpdate({ _id: id, state: from }, { $set: { state, resolvedAt: new Date() } }).lean()
|
|
51
|
-
);
|
|
52
|
-
|
|
53
|
-
const takeReportingLease = async (id) => Boolean(
|
|
54
|
-
await SafetyNetPledge.findOneAndUpdate(
|
|
55
|
-
{ _id: id, $or: [{ state: 'pending' }, { state: 'reporting', reportingSince: { $lt: new Date(Date.now() - REPORT_LEASE_MS) } }] },
|
|
56
|
-
{ $set: { state: 'reporting', reportingSince: new Date() } },
|
|
57
|
-
).lean()
|
|
58
|
-
);
|
|
59
|
-
|
|
60
|
-
async function sweepSafetyNetPledges() {
|
|
61
|
-
const due = await SafetyNetPledge.find({
|
|
62
|
-
state: { $in: ['pending', 'reporting'] },
|
|
63
|
-
dueAt: { $lte: new Date() },
|
|
64
|
-
})
|
|
65
|
-
.select({ _id: 1, code: 1, pledgedAt: 1 })
|
|
66
|
-
.limit(SWEEP_LIMIT)
|
|
67
|
-
.lean();
|
|
68
|
-
|
|
69
|
-
let breached = 0;
|
|
70
|
-
|
|
71
|
-
for (const pledge of due) {
|
|
72
|
-
try {
|
|
73
|
-
if (!await takeReportingLease(pledge._id)) continue;
|
|
74
|
-
|
|
75
|
-
if (await humanRepliedSince(pledge.code, pledge.pledgedAt)) {
|
|
76
|
-
await settle(pledge._id, 'reporting', 'met');
|
|
77
|
-
continue;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
if (!await reportBreach(pledge)) {
|
|
81
|
-
await SafetyNetPledge.updateOne({ _id: pledge._id, state: 'reporting' }, { $set: { state: 'pending', reportingSince: null } });
|
|
82
|
-
logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
|
|
83
|
-
continue;
|
|
84
|
-
}
|
|
85
|
-
if (await settle(pledge._id, 'reporting', 'breached')) breached += 1;
|
|
86
|
-
} catch (error) {
|
|
87
|
-
logger.error('[SafetyNetPledge] Could not resolve a pledge', { code: pledge.code, error: error.message });
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
return breached;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
module.exports = {
|
|
95
|
-
humanRepliedSince,
|
|
96
|
-
openPledge,
|
|
97
|
-
pledgeDueAt,
|
|
98
|
-
sweepSafetyNetPledges,
|
|
99
|
-
BREACH_QUESTION
|
|
100
|
-
};
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
const { logger } = require('../utils/logger');
|
|
2
|
-
|
|
3
|
-
const routes = new Map();
|
|
4
|
-
|
|
5
|
-
const normalizePayload = (value) => String(value ?? '').trim().toLowerCase();
|
|
6
|
-
|
|
7
|
-
function registerInteractiveRoute(prefix, handler) {
|
|
8
|
-
const key = normalizePayload(prefix);
|
|
9
|
-
if (!key) throw new Error('registerInteractiveRoute requires a payload prefix');
|
|
10
|
-
if (typeof handler !== 'function') throw new Error('registerInteractiveRoute requires a handler function');
|
|
11
|
-
routes.set(key, handler);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function clearInteractiveRoutes() {
|
|
15
|
-
routes.clear();
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function hasInteractiveRoutes() {
|
|
19
|
-
return routes.size > 0;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function resolveInteractiveRoute(payload) {
|
|
23
|
-
const candidate = normalizePayload(payload);
|
|
24
|
-
if (!candidate) return null;
|
|
25
|
-
for (const [prefix, handler] of routes) {
|
|
26
|
-
if (candidate.startsWith(prefix)) return handler;
|
|
27
|
-
}
|
|
28
|
-
return null;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
async function invokeInteractiveRoute(messageData) {
|
|
32
|
-
if (!routes.size) return false;
|
|
33
|
-
|
|
34
|
-
const interactive = messageData?.interactive || {};
|
|
35
|
-
const handler = resolveInteractiveRoute(interactive.payload);
|
|
36
|
-
if (!handler) return false;
|
|
37
|
-
|
|
38
|
-
try {
|
|
39
|
-
await handler({
|
|
40
|
-
code: messageData.code,
|
|
41
|
-
payload: interactive.payload ?? null,
|
|
42
|
-
title: interactive.title ?? null,
|
|
43
|
-
messageData
|
|
44
|
-
});
|
|
45
|
-
return true;
|
|
46
|
-
} catch (error) {
|
|
47
|
-
logger.error('[InteractiveRoutes] Route handler failed', { error: error?.message || error });
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
module.exports = {
|
|
53
|
-
registerInteractiveRoute,
|
|
54
|
-
clearInteractiveRoutes,
|
|
55
|
-
hasInteractiveRoutes,
|
|
56
|
-
resolveInteractiveRoute,
|
|
57
|
-
invokeInteractiveRoute
|
|
58
|
-
};
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
const mongoose = require('mongoose');
|
|
2
|
-
|
|
3
|
-
const PLEDGE_STATES = ['pending', 'reporting', 'met', 'breached'];
|
|
4
|
-
|
|
5
|
-
const safetyNetPledgeSchema = new mongoose.Schema({
|
|
6
|
-
code: { type: String, required: true },
|
|
7
|
-
pledgedAt: { type: Date, required: true },
|
|
8
|
-
dueAt: { type: Date, required: true },
|
|
9
|
-
deferredToWindow: { type: Boolean, default: false },
|
|
10
|
-
state: { type: String, enum: PLEDGE_STATES, default: 'pending' },
|
|
11
|
-
reportingSince: { type: Date, default: null },
|
|
12
|
-
resolvedAt: { type: Date, default: null },
|
|
13
|
-
createdAt: { type: Date, default: Date.now }
|
|
14
|
-
});
|
|
15
|
-
|
|
16
|
-
safetyNetPledgeSchema.index({ state: 1, dueAt: 1 }, { name: 'safety_net_pledge_due_idx' });
|
|
17
|
-
|
|
18
|
-
const SafetyNetPledge = mongoose.model('SafetyNetPledge', safetyNetPledgeSchema);
|
|
19
|
-
|
|
20
|
-
module.exports = { SafetyNetPledge, PLEDGE_STATES };
|