@peopl-health/nexus 5.56.4 → 5.56.6
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/flags/turnEfficiencyFlags.js +14 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +65 -18
- package/lib/clinical/providers/AnthropicProvider.js +18 -0
- package/lib/clinical/providers/BaseLLMProvider.js +13 -2
- package/lib/clinical/services/supportCandidateService.js +54 -9
- package/lib/clinical/tools/extractClinicalInfoTool.js +31 -12
- package/lib/clinical/tools/submitRoutingDecisionTool.js +6 -11
- package/lib/index.d.ts +3 -1
- package/lib/models/escalationReviewModel.js +2 -1
- package/lib/services/escalationReviewService.js +110 -11
- package/lib/services/threadService.js +5 -5
- package/package.json +1 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const runtimeConfig = require('../../config/runtimeConfig');
|
|
2
|
+
|
|
3
|
+
function isConversationalDeclarationLive() {
|
|
4
|
+
return runtimeConfig.get('CONVERSATIONAL_DECLARATION_ENABLED', 'true') === 'true';
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function isConversationalDraftReuseLive() {
|
|
8
|
+
return runtimeConfig.get('CONVERSATIONAL_DRAFT_REUSE_ENABLED', 'true') === 'true';
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
module.exports = {
|
|
12
|
+
isConversationalDeclarationLive,
|
|
13
|
+
isConversationalDraftReuseLive,
|
|
14
|
+
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { isConversationalDeclarationLive } = require('../flags/turnEfficiencyFlags');
|
|
2
|
+
|
|
1
3
|
const REFUSAL = {
|
|
2
4
|
intakeBeforeDelivery: 'clinical_intake_required_before_delivery',
|
|
3
5
|
riskBeforeDelivery: 'risk_assessment_required_before_delivery',
|
|
@@ -43,7 +45,9 @@ function hasAlternateTerminalCommit(trace) {
|
|
|
43
45
|
);
|
|
44
46
|
}
|
|
45
47
|
|
|
46
|
-
|
|
48
|
+
const RISK_TOOL_IDS = ['getRouterContextBundle', 'getPatientRiskAssessment'];
|
|
49
|
+
|
|
50
|
+
function routingSkillStep(trace, { enabledSkills = [], skillActivationIteration = null, currentIteration = null } = {}) {
|
|
47
51
|
if (!clinicalIntakeRequiresRisk(trace)) return null;
|
|
48
52
|
if (!(enabledSkills || []).includes(ROUTING_SKILL)) return null;
|
|
49
53
|
if (!(trace?.signals?.offeredToolIds || []).includes(SKILL_TOOL)) return null;
|
|
@@ -54,12 +58,59 @@ function validateRoutingSkill(trace, { enabledSkills = [], skillActivationIterat
|
|
|
54
58
|
const consumed = activatedAt != null && currentIteration != null && activatedAt < currentIteration;
|
|
55
59
|
if (consumed) return null;
|
|
56
60
|
|
|
61
|
+
return {
|
|
62
|
+
instruction: activatedAt != null
|
|
63
|
+
? `read the ${ROUTING_SKILL} body returned to you (it was requested in this same response, so its content did not reach you)`
|
|
64
|
+
: `call Skill with skill="${ROUTING_SKILL}" and read what it returns`,
|
|
65
|
+
toolIds: [SKILL_TOOL],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function pendingRoutingSteps(trace, options = {}, { decisionRequired = false } = {}) {
|
|
70
|
+
if (!clinicalIntakeRequiresRisk(trace)) return [];
|
|
71
|
+
const steps = [];
|
|
72
|
+
const routed = trace?.signals?.branchTaken === 'ai_agent';
|
|
73
|
+
const skill = decisionRequired && routed ? null : routingSkillStep(trace, options);
|
|
74
|
+
if (skill) steps.push({ key: 'routing_skill', ...skill });
|
|
75
|
+
if (!hasUsableRiskContext(trace)) {
|
|
76
|
+
steps.push({
|
|
77
|
+
key: 'risk',
|
|
78
|
+
instruction: 'call getRouterContextBundle (if its risk section failed, call getPatientRiskAssessment)',
|
|
79
|
+
toolIds: RISK_TOOL_IDS,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (decisionRequired && !routed) {
|
|
83
|
+
steps.push({
|
|
84
|
+
key: 'routing_decision',
|
|
85
|
+
instruction: 'call submitRoutingDecision with the plan the routing body defines',
|
|
86
|
+
toolIds: ['submitRoutingDecision'],
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return steps;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function describeSteps(steps, then) {
|
|
93
|
+
const list = steps.map((step, index) => `(${index + 1}) ${step.instruction}`).join('; ');
|
|
94
|
+
return `Still missing, in this order: ${list}. Then ${then}.`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function validateRoutingSkill(trace, options = {}) {
|
|
98
|
+
const skill = routingSkillStep(trace, options);
|
|
99
|
+
if (!skill) return null;
|
|
57
100
|
return {
|
|
58
101
|
error: REFUSAL.routingSkillBeforeRouting,
|
|
59
|
-
recovery:
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
102
|
+
recovery: describeSteps([skill], 'retry submitRoutingDecision with the plan it defines'),
|
|
103
|
+
requiredToolIds: skill.toolIds,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function validateRoutingPrerequisites(trace, options = {}) {
|
|
108
|
+
const steps = pendingRoutingSteps(trace, options);
|
|
109
|
+
if (!steps.length) return null;
|
|
110
|
+
return {
|
|
111
|
+
error: steps[0].key === 'routing_skill' ? REFUSAL.routingSkillBeforeRouting : REFUSAL.riskBeforeRouting,
|
|
112
|
+
recovery: describeSteps(steps, 'retry submitRoutingDecision'),
|
|
113
|
+
requiredToolIds: steps[0].toolIds,
|
|
63
114
|
};
|
|
64
115
|
}
|
|
65
116
|
|
|
@@ -72,28 +123,23 @@ function validateClinicalDelivery(trace, { enabledSkills = [], skillActivationIt
|
|
|
72
123
|
if (signals.clinicalIntakeCompleted !== true) {
|
|
73
124
|
return {
|
|
74
125
|
error: REFUSAL.intakeBeforeDelivery,
|
|
75
|
-
recovery:
|
|
126
|
+
recovery: `Classify the complete patient message: call extractClinicalInfo with every supported tag it carries, or declare its non_clinical_request when it carries no clinical content${isConversationalDeclarationLive() ? ' (`conversational` for small talk) and, in that same response, call DeliverPatientMessage again after the declaration' : ''}, or commit the workflow matching the clinical event it names. Do not file an administrative escalation for a turn that carries no pending request, or for a request you answer yourself.`,
|
|
76
127
|
requiredToolIds: [
|
|
77
128
|
'extractClinicalInfo', 'reportResultsReceived', 'reportCrisis',
|
|
78
129
|
'reportMedicalEscalation',
|
|
79
130
|
],
|
|
80
131
|
};
|
|
81
132
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
error: REFUSAL.riskBeforeDelivery,
|
|
86
|
-
recovery: 'Call getRouterContextBundle. If its risk section failed, call getPatientRiskAssessment.',
|
|
87
|
-
requiredToolIds: ['getRouterContextBundle', 'getPatientRiskAssessment'],
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
if (signals.branchTaken !== 'ai_agent') {
|
|
133
|
+
const options = { enabledSkills, skillActivationIteration, currentIteration };
|
|
134
|
+
const steps = pendingRoutingSteps(trace, options, { decisionRequired: true });
|
|
135
|
+
if (steps.length) {
|
|
91
136
|
return {
|
|
92
|
-
error: REFUSAL.routingBeforeDelivery,
|
|
93
|
-
recovery:
|
|
94
|
-
requiredToolIds: [
|
|
137
|
+
error: hasUsableRiskContext(trace) ? REFUSAL.routingBeforeDelivery : REFUSAL.riskBeforeDelivery,
|
|
138
|
+
recovery: describeSteps(steps, 'regenerate the patient message from the committed plan'),
|
|
139
|
+
requiredToolIds: steps[0].toolIds,
|
|
95
140
|
};
|
|
96
141
|
}
|
|
142
|
+
if (!clinicalIntakeRequiresRisk(trace)) return null;
|
|
97
143
|
const downstream = signals.downstreamSkill;
|
|
98
144
|
if (!downstream) return null;
|
|
99
145
|
if (!(enabledSkills || []).includes(downstream)) return null;
|
|
@@ -123,5 +169,6 @@ module.exports = {
|
|
|
123
169
|
hasUsableRiskContext,
|
|
124
170
|
isPurelyConversational,
|
|
125
171
|
validateClinicalDelivery,
|
|
172
|
+
validateRoutingPrerequisites,
|
|
126
173
|
validateRoutingSkill,
|
|
127
174
|
};
|
|
@@ -4,6 +4,7 @@ const { OPERATOR_TURN_PREFIX } = require('../memory/DefaultMemoryManager');
|
|
|
4
4
|
const { ROUTING_SKILL } = require('../helpers/clinicalWorkflowGuard');
|
|
5
5
|
const { appendCall } = require('../services/llmAuditService');
|
|
6
6
|
const { composePrompt } = require('../services/promptComposerService');
|
|
7
|
+
const { isConversationalDraftReuseLive } = require('../flags/turnEfficiencyFlags');
|
|
7
8
|
const { retryWithBackoff } = require('../../utils/retryUtils');
|
|
8
9
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
9
10
|
const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
|
|
@@ -216,6 +217,7 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
216
217
|
const nudgeGateOpen = canDecide || canDeliver;
|
|
217
218
|
|
|
218
219
|
let toolRounds = 0;
|
|
220
|
+
let previousRoundTools = [];
|
|
219
221
|
let deliveryNudges = 0;
|
|
220
222
|
let shouldBreakForDelivery = false;
|
|
221
223
|
let shouldBreakForUnavailableRecovery = false;
|
|
@@ -237,6 +239,7 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
237
239
|
const lastUserTurn = currentMessages[currentMessages.length - 1];
|
|
238
240
|
if (lastUserTurn?.role === 'user') {
|
|
239
241
|
deliveryNudges++;
|
|
242
|
+
previousRoundTools = [];
|
|
240
243
|
trace?.setSignals?.({ deliveryNudges });
|
|
241
244
|
logger.warn('[AnthropicProvider] Turn will not close — nudging', { tool: canDecide ? OUTREACH_DECISION_TOOL : 'DeliverPatientMessage', deliveryNudges, hasEnded, isBudgetSpent });
|
|
242
245
|
const turnContent = Array.isArray(lastUserTurn.content)
|
|
@@ -277,6 +280,21 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
277
280
|
{ role: 'user', content: userContent }
|
|
278
281
|
);
|
|
279
282
|
allToolsExecuted.push(...toolsExecuted);
|
|
283
|
+
const draft = !isOutreach && isConversationalDraftReuseLive() && !isSuperseded(shouldContinue)
|
|
284
|
+
? this._conversationalDraftToReuse(toolsExecuted, previousRoundTools)
|
|
285
|
+
: null;
|
|
286
|
+
previousRoundTools = toolsExecuted;
|
|
287
|
+
if (draft) {
|
|
288
|
+
const reuseCall = { name: draft.tool_name, arguments: JSON.stringify(draft.tool_arguments ?? {}), call_id: `${draft.call_id}:reuse` };
|
|
289
|
+
allToolCalls.push({ name: reuseCall.name, arguments: draft.tool_arguments ?? {}, call_id: reuseCall.call_id });
|
|
290
|
+
const { toolsExecuted: reused } = await executeTools([reuseCall], assistant, phiProcessor, producingIteration);
|
|
291
|
+
allToolsExecuted.push(...reused);
|
|
292
|
+
if (this._deliveryCommitted(reused)) {
|
|
293
|
+
trace?.setSignals?.({ conversationalDraftReused: true });
|
|
294
|
+
shouldBreakForDelivery = true;
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
280
298
|
if (toolsExecuted.some(t => this._endsClinicalReasoning(t?.tool_name, assistant?.toolRuntimeContext) && this._toolSucceeded(t))) hasSeenTerminalCommit = true;
|
|
281
299
|
if (terminalOnly && (isOutreach
|
|
282
300
|
? this._outreachCommitted(allToolsExecuted, assistant?.toolRuntimeContext?.outreachReminderType)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { DefaultMemoryManager } = require('../memory/DefaultMemoryManager');
|
|
2
|
-
const { isPurelyConversational } = require('../helpers/clinicalWorkflowGuard');
|
|
2
|
+
const { REFUSAL, isPurelyConversational } = require('../helpers/clinicalWorkflowGuard');
|
|
3
3
|
const { isToolFailure, toolRecoveryContract } = require('../helpers/toolResultHelper');
|
|
4
4
|
const { buildDateAnchor } = require('../helpers/dateAnchorHelper');
|
|
5
5
|
const { getConversationalTokens } = require('../services/clinicalExtractionService');
|
|
@@ -15,7 +15,7 @@ const { TAIL_PLACEMENT, CURRENT_TURN } = require('../promptPlacement');
|
|
|
15
15
|
const { logger } = require('../../utils/logger');
|
|
16
16
|
const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
|
|
17
17
|
const { isJsonBlob } = require('../../utils/formatUtils');
|
|
18
|
-
const { isPlainObject } = require('../../utils/jsonUtils');
|
|
18
|
+
const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
|
|
19
19
|
const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
|
|
20
20
|
|
|
21
21
|
const CONSUMER_SIGNALS_KEY = 'consumer';
|
|
@@ -43,6 +43,7 @@ const CONTINGENCY_RULE = [
|
|
|
43
43
|
const TERMINAL_DELIVERY_TOOLS = new Set(['DeliverPatientMessage']);
|
|
44
44
|
const BRIDGE_TOOL = 'SendBridgeMessage';
|
|
45
45
|
const EXTRACTION_TOOL = 'extractClinicalInfo';
|
|
46
|
+
const CONVERSATIONAL_REQUEST = 'conversational';
|
|
46
47
|
const DELIVERY_NUDGE = 'sistema: el turno no puede cerrar sin un mensaje para el paciente. Llama ahora a DeliverPatientMessage con message_text en español. No repitas herramientas clínicas ya ejecutadas en este turno.';
|
|
47
48
|
const MAX_DELIVERY_NUDGES = 2;
|
|
48
49
|
const OUTREACH_DECISION_TOOL = 'submitOutreachDecision';
|
|
@@ -695,6 +696,16 @@ class BaseLLMProvider {
|
|
|
695
696
|
return (toolsExecuted || []).some(t => TERMINAL_DELIVERY_TOOLS.has(t?.tool_name) && this._toolSucceeded(t));
|
|
696
697
|
}
|
|
697
698
|
|
|
699
|
+
_conversationalDraftToReuse(roundTools, previousRoundTools) {
|
|
700
|
+
if ((roundTools || []).length !== 1) return null;
|
|
701
|
+
const [intake] = roundTools;
|
|
702
|
+
if (intake?.tool_name !== EXTRACTION_TOOL || !this._toolSucceeded(intake)) return null;
|
|
703
|
+
if (safeParse(intake.tool_output)?.data?.non_clinical_request !== CONVERSATIONAL_REQUEST) return null;
|
|
704
|
+
const refused = (previousRoundTools || []).filter(t => TERMINAL_DELIVERY_TOOLS.has(t?.tool_name)).at(-1);
|
|
705
|
+
if (!refused || safeParse(refused.tool_output)?.error !== REFUSAL.intakeBeforeDelivery) return null;
|
|
706
|
+
return refused;
|
|
707
|
+
}
|
|
708
|
+
|
|
698
709
|
_outreachCommitted(toolsExecuted, reminderType = 'seguimiento') {
|
|
699
710
|
const successful = (toolsExecuted || []).filter(t => t?.tool_name === OUTREACH_DECISION_TOOL && this._toolSucceeded(t));
|
|
700
711
|
const args = successful.at(-1)?.tool_arguments || {};
|
|
@@ -520,8 +520,8 @@ async function clearCandidateEscalation(candidateId, {
|
|
|
520
520
|
// specialist can see who was already invited and not invite them twice.
|
|
521
521
|
const INVITABLE_ENGAGEMENT = { 'engagement.state': { $in: ['notInvited', 'invited', 'registered', 'attended'] } };
|
|
522
522
|
|
|
523
|
-
|
|
524
|
-
|
|
523
|
+
function dashboardFilter() {
|
|
524
|
+
return {
|
|
525
525
|
service: { $in: ['nutrition', 'psychology'] },
|
|
526
526
|
$or: [
|
|
527
527
|
...GROUP_INVITABLE.map((clause) => ({ ...INVITABLE_ENGAGEMENT, ...clause })),
|
|
@@ -531,19 +531,64 @@ async function readSupportDashboardCandidates() {
|
|
|
531
531
|
{ operationalReviewOverflow: true },
|
|
532
532
|
{ invitationAttempts: { $elemMatch: { status: { $in: ['failed', 'unknown'] } } } },
|
|
533
533
|
],
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const DASHBOARD_READ_LIMIT = 2000;
|
|
538
|
+
|
|
539
|
+
// No `evidence`: reasonCodes carry the "why", so the patient's own wording stays in the store.
|
|
540
|
+
const DASHBOARD_FIELDS = Object.freeze([
|
|
541
|
+
'candidateId', 'patientId', 'service', 'disposition', 'groupEligible', 'nutritionRisk',
|
|
542
|
+
'psychologyRisk', 'confidence', 'priority', 'engagement.state', 'engagement.lastInvitedAt',
|
|
543
|
+
'engagement.cooldownUntil', 'activeInvitationKey', 'escalation', 'operationalReviews',
|
|
544
|
+
'operationalReviewOverflow', 'reasonCodes', 'createdAt', 'lastEvaluatedAt',
|
|
545
|
+
'invitationAttempts.invitationCycle', 'invitationAttempts.status', 'invitationAttempts.createdAt',
|
|
546
|
+
]);
|
|
547
|
+
|
|
548
|
+
const DASHBOARD_PROJECTION = Object.freeze({
|
|
549
|
+
_id: 0,
|
|
550
|
+
...Object.fromEntries(DASHBOARD_FIELDS.map((field) => [field, 1])),
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
const DASHBOARD_RANK = {
|
|
554
|
+
$switch: {
|
|
555
|
+
branches: [
|
|
556
|
+
{ case: { $eq: ['$disposition', 'escalated'] }, then: 0 },
|
|
557
|
+
{ case: { $eq: ['$disposition', 'reviewRequired'] }, then: 1 },
|
|
558
|
+
{ case: { $gt: [{ $size: { $ifNull: ['$operationalReviews', []] } }, 0] }, then: 2 },
|
|
559
|
+
{ case: { $eq: ['$operationalReviewOverflow', true] }, then: 2 },
|
|
560
|
+
],
|
|
561
|
+
default: 3,
|
|
562
|
+
},
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
const boundedLimit = (limit) => {
|
|
566
|
+
const requested = Number.isInteger(limit) && limit > 0 ? limit : DASHBOARD_READ_LIMIT;
|
|
567
|
+
return Math.min(requested, DASHBOARD_READ_LIMIT);
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
async function readSupportDashboardCandidates({ limit = DASHBOARD_READ_LIMIT } = {}) {
|
|
571
|
+
return getSupportCandidateModel().aggregate([
|
|
572
|
+
{ $match: dashboardFilter() },
|
|
573
|
+
{ $project: { ...DASHBOARD_PROJECTION, dashboardRank: DASHBOARD_RANK } },
|
|
574
|
+
{ $sort: { dashboardRank: 1, lastEvaluatedAt: -1, candidateId: 1 } },
|
|
575
|
+
{ $limit: boundedLimit(limit) },
|
|
576
|
+
{ $unset: 'dashboardRank' },
|
|
577
|
+
]).option({ maxTimeMS: 10000, allowDiskUse: true });
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async function readSupportDashboardCandidate(candidateId) {
|
|
581
|
+
if (!candidateId) return null;
|
|
582
|
+
return getSupportCandidateModel().findOne({ ...dashboardFilter(), candidateId })
|
|
583
|
+
.select(DASHBOARD_PROJECTION).maxTimeMS(10000).lean();
|
|
541
584
|
}
|
|
542
585
|
|
|
543
586
|
module.exports = {
|
|
544
587
|
recordSentInvitationResponse,
|
|
545
588
|
updateSupportOperationalReview,
|
|
546
589
|
readSupportDashboardCandidates,
|
|
590
|
+
readSupportDashboardCandidate,
|
|
591
|
+
DASHBOARD_READ_LIMIT,
|
|
547
592
|
approveCandidate,
|
|
548
593
|
candidatePatch,
|
|
549
594
|
claimInvitation,
|
|
@@ -6,6 +6,7 @@ const { projectClinicalFacts, renderClinicalIntakeSummary } = require('../helper
|
|
|
6
6
|
const { extractClinicalMentions, getConversationalTokens } = require('../services/clinicalExtractionService');
|
|
7
7
|
const { recordClinicalIntake } = require('../services/clinicalAirtableService');
|
|
8
8
|
const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
|
|
9
|
+
const { isConversationalDeclarationLive } = require('../flags/turnEfficiencyFlags');
|
|
9
10
|
const { logger } = require('../../utils/logger');
|
|
10
11
|
|
|
11
12
|
const DETECTED_TAG_ENUM = [
|
|
@@ -13,6 +14,27 @@ const DETECTED_TAG_ENUM = [
|
|
|
13
14
|
'emotion', 'lab_value', 'diagnosis', 'allergy', 'comorbidity', 'performance_status',
|
|
14
15
|
];
|
|
15
16
|
const NON_CLINICAL_REQUESTS = ['external_booking'];
|
|
17
|
+
const CONVERSATIONAL_REQUEST = 'conversational';
|
|
18
|
+
|
|
19
|
+
function declarableRequests() {
|
|
20
|
+
return isConversationalDeclarationLive() ? [...NON_CLINICAL_REQUESTS, CONVERSATIONAL_REQUEST] : NON_CLINICAL_REQUESTS;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function nonClinicalRequestSchema() {
|
|
24
|
+
const conversational = isConversationalDeclarationLive();
|
|
25
|
+
return {
|
|
26
|
+
anyOf: [{ type: 'string', enum: declarableRequests() }, { type: 'null' }],
|
|
27
|
+
description: [
|
|
28
|
+
'Declara que el mensaje NO trae contenido clínico y que lo contestas tú directamente, sin el equipo.',
|
|
29
|
+
'- external_booking: agendar, reprogramar o cancelar una cita con un médico, una sesión de tratamiento (quimio, radio, infusión) o un estudio de laboratorio o imagen.',
|
|
30
|
+
...(conversational ? ['- conversational: el mensaje es solo conversación (saludo, agradecimiento, acuse, despedida) y no pide nada. Se contesta con un cierre breve, sin routing.'] : []),
|
|
31
|
+
'Va con `detected_tags` vacío. Si el mensaje también menciona un síntoma, emoción, medicamento, tratamiento o resultado, etiqueta esas variables y manda `null` aquí.',
|
|
32
|
+
'Manda `null` cuando la petición necesita que el equipo actúe (p. ej. una sesión del programa de acompañamiento de AUNA) y cuando el paciente solo cuenta que tiene una cita.',
|
|
33
|
+
'Con este campo, `bridge_text` va en `null`: la respuesta es un solo mensaje.',
|
|
34
|
+
].join('\n'),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
16
38
|
const MAX_CONTEXT_TURNS = 6;
|
|
17
39
|
|
|
18
40
|
const definition = {
|
|
@@ -37,7 +59,7 @@ const definition = {
|
|
|
37
59
|
'- adherence: toma/omisión/ajuste de una indicación o medicación.',
|
|
38
60
|
'- medication: medicación no-oncológica o adyuvante. Etiqueta aunque solo la vaya a empezar, la tome ahora, o la haya tomado antes (el backend distingue planeada/actual/pasada y solo la actual entra a la lista de medicación vigente).',
|
|
39
61
|
'- appointment: cita o estudio confirmado/atendido/cancelado.',
|
|
40
|
-
'- emotion: estado emocional
|
|
62
|
+
'- emotion: estado emocional del paciente que el equipo de cuidado seguiría o atendería (ansiedad, tristeza, miedo, etc.). Una fórmula de cortesía no expresa un estado emocional.',
|
|
41
63
|
'- lab_value: valor NUMÉRICO de laboratorio que el paciente comparte en el texto (ej: hemoglobina 9.2). Para solo mencionar que recibió resultados sin valores, usa reportResultsReceived.',
|
|
42
64
|
'- diagnosis: diagnóstico nuevo, confirmado, descartado, en progresión o remisión.',
|
|
43
65
|
'- allergy: alergia o reacción adversa a una sustancia.',
|
|
@@ -87,15 +109,8 @@ const definition = {
|
|
|
87
109
|
anyOf: [{ type: 'string' }, { type: 'null' }],
|
|
88
110
|
description: 'Una frase: en qué detalle del inbound anclaste `bridge_text` y por qué ese detalle. INTERNO; el paciente nunca lo ve. null cuando `bridge_text` es null.',
|
|
89
111
|
},
|
|
90
|
-
non_clinical_request
|
|
91
|
-
|
|
92
|
-
description: [
|
|
93
|
-
'Declara que el mensaje NO trae contenido clínico y solo pide algo que tú contestas directamente, sin el equipo.',
|
|
94
|
-
'- external_booking: agendar, reprogramar o cancelar una cita con un médico, una sesión de tratamiento (quimio, radio, infusión) o un estudio de laboratorio o imagen.',
|
|
95
|
-
'Va con `detected_tags` vacío. Si el mensaje también menciona un síntoma, emoción, medicamento, tratamiento o resultado, etiqueta esas variables y manda `null` aquí.',
|
|
96
|
-
'Manda `null` cuando la petición necesita que el equipo actúe (p. ej. una sesión del programa de acompañamiento de AUNA) y cuando el paciente solo cuenta que tiene una cita.',
|
|
97
|
-
'Con este campo, `bridge_text` va en `null`: la respuesta es un solo mensaje.',
|
|
98
|
-
].join('\n'),
|
|
112
|
+
get non_clinical_request() {
|
|
113
|
+
return nonClinicalRequestSchema();
|
|
99
114
|
},
|
|
100
115
|
},
|
|
101
116
|
required: ['raw_message', 'detected_tags', 'intake_source', 'response_format', 'context', 'bridge_text', 'bridge_reasoning', 'non_clinical_request'],
|
|
@@ -105,6 +120,10 @@ const definition = {
|
|
|
105
120
|
|
|
106
121
|
const SUPPORTED_TAGS = new Set(DETECTED_TAG_ENUM);
|
|
107
122
|
|
|
123
|
+
function isDeclarable(request) {
|
|
124
|
+
return declarableRequests().includes(request);
|
|
125
|
+
}
|
|
126
|
+
|
|
108
127
|
async function handler(args, context = {}) {
|
|
109
128
|
const runtime = context?.toolRuntimeContext || null;
|
|
110
129
|
const trace = runtime?.trace || null;
|
|
@@ -127,7 +146,7 @@ async function handler(args, context = {}) {
|
|
|
127
146
|
|
|
128
147
|
if (!detectedTags.length) {
|
|
129
148
|
const supported = [...SUPPORTED_TAGS].sort();
|
|
130
|
-
const declaredRequest = !detectedTagsRaw.length &&
|
|
149
|
+
const declaredRequest = !detectedTagsRaw.length && isDeclarable(args?.non_clinical_request) ? args.non_clinical_request : null;
|
|
131
150
|
if (declaredRequest && trace?.signals?.clinicalFactsExtracted) {
|
|
132
151
|
return JSON.stringify({ success: false, error: 'This turn already extracted clinical facts, so it cannot be declared a non-clinical request. Continue the clinical workflow those facts require.' });
|
|
133
152
|
}
|
|
@@ -162,7 +181,7 @@ async function handler(args, context = {}) {
|
|
|
162
181
|
}
|
|
163
182
|
const emptyTagsError = declaredRequest
|
|
164
183
|
? `The message matched a safety pattern or the safety scan was unavailable, so it cannot be declared a non-clinical request. Re-call with every applicable supported tag (${supported.join(', ')}).`
|
|
165
|
-
: `extractClinicalInfo was called with an empty \`detected_tags\` list and
|
|
184
|
+
: `extractClinicalInfo was called with an empty \`detected_tags\` list and no \`non_clinical_request\`. The intake decision is incomplete, so direct delivery remains blocked. Re-call with every applicable supported tag (${supported.join(', ')}). If the message carries no clinical content, re-call with empty tags and the \`non_clinical_request\` value that describes it${isConversationalDeclarationLive() ? ' (`conversational` for small talk)' : ''}. If it carries no clinical content but needs the team to act on a request, commit that workflow instead.`;
|
|
166
185
|
const error = !detectedTagsRaw.length
|
|
167
186
|
? emptyTagsError
|
|
168
187
|
: `extractClinicalInfo received detected_tags=${JSON.stringify(detectedTagsRaw)} but none are supported. Use only these exact strings (lowercase): ${supported.join(', ')}. Re-call with the corrected tags.`;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const crypto = require('node:crypto');
|
|
2
2
|
|
|
3
|
-
const {
|
|
3
|
+
const { validateRoutingPrerequisites } = require('../helpers/clinicalWorkflowGuard');
|
|
4
4
|
const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
|
|
5
5
|
const { storeRoutingDecision, readRoutingDecisions, readSymptomCases } = require('../../fhir');
|
|
6
6
|
const { RoutingDecision } = require('../../shared/dtos/RoutingDecision');
|
|
@@ -370,20 +370,15 @@ async function handler(args = {}, context = {}) {
|
|
|
370
370
|
const turnPlan = args?.turn_plan;
|
|
371
371
|
if (!trace || typeof trace !== 'object' || Array.isArray(trace)) return fail('trace is required (non-empty object)');
|
|
372
372
|
if (!turnPlan || typeof turnPlan !== 'object' || Array.isArray(turnPlan)) return fail('turn_plan is required (non-empty object)');
|
|
373
|
-
const
|
|
373
|
+
const prerequisite = validateRoutingPrerequisites(runtime.trace, {
|
|
374
374
|
enabledSkills: runtime.enabledSkills,
|
|
375
375
|
skillActivationIteration: runtime.skillActivationIteration,
|
|
376
376
|
currentIteration: runtime.currentIteration,
|
|
377
377
|
});
|
|
378
|
-
if (
|
|
379
|
-
return fail(
|
|
380
|
-
recovery:
|
|
381
|
-
required_tool_ids:
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
if (clinicalIntakeRequiresRisk(runtime.trace) && !hasUsableRiskContext(runtime.trace)) {
|
|
385
|
-
return fail(REFUSAL.riskBeforeRouting, {
|
|
386
|
-
recovery: 'Call getRouterContextBundle. If sections_returned lacks risk, call getPatientRiskAssessment; then retry submitRoutingDecision.',
|
|
378
|
+
if (prerequisite) {
|
|
379
|
+
return fail(prerequisite.error, {
|
|
380
|
+
recovery: prerequisite.recovery,
|
|
381
|
+
required_tool_ids: prerequisite.requiredToolIds,
|
|
387
382
|
});
|
|
388
383
|
}
|
|
389
384
|
|
package/lib/index.d.ts
CHANGED
|
@@ -835,7 +835,9 @@ declare module '@peopl-health/nexus' {
|
|
|
835
835
|
noClinicalDecision?: boolean;
|
|
836
836
|
now?: Date;
|
|
837
837
|
}, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
|
|
838
|
-
readSupportDashboardCandidates(): Promise<SupportDashboardCandidateRecord[]>;
|
|
838
|
+
readSupportDashboardCandidates(options?: { limit?: number }): Promise<SupportDashboardCandidateRecord[]>;
|
|
839
|
+
readSupportDashboardCandidate(candidateId: string): Promise<SupportDashboardCandidateRecord | null>;
|
|
840
|
+
DASHBOARD_READ_LIMIT: number;
|
|
839
841
|
approveCandidate(candidateId: string, options: {
|
|
840
842
|
reviewedRevision: number;
|
|
841
843
|
reviewedRisk: 'green' | 'yellow';
|
|
@@ -7,7 +7,7 @@ const { logger } = require('../utils/logger');
|
|
|
7
7
|
const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
|
|
8
8
|
const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
9
9
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
10
|
-
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned'];
|
|
10
|
+
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
11
11
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
12
12
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
|
|
13
13
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
|
|
@@ -91,6 +91,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
91
91
|
default: 'open',
|
|
92
92
|
},
|
|
93
93
|
openedBy: { type: String, required: true },
|
|
94
|
+
assistantPausedByReview: { type: Boolean, default: false },
|
|
94
95
|
callLogs: { type: [callLogSchema], default: [] },
|
|
95
96
|
drafts: { type: [draftSchema], default: [] },
|
|
96
97
|
doctorHandoffs: { type: [doctorHandoffSchema], default: [] },
|
|
@@ -22,6 +22,7 @@ const { generateEscalationDraft } = require('../clinical/services/escalationDraf
|
|
|
22
22
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
23
23
|
const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
|
|
24
24
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
25
|
+
const { switchThreadStoppedStatus } = require('./threadService');
|
|
25
26
|
|
|
26
27
|
const AUDIT_SOURCE = 'escalation_review';
|
|
27
28
|
const RECENT_REVIEW_LIMIT = 20;
|
|
@@ -30,6 +31,7 @@ const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
|
30
31
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
31
32
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
32
33
|
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_intervention'];
|
|
34
|
+
const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
|
|
33
35
|
const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
|
|
34
36
|
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
35
37
|
const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
|
|
@@ -86,6 +88,43 @@ const audit = (review, updatedBy, requestId, changes) => logPatientChange({
|
|
|
86
88
|
changes: { escalationReviewId: String(review._id), ...changes },
|
|
87
89
|
});
|
|
88
90
|
|
|
91
|
+
async function pauseAssistantFor(patientCode) {
|
|
92
|
+
try {
|
|
93
|
+
const result = await switchThreadStoppedStatus(patientCode, true, { byOperator: true });
|
|
94
|
+
return Boolean(result?.modifiedCount);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
logger.error('[EscalationReview] The assistant could not be paused for this patient', { error: error.message });
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const passPauseToOpenReview = (review) => getEscalationReview().findOneAndUpdate(
|
|
102
|
+
{ patientCode: review.patientCode, closedAt: null, _id: { $ne: review._id } },
|
|
103
|
+
{ $set: { assistantPausedByReview: true } },
|
|
104
|
+
).lean();
|
|
105
|
+
|
|
106
|
+
async function resumeAssistant(review, operator = null, requestId = null) {
|
|
107
|
+
if (review.assistantPausedByReview !== true) return review;
|
|
108
|
+
const stopClaiming = () => getEscalationReview()
|
|
109
|
+
.updateOne({ _id: review._id }, { $set: { assistantPausedByReview: false } });
|
|
110
|
+
try {
|
|
111
|
+
if (!await passPauseToOpenReview(review)) {
|
|
112
|
+
await switchThreadStoppedStatus(review.patientCode, false);
|
|
113
|
+
if (await passPauseToOpenReview(review)) {
|
|
114
|
+
await switchThreadStoppedStatus(review.patientCode, true, { byOperator: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
await stopClaiming();
|
|
118
|
+
return { ...review, assistantPausedByReview: false };
|
|
119
|
+
} catch (error) {
|
|
120
|
+
logger.error('[EscalationReview] The assistant could not be resumed after this review', {
|
|
121
|
+
escalationReviewId: String(review._id), error: error.message,
|
|
122
|
+
});
|
|
123
|
+
await audit(review, operator ?? review.closedBy ?? 'system', requestId, { action: 'assistant_resume_failed' });
|
|
124
|
+
return review;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
89
128
|
const withCaseMirror = (review, update, changes) => {
|
|
90
129
|
const recordIds = caseIdsOf(review);
|
|
91
130
|
if (!recordIds.length) return update;
|
|
@@ -352,19 +391,49 @@ async function openEscalationReview({
|
|
|
352
391
|
if (!patient) throw httpError(404, 'Patient not found');
|
|
353
392
|
|
|
354
393
|
const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
|
|
355
|
-
const
|
|
394
|
+
const pausedHere = await pauseAssistantFor(patientCode);
|
|
395
|
+
const fields = {
|
|
396
|
+
patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: pausedHere,
|
|
397
|
+
};
|
|
356
398
|
|
|
357
399
|
const EscalationReview = getEscalationReview();
|
|
358
|
-
await ensureActiveReviewIndex(EscalationReview);
|
|
359
400
|
let review;
|
|
360
401
|
try {
|
|
402
|
+
await ensureActiveReviewIndex(EscalationReview);
|
|
361
403
|
review = (await EscalationReview.create(fields)).toObject();
|
|
362
404
|
} catch (error) {
|
|
363
|
-
if (error?.code !== DUPLICATE_KEY_ERROR)
|
|
405
|
+
if (error?.code !== DUPLICATE_KEY_ERROR) {
|
|
406
|
+
if (pausedHere) {
|
|
407
|
+
await switchThreadStoppedStatus(patientCode, false).catch((resumeError) => {
|
|
408
|
+
logger.error('[EscalationReview] A failed open left the assistant paused', {
|
|
409
|
+
error: resumeError.message,
|
|
410
|
+
});
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
throw error;
|
|
414
|
+
}
|
|
364
415
|
const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
|
|
365
|
-
if (!existing)
|
|
416
|
+
if (!existing) {
|
|
417
|
+
if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
|
|
418
|
+
throw httpError(409, 'This patient already has a review being opened; try again in a moment');
|
|
419
|
+
}
|
|
420
|
+
if (pausedHere && existing.assistantPausedByReview !== true) {
|
|
421
|
+
try {
|
|
422
|
+
await EscalationReview.updateOne({ _id: existing._id }, { $set: { assistantPausedByReview: true } });
|
|
423
|
+
existing.assistantPausedByReview = true;
|
|
424
|
+
} catch (error) {
|
|
425
|
+
logger.error('[EscalationReview] The pause was not recorded against the open review', {
|
|
426
|
+
escalationReviewId: String(existing._id), error: error.message,
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
}
|
|
366
430
|
return { review: existing, created: false };
|
|
367
431
|
}
|
|
432
|
+
const held = pausedHere || await pauseAssistantFor(patientCode);
|
|
433
|
+
if (held !== review.assistantPausedByReview) {
|
|
434
|
+
await EscalationReview.updateOne({ _id: review._id }, { $set: { assistantPausedByReview: held } });
|
|
435
|
+
review.assistantPausedByReview = held;
|
|
436
|
+
}
|
|
368
437
|
await audit(review, operator, requestId, { action: 'opened', patientCaseRecordIds: recordIds });
|
|
369
438
|
return { review, created: true };
|
|
370
439
|
}
|
|
@@ -612,6 +681,8 @@ async function recordDoctorDecision({
|
|
|
612
681
|
let approvedText = null;
|
|
613
682
|
if (decision === 'approved') approvedText = draft.patientMessage;
|
|
614
683
|
if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
|
|
684
|
+
// Truthiness, not != null: an empty textarea is a decline with nothing to say.
|
|
685
|
+
if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
|
|
615
686
|
|
|
616
687
|
const updated = await updateReview(reviewId, ['awaiting_doctor'], {
|
|
617
688
|
$push: {
|
|
@@ -640,16 +711,40 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
640
711
|
}
|
|
641
712
|
|
|
642
713
|
const claim = newOperationClaim();
|
|
643
|
-
const claimed = await updateReview(reviewId,
|
|
714
|
+
const claimed = await updateReview(reviewId, SENDABLE_STATUSES, { $set: { status: 'sending', operationClaim: claim } });
|
|
644
715
|
const decisionNumber = claimed.decisions.length;
|
|
645
|
-
const { finalText } = claimed.decisions[decisionNumber - 1];
|
|
716
|
+
const { finalText, decision } = claimed.decisions[decisionNumber - 1];
|
|
717
|
+
const claimedFrom = statusAfter(decision);
|
|
718
|
+
|
|
719
|
+
if (!finalText) {
|
|
720
|
+
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
721
|
+
logger.error('[EscalationReview] The claim was not released after a decision with no text', {
|
|
722
|
+
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
723
|
+
});
|
|
724
|
+
});
|
|
725
|
+
throw httpError(409, 'This decision carries no approved text to send to the patient');
|
|
726
|
+
}
|
|
646
727
|
|
|
728
|
+
// Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
|
|
647
729
|
let message;
|
|
648
|
-
let result;
|
|
649
730
|
try {
|
|
650
731
|
message = await patientIndicationsMessage({ review: claimed, finalText, outsideWindowRoute, operator });
|
|
732
|
+
} catch (error) {
|
|
733
|
+
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
734
|
+
logger.error('[EscalationReview] The claim was not released after a send that never started', {
|
|
735
|
+
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
736
|
+
});
|
|
737
|
+
});
|
|
738
|
+
throw error;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
let result;
|
|
742
|
+
try {
|
|
651
743
|
result = await sendMessage(message);
|
|
652
|
-
|
|
744
|
+
const alreadyDelivered = result?.status === 'duplicate_suppressed' && result?.completed === true;
|
|
745
|
+
if (!result?.success && !alreadyDelivered) {
|
|
746
|
+
throw httpError(502, 'The indications could not be sent to the patient');
|
|
747
|
+
}
|
|
653
748
|
} catch (error) {
|
|
654
749
|
if (!sendDidNotHappen(error)) {
|
|
655
750
|
logger.error('[EscalationReview] Patient send outcome is unknown; leaving the review in sending', {
|
|
@@ -658,7 +753,11 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
658
753
|
});
|
|
659
754
|
throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
|
|
660
755
|
}
|
|
661
|
-
await releaseReview(reviewId, 'sending',
|
|
756
|
+
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
757
|
+
logger.error('[EscalationReview] The claim was not released after a confirmed non-send', {
|
|
758
|
+
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
759
|
+
});
|
|
760
|
+
});
|
|
662
761
|
throw error;
|
|
663
762
|
}
|
|
664
763
|
|
|
@@ -711,7 +810,7 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
|
|
|
711
810
|
if (interrupted) closeChanges.fromStatus = current.status;
|
|
712
811
|
if (queued) closeChanges.deliveryConfirmed = true;
|
|
713
812
|
await audit(review, operator, requestId, closeChanges);
|
|
714
|
-
return syncCase(review, operator, requestId);
|
|
813
|
+
return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
|
|
715
814
|
}
|
|
716
815
|
|
|
717
816
|
async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
|
|
@@ -737,7 +836,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
|
|
|
737
836
|
}
|
|
738
837
|
|
|
739
838
|
await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
|
|
740
|
-
return syncCase(review, operator, requestId);
|
|
839
|
+
return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
|
|
741
840
|
}
|
|
742
841
|
|
|
743
842
|
async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
|
|
@@ -35,14 +35,14 @@ const getThreadInfo = async (code) => {
|
|
|
35
35
|
};
|
|
36
36
|
|
|
37
37
|
const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } = {}) => {
|
|
38
|
-
|
|
39
|
-
await Thread.updateOne({ code, stopped: { $ne: true } }, { stopped, pausedAt: new Date() })
|
|
40
|
-
|
|
41
|
-
await Thread.updateOne({ code }, stopped ? { stopped } : { stopped, pausedAt: null });
|
|
42
|
-
}
|
|
38
|
+
const result = stopped && byOperator
|
|
39
|
+
? await Thread.updateOne({ code, stopped: { $ne: true } }, { stopped, pausedAt: new Date() })
|
|
40
|
+
: await Thread.updateOne({ code }, stopped ? { stopped } : { stopped, pausedAt: null });
|
|
43
41
|
|
|
44
42
|
updateRecordByFilter(Monitoreo_ID, 'message_monitor', `{whatsapp_id} = "${code}"`, { stopped }, code)
|
|
45
43
|
.catch(err => logger.error('[switchThreadStoppedStatus] Failed to update message_monitor', { code, error: err.message }));
|
|
44
|
+
|
|
45
|
+
return result;
|
|
46
46
|
};
|
|
47
47
|
|
|
48
48
|
const setThreadPromptId = async (code, promptId) => {
|