@peopl-health/nexus 5.51.0-dev.7608 → 5.51.0-dev.7627
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/README.md +21 -0
- package/lib/clinical/AssistantProcessor.js +156 -12
- package/lib/clinical/context/ToolRuntimeContext.js +39 -1
- package/lib/clinical/context/turnContext.js +10 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +29 -0
- package/lib/clinical/providers/BaseLLMProvider.js +45 -5
- package/lib/clinical/services/clinicalAirtableService.js +8 -5
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/divergenceService.js +9 -2
- package/lib/clinical/services/supportActionService.js +129 -0
- package/lib/clinical/services/supportCandidateService.js +470 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/triageRecommendationService.js +456 -251
- package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
- package/lib/clinical/tools/registerClinicalTools.js +2 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +121 -0
- package/lib/controllers/dashboardController.js +5 -2
- package/lib/core/BatchingManager.js +20 -9
- package/lib/core/NexusMessaging.js +25 -6
- package/lib/core/ProcessingPipeline.js +32 -3
- package/lib/index.d.ts +325 -6
- package/lib/index.js +22 -0
- package/lib/services/airtableService.js +8 -1
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +30 -3
- package/lib/services/escalationReviewService.js +7 -7
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/package.json +1 -1
|
@@ -166,6 +166,33 @@ function fail(error, data = {}) {
|
|
|
166
166
|
return JSON.stringify({ success: false, error, data });
|
|
167
167
|
}
|
|
168
168
|
|
|
169
|
+
function runtimeIsLive(runtime) {
|
|
170
|
+
try {
|
|
171
|
+
return typeof runtime?.isLive !== 'function' || runtime.isLive() === true;
|
|
172
|
+
} catch (error) {
|
|
173
|
+
logger.warn('[DeliverPatientMessage] liveness check failed', {
|
|
174
|
+
reason: 'delivery_liveness_check_failed',
|
|
175
|
+
errorType: error?.constructor?.name || typeof error,
|
|
176
|
+
});
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function releaseClaim(runtime) {
|
|
182
|
+
try {
|
|
183
|
+
return typeof runtime?.settleDelivery === 'function'
|
|
184
|
+
? await runtime.settleDelivery('known_not_sent')
|
|
185
|
+
: false;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
logger.warn('[DeliverPatientMessage] claim release failed', {
|
|
188
|
+
operationId: runtime?.deliveryDirective?.operationId || null,
|
|
189
|
+
reason: 'nutrition_safety_settlement_failed',
|
|
190
|
+
errorType: error?.constructor?.name || typeof error,
|
|
191
|
+
});
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
169
196
|
async function handler(args = {}, context = {}) {
|
|
170
197
|
const runtime = context?.toolRuntimeContext || null;
|
|
171
198
|
const trace = runtime?.trace || null;
|
|
@@ -173,24 +200,29 @@ async function handler(args = {}, context = {}) {
|
|
|
173
200
|
return fail('DeliverPatientMessage requires an active turn context (turnId, patientCode, trace).');
|
|
174
201
|
}
|
|
175
202
|
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
return fail(prerequisite.error, {
|
|
183
|
-
recovery: prerequisite.recovery,
|
|
184
|
-
required_tool_ids: prerequisite.requiredToolIds,
|
|
203
|
+
const directive = runtime.deliveryDirective;
|
|
204
|
+
if (!directive) {
|
|
205
|
+
const prerequisite = validateClinicalDelivery(trace, {
|
|
206
|
+
enabledSkills: runtime?.enabledSkills,
|
|
207
|
+
skillActivationIteration: runtime?.skillActivationIteration,
|
|
208
|
+
currentIteration: runtime?.currentIteration,
|
|
185
209
|
});
|
|
210
|
+
if (prerequisite) {
|
|
211
|
+
return fail(prerequisite.error, {
|
|
212
|
+
recovery: prerequisite.recovery,
|
|
213
|
+
required_tool_ids: prerequisite.requiredToolIds,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
186
216
|
}
|
|
187
217
|
|
|
188
218
|
const rawPurpose = typeof args.purpose === 'string' ? args.purpose.trim() : '';
|
|
189
|
-
const purpose =
|
|
219
|
+
const purpose = directive
|
|
220
|
+
? 'ask_clarifying_question'
|
|
221
|
+
: (PURPOSES.includes(rawPurpose) ? rawPurpose : 'ask_clarifying_question');
|
|
190
222
|
const messageText = typeof args.message_text === 'string' ? args.message_text : '';
|
|
191
223
|
|
|
192
|
-
let outbound = messageText;
|
|
193
|
-
if (isComposerEnabled() && !isAgentSelfRenderEnabled() && args.intent_payload) {
|
|
224
|
+
let outbound = directive?.body || messageText;
|
|
225
|
+
if (!directive && isComposerEnabled() && !isAgentSelfRenderEnabled() && args.intent_payload) {
|
|
194
226
|
let provider = null;
|
|
195
227
|
try {
|
|
196
228
|
provider = requireGatewayProvider();
|
|
@@ -204,24 +236,51 @@ async function handler(args = {}, context = {}) {
|
|
|
204
236
|
}
|
|
205
237
|
if (!(outbound || '').trim()) outbound = EMPTY_OUTBOUND_FALLBACK;
|
|
206
238
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
239
|
+
if (directive && directive.claimAttempted !== true) {
|
|
240
|
+
if (!runtimeIsLive(runtime)) {
|
|
241
|
+
directive.claimAttempted = true;
|
|
242
|
+
directive.claimed = false;
|
|
243
|
+
} else {
|
|
244
|
+
directive.claimAttempted = true;
|
|
245
|
+
try {
|
|
246
|
+
const claim = runtime.repos?.nutritionSafety?.claimDelivery;
|
|
247
|
+
const claimed = typeof claim === 'function'
|
|
248
|
+
? await claim({
|
|
249
|
+
operationId: directive.operationId,
|
|
250
|
+
patientCode: runtime.patientCode,
|
|
251
|
+
turnId: runtime.turnId,
|
|
252
|
+
traceId: trace?._id ? String(trace._id) : null,
|
|
253
|
+
sourceId: runtime.patientInput?.sourceId || null,
|
|
254
|
+
})
|
|
255
|
+
: null;
|
|
256
|
+
directive.claimed = claimed?.acquired === true;
|
|
257
|
+
} catch {
|
|
258
|
+
directive.claimed = false;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
216
261
|
}
|
|
262
|
+
|
|
263
|
+
const live = runtimeIsLive(runtime);
|
|
264
|
+
if (directive?.claimed && !live) await releaseClaim(runtime);
|
|
265
|
+
|
|
266
|
+
trace.setSignals({
|
|
267
|
+
outboundPurpose: purpose,
|
|
268
|
+
...(directive && {
|
|
269
|
+
deterministicDelivery: {
|
|
270
|
+
operationId: directive.operationId,
|
|
271
|
+
claimed: directive.claimed === true,
|
|
272
|
+
},
|
|
273
|
+
}),
|
|
274
|
+
});
|
|
275
|
+
trace.setOutbound(outbound);
|
|
217
276
|
return JSON.stringify({
|
|
218
277
|
success: true,
|
|
219
278
|
data: {
|
|
220
279
|
purpose,
|
|
221
280
|
recorded: true,
|
|
222
281
|
delivered: false,
|
|
223
|
-
still_active: live,
|
|
224
|
-
means: live
|
|
282
|
+
still_active: live && (!directive || directive.claimed === true),
|
|
283
|
+
means: live && (!directive || directive.claimed === true)
|
|
225
284
|
? 'The reply is RECORDED as the outbound of this turn. Nothing has been sent yet: it goes out only if this turn is still the active run when it finishes, and a newer patient message drops it. Do not treat the patient as informed on the strength of this ack.'
|
|
226
285
|
: 'A newer patient message has already superseded this turn, so this reply will NOT be sent. The replacement turn answers the patient; do not assume they were told anything here.',
|
|
227
286
|
},
|
|
@@ -29,6 +29,8 @@ const TOOLS = [
|
|
|
29
29
|
require('./submitPalliativeCarePlanTool'),
|
|
30
30
|
require('./submitSafetyGateTool'),
|
|
31
31
|
require('./submitRecommendationPlanTool'),
|
|
32
|
+
require('./submitSupportRoutingRecommendationTool'),
|
|
33
|
+
require('./submitNutritionSafetyDecisionTool'),
|
|
32
34
|
require('./getActiveRecommendationsTool'),
|
|
33
35
|
require('./recordRecommendationOutcomeTool'),
|
|
34
36
|
require('./getPatientRiskAssessmentTool'),
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
NutritionSafetyDecision,
|
|
5
|
+
FINDING_CODES,
|
|
6
|
+
FINDING_VALUES,
|
|
7
|
+
QUESTION_CODES,
|
|
8
|
+
EVIDENCE_SOURCE_TYPES,
|
|
9
|
+
DISPOSITIONS,
|
|
10
|
+
} = require('../../shared/dtos/NutritionSafetyDecision');
|
|
11
|
+
|
|
12
|
+
const definition = {
|
|
13
|
+
name: 'submitNutritionSafetyDecision',
|
|
14
|
+
description: '**Does:** Commits the typed warning-sign decision for the current nutrition-intake clarification turn. The active patient, trace, inbound message identity, submission revision, and screen revision are validated by Nexus and revalidated by the consumer repository. Call exactly once when this runtime tool is offered and forced.\n\n**Required inputs:** the reviewed submission and screen revisions; all four findings as yes/no/unknown; every unresolved question code; and a clear, clarify, escalate, or review_required disposition.\n\n**Side effects:** synchronously invokes the configured canonical nutrition-safety repository. It never writes consumer state directly.',
|
|
15
|
+
strict: true,
|
|
16
|
+
replayScope: 'turn',
|
|
17
|
+
parameters: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
additionalProperties: false,
|
|
20
|
+
properties: {
|
|
21
|
+
submission_revision: { type: 'integer', minimum: 1 },
|
|
22
|
+
screen_revision: { type: 'integer', minimum: 0 },
|
|
23
|
+
findings: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
additionalProperties: false,
|
|
26
|
+
properties: Object.fromEntries(FINDING_CODES.map(code => [code, { type: 'string', enum: FINDING_VALUES }])),
|
|
27
|
+
required: FINDING_CODES,
|
|
28
|
+
},
|
|
29
|
+
evidence_refs: {
|
|
30
|
+
type: 'array',
|
|
31
|
+
minItems: FINDING_CODES.length,
|
|
32
|
+
items: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
properties: {
|
|
36
|
+
finding: { type: 'string', enum: FINDING_CODES },
|
|
37
|
+
source_type: { type: 'string', enum: EVIDENCE_SOURCE_TYPES },
|
|
38
|
+
source_id: { type: 'string', minLength: 1 },
|
|
39
|
+
observed_at: { type: 'string', format: 'date-time' },
|
|
40
|
+
},
|
|
41
|
+
required: ['finding', 'source_type', 'source_id', 'observed_at'],
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
questions_needed: {
|
|
45
|
+
type: 'array',
|
|
46
|
+
maxItems: QUESTION_CODES.length,
|
|
47
|
+
uniqueItems: true,
|
|
48
|
+
items: { type: 'string', enum: QUESTION_CODES },
|
|
49
|
+
},
|
|
50
|
+
disposition: { type: 'string', enum: DISPOSITIONS },
|
|
51
|
+
},
|
|
52
|
+
required: ['submission_revision', 'screen_revision', 'findings', 'evidence_refs', 'questions_needed', 'disposition'],
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function fail(error, data = {}) {
|
|
57
|
+
return JSON.stringify({ success: false, error, data });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function activeIdentity(runtime) {
|
|
61
|
+
const trace = runtime?.trace;
|
|
62
|
+
const traceId = trace?._id ? String(trace._id) : null;
|
|
63
|
+
const sourceId = runtime?.patientInput?.sourceId;
|
|
64
|
+
const observedAt = runtime?.patientInput?.observedAt;
|
|
65
|
+
if (!runtime?.turnId || !runtime?.patientCode || runtime?.turnKind !== 'patient' || !traceId
|
|
66
|
+
|| String(trace.turnId) !== String(runtime.turnId)
|
|
67
|
+
|| String(trace.patientCode) !== String(runtime.patientCode)
|
|
68
|
+
|| typeof sourceId !== 'string' || !sourceId
|
|
69
|
+
|| typeof observedAt !== 'string' || Number.isNaN(new Date(observedAt).getTime())) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
patientCode: runtime.patientCode,
|
|
74
|
+
turnId: runtime.turnId,
|
|
75
|
+
traceId,
|
|
76
|
+
sourceId,
|
|
77
|
+
observedAt,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function safeCommitResult(result) {
|
|
82
|
+
const outcome = typeof result?.outcome === 'string' ? result.outcome : null;
|
|
83
|
+
const status = typeof result?.screen?.status === 'string'
|
|
84
|
+
? result.screen.status
|
|
85
|
+
: (typeof result?.status === 'string' ? result.status : null);
|
|
86
|
+
const requested = result?.questionsNeeded ?? result?.questions_needed ?? [];
|
|
87
|
+
const questionsNeeded = Array.isArray(requested)
|
|
88
|
+
? [...new Set(requested.filter(code => QUESTION_CODES.includes(code)))]
|
|
89
|
+
: [];
|
|
90
|
+
if (!outcome || !status) return null;
|
|
91
|
+
return { outcome, status, questions_needed: questionsNeeded };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sameInstant(first, second) {
|
|
95
|
+
return new Date(first).getTime() === new Date(second).getTime();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function validateEvidence(decision, runtime, identity) {
|
|
99
|
+
const trustedContext = runtime?.consumerMetadata?.nutritionSafety?.evidenceRefs;
|
|
100
|
+
const trustedReferences = Array.isArray(trustedContext) ? trustedContext : [];
|
|
101
|
+
|
|
102
|
+
const validated = decision.evidenceRefs.map((reference) => {
|
|
103
|
+
if (reference.sourceType === 'chat') {
|
|
104
|
+
if (reference.sourceId !== identity.sourceId
|
|
105
|
+
|| !sameInstant(reference.observedAt, identity.observedAt)) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
return { ...reference, observedAt: identity.observedAt, traceId: identity.traceId };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const trusted = trustedReferences.find(candidate => (
|
|
112
|
+
candidate?.finding === reference.finding
|
|
113
|
+
&& candidate?.sourceType === reference.sourceType
|
|
114
|
+
&& candidate?.sourceId === reference.sourceId
|
|
115
|
+
&& typeof candidate?.observedAt === 'string'
|
|
116
|
+
&& (reference.sourceType === 'flow'
|
|
117
|
+
? candidate.observedAt === reference.observedAt
|
|
118
|
+
: sameInstant(candidate.observedAt, reference.observedAt))
|
|
119
|
+
));
|
|
120
|
+
if (!trusted) return null;
|
|
121
|
+
return {
|
|
122
|
+
...reference,
|
|
123
|
+
observedAt: trusted.observedAt,
|
|
124
|
+
...(typeof trusted.traceId === 'string' && trusted.traceId ? { traceId: trusted.traceId } : {}),
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
if (validated.some(reference => reference === null)) return null;
|
|
129
|
+
return validated;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function isRuntimeLive(runtime) {
|
|
133
|
+
if (typeof runtime?.isLive !== 'function') return false;
|
|
134
|
+
try {
|
|
135
|
+
return runtime.isLive() === true;
|
|
136
|
+
} catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function handler(args = {}, context = {}) {
|
|
142
|
+
const runtime = context?.toolRuntimeContext;
|
|
143
|
+
const identity = activeIdentity(runtime);
|
|
144
|
+
const commitDecision = runtime?.repos?.nutritionSafety?.commitDecision;
|
|
145
|
+
if (!identity || typeof commitDecision !== 'function') {
|
|
146
|
+
return fail('nutrition_safety_active_context_required');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let decision;
|
|
150
|
+
try {
|
|
151
|
+
decision = new NutritionSafetyDecision(args);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (error instanceof ZodError) {
|
|
154
|
+
return fail('nutrition_safety_decision_invalid', {
|
|
155
|
+
issues: error.issues.slice(0, 20).map(issue => ({
|
|
156
|
+
path: issue.path.join('.'),
|
|
157
|
+
problem: issue.message,
|
|
158
|
+
})),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return fail('nutrition_safety_decision_invalid');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const evidenceRefs = validateEvidence(decision, runtime, identity);
|
|
165
|
+
if (!evidenceRefs) return fail('nutrition_safety_evidence_invalid');
|
|
166
|
+
decision.evidenceRefs = evidenceRefs;
|
|
167
|
+
|
|
168
|
+
if (!isRuntimeLive(runtime)) {
|
|
169
|
+
return fail('nutrition_safety_turn_inactive');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
const result = await commitDecision({ decision, ...identity });
|
|
174
|
+
const safeResult = safeCommitResult(result);
|
|
175
|
+
if (!safeResult) return fail('nutrition_safety_commit_result_invalid');
|
|
176
|
+
if (result?.deliveryDirective) {
|
|
177
|
+
if (typeof runtime?.setDeliveryDirective !== 'function') {
|
|
178
|
+
return fail('nutrition_safety_delivery_directive_unavailable');
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
runtime.setDeliveryDirective(result.deliveryDirective);
|
|
182
|
+
} catch {
|
|
183
|
+
return fail('nutrition_safety_delivery_directive_invalid');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
runtime.trace?.setSignals?.({
|
|
187
|
+
nutritionSafety: {
|
|
188
|
+
submissionRevision: decision.submissionRevision,
|
|
189
|
+
screenRevision: decision.screenRevision,
|
|
190
|
+
disposition: decision.disposition,
|
|
191
|
+
status: safeResult.status,
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
return JSON.stringify({ success: true, data: safeResult });
|
|
195
|
+
} catch {
|
|
196
|
+
return fail('nutrition_safety_commit_failed');
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
module.exports = { definition, handler };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
|
|
4
|
+
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
5
|
+
|
|
6
|
+
const decisionProperties = {
|
|
7
|
+
service: { type: 'string', enum: ['nutrition', 'psychology'] },
|
|
8
|
+
nutritionRisk: { type: ['string', 'null'], enum: ['green', 'yellow', 'red', 'unknown', null] },
|
|
9
|
+
psychologyRisk: { type: ['string', 'null'], enum: ['green', 'orange', 'red', 'unknown', null] },
|
|
10
|
+
disposition: { type: 'string', enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'] },
|
|
11
|
+
groupEligible: { type: 'boolean' },
|
|
12
|
+
urgentIntakeEligible: { type: 'boolean' },
|
|
13
|
+
priority: { type: 'string', enum: ['routine', 'soon', 'urgent'] },
|
|
14
|
+
confidence: { type: 'number', minimum: 0, maximum: 1 },
|
|
15
|
+
reasonCodes: { type: 'array', items: { type: 'string' }, maxItems: 20 },
|
|
16
|
+
evidence: {
|
|
17
|
+
type: 'array',
|
|
18
|
+
minItems: 1,
|
|
19
|
+
maxItems: 20,
|
|
20
|
+
items: {
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: {
|
|
23
|
+
source: { type: 'string', enum: ['chat', 'triage', 'fhir', 'airtable'] },
|
|
24
|
+
sourceId: { type: 'string' },
|
|
25
|
+
code: { type: 'string' },
|
|
26
|
+
summary: { type: ['string', 'null'] },
|
|
27
|
+
confidence: { type: ['number', 'null'], minimum: 0, maximum: 1 },
|
|
28
|
+
},
|
|
29
|
+
required: ['source', 'sourceId', 'code'],
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
safety: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
properties: {
|
|
35
|
+
suicidalIdeation: { type: 'boolean' },
|
|
36
|
+
immediateRisk: { type: 'boolean' },
|
|
37
|
+
urgentMedicalRisk: { type: 'boolean' },
|
|
38
|
+
needsHumanConfirmation: { type: 'boolean' },
|
|
39
|
+
},
|
|
40
|
+
required: ['suicidalIdeation', 'immediateRisk', 'urgentMedicalRisk', 'needsHumanConfirmation'],
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const definition = {
|
|
45
|
+
name: 'submitSupportRoutingRecommendation',
|
|
46
|
+
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
|
|
47
|
+
strict: false,
|
|
48
|
+
parameters: {
|
|
49
|
+
type: 'object',
|
|
50
|
+
properties: {
|
|
51
|
+
decisions: {
|
|
52
|
+
type: 'array',
|
|
53
|
+
minItems: 1,
|
|
54
|
+
maxItems: 2,
|
|
55
|
+
items: { type: 'object', properties: decisionProperties, required: ['service', 'disposition', 'groupEligible', 'confidence', 'evidence', 'safety'] },
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
required: ['decisions'],
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function normalizedDecision(raw, turnId) {
|
|
63
|
+
const common = {
|
|
64
|
+
service: raw.service,
|
|
65
|
+
disposition: raw.disposition,
|
|
66
|
+
groupEligible: raw.groupEligible,
|
|
67
|
+
priority: raw.priority || 'routine',
|
|
68
|
+
confidence: raw.confidence,
|
|
69
|
+
reasonCodes: raw.reasonCodes || [],
|
|
70
|
+
evidence: (raw.evidence || []).map((item) => ({
|
|
71
|
+
source: 'chat',
|
|
72
|
+
sourceId: turnId,
|
|
73
|
+
code: item.code,
|
|
74
|
+
summary: item.summary ?? null,
|
|
75
|
+
confidence: item.confidence ?? null,
|
|
76
|
+
})),
|
|
77
|
+
safety: raw.safety,
|
|
78
|
+
};
|
|
79
|
+
return raw.service === 'nutrition'
|
|
80
|
+
? { ...common, nutritionRisk: raw.nutritionRisk || 'unknown', urgentIntakeEligible: raw.urgentIntakeEligible ?? false }
|
|
81
|
+
: { ...common, psychologyRisk: raw.psychologyRisk || 'unknown' };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function handler(args = {}, context = {}) {
|
|
85
|
+
const runtime = context?.toolRuntimeContext;
|
|
86
|
+
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
87
|
+
return JSON.stringify({ success: false, error: 'submitSupportRoutingRecommendation requires an active turn context.', data: {} });
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
const recommendation = new SupportRoutingRecommendation({
|
|
91
|
+
patientId: runtime.patientCode,
|
|
92
|
+
origin: 'chat',
|
|
93
|
+
sourceId: runtime.turnId,
|
|
94
|
+
createdAt: new Date().toISOString(),
|
|
95
|
+
decisions: (args.decisions || []).map((decision) => normalizedDecision(decision, runtime.turnId)),
|
|
96
|
+
});
|
|
97
|
+
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
98
|
+
runtime.trace?.setSignals?.({
|
|
99
|
+
supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
|
|
100
|
+
});
|
|
101
|
+
return JSON.stringify({
|
|
102
|
+
success: true,
|
|
103
|
+
data: {
|
|
104
|
+
accepted: true,
|
|
105
|
+
candidates: candidates.map((candidate) => ({
|
|
106
|
+
candidate_id: candidate.candidateId,
|
|
107
|
+
service: candidate.service,
|
|
108
|
+
disposition: candidate.disposition,
|
|
109
|
+
})),
|
|
110
|
+
invitation_sent: false,
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (error instanceof ZodError) {
|
|
115
|
+
return JSON.stringify({ success: false, error: 'support_routing_schema_invalid', data: { issues: error.issues.map((issue) => ({ path: issue.path.join('.'), problem: issue.message })) } });
|
|
116
|
+
}
|
|
117
|
+
return JSON.stringify({ success: false, error: error?.message || 'support routing failed', data: {} });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = { definition, handler };
|
|
@@ -8,6 +8,7 @@ const { getAllBoxes, getStatsById, updateBox, getDailyTrend } = require('../serv
|
|
|
8
8
|
const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
|
|
9
9
|
|
|
10
10
|
const getDashboardController = async (req, res) => {
|
|
11
|
+
res.set('Cache-Control', 'private, no-store');
|
|
11
12
|
try {
|
|
12
13
|
const shouldForce = req.query.force === 'true';
|
|
13
14
|
const boxes = await getAllBoxes(shouldForce);
|
|
@@ -19,6 +20,7 @@ const getDashboardController = async (req, res) => {
|
|
|
19
20
|
};
|
|
20
21
|
|
|
21
22
|
const getDashboardStatsControllerById = async (req, res) => {
|
|
23
|
+
res.set('Cache-Control', 'private, no-store');
|
|
22
24
|
try {
|
|
23
25
|
const { id } = req.params;
|
|
24
26
|
const { type } = req.query;
|
|
@@ -43,16 +45,17 @@ const updateDashboardControllerById = async (req, res) => {
|
|
|
43
45
|
return res.status(400).json({ success: false, error });
|
|
44
46
|
}
|
|
45
47
|
|
|
46
|
-
res.json({ success: true, message: 'Box updated', id: box.id });
|
|
47
|
-
|
|
48
48
|
const updatedBox = await updateBox(box.id, box);
|
|
49
49
|
|
|
50
|
+
res.json({ success: true, message: 'Box updated', id: box.id });
|
|
51
|
+
|
|
50
52
|
safeEmit(getStatusEventBus(), 'dashboard:updated', createEvent('dashboard:updated', {
|
|
51
53
|
...updatedBox
|
|
52
54
|
}));
|
|
53
55
|
|
|
54
56
|
} catch (error) {
|
|
55
57
|
logger.error('[DashboardController] Error updating dashboard:', { error: error.message, id: req.params?.id });
|
|
58
|
+
if (!res.headersSent) res.status(500).json({ success: false, error: error.message || 'Failed to update dashboard' });
|
|
56
59
|
}
|
|
57
60
|
};
|
|
58
61
|
|
|
@@ -67,9 +67,8 @@ class BatchingManager {
|
|
|
67
67
|
return this.abortControllers.get(runId)?.signal;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
async handleBatchedProcessing(chatId, processingFn, sendResponseFn) {
|
|
70
|
+
async handleBatchedProcessing(chatId, processingFn, sendResponseFn, discardResponseFn = null) {
|
|
71
71
|
if (this.draining) return this._refuse(chatId, false);
|
|
72
|
-
|
|
73
72
|
if (this.processingLocks.has(chatId)) {
|
|
74
73
|
if (this.config.abortOnNewMessage && this.activeRequests.has(chatId)) {
|
|
75
74
|
const runId = this.activeRequests.get(chatId);
|
|
@@ -80,18 +79,18 @@ class BatchingManager {
|
|
|
80
79
|
if (this.config.immediateRestart) {
|
|
81
80
|
this._clearProcessingState(chatId);
|
|
82
81
|
this.processingLocks.set(chatId, true);
|
|
83
|
-
return await this._runWithLock(chatId, processingFn, sendResponseFn);
|
|
82
|
+
return await this._runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn);
|
|
84
83
|
}
|
|
85
84
|
}
|
|
86
85
|
return { accepted: true };
|
|
87
86
|
}
|
|
88
87
|
|
|
89
88
|
this.processingLocks.set(chatId, true);
|
|
90
|
-
return await this._runWithLock(chatId, processingFn, sendResponseFn);
|
|
89
|
+
return await this._runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn);
|
|
91
90
|
}
|
|
92
91
|
|
|
93
|
-
async enqueueProcessing(chatId, processingFn, sendResponseFn) {
|
|
94
|
-
return await this._runWithLock(chatId, processingFn, sendResponseFn, { rethrow: true });
|
|
92
|
+
async enqueueProcessing(chatId, processingFn, sendResponseFn, discardResponseFn = null) {
|
|
93
|
+
return await this._runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn, { rethrow: true });
|
|
95
94
|
}
|
|
96
95
|
|
|
97
96
|
_refuse(chatId, rethrow) {
|
|
@@ -101,9 +100,8 @@ class BatchingManager {
|
|
|
101
100
|
return { accepted: false, reason: 'draining' };
|
|
102
101
|
}
|
|
103
102
|
|
|
104
|
-
async _runWithLock(chatId, processingFn, sendResponseFn, { rethrow = false } = {}) {
|
|
103
|
+
async _runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn = null, { rethrow = false } = {}) {
|
|
105
104
|
if (this.draining) return this._refuse(chatId, rethrow);
|
|
106
|
-
|
|
107
105
|
const prev = this.chatQueues.get(chatId) || Promise.resolve();
|
|
108
106
|
let resolveGate;
|
|
109
107
|
const gate = new Promise(r => { resolveGate = r; });
|
|
@@ -128,7 +126,20 @@ class BatchingManager {
|
|
|
128
126
|
if (this._checkAbandoned(runId)) return { accepted: true };
|
|
129
127
|
|
|
130
128
|
const result = await processingFn(runId);
|
|
131
|
-
if (this._checkAbandoned(runId))
|
|
129
|
+
if (this._checkAbandoned(runId)) {
|
|
130
|
+
if (result && typeof discardResponseFn === 'function') {
|
|
131
|
+
try {
|
|
132
|
+
await discardResponseFn(result);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger.warn('[BatchingManager] abandoned response discard failed', {
|
|
135
|
+
chatId,
|
|
136
|
+
reason: 'abandoned_response_discard_failed',
|
|
137
|
+
errorType: error?.constructor?.name || typeof error,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return { accepted: true };
|
|
142
|
+
}
|
|
132
143
|
|
|
133
144
|
if (sendResponseFn && result) {
|
|
134
145
|
try {
|
|
@@ -146,6 +146,7 @@ class NexusMessaging {
|
|
|
146
146
|
phiProcessor: this.phiProcessor,
|
|
147
147
|
storeRunMetrics,
|
|
148
148
|
llmMonitor: this.llmMonitor,
|
|
149
|
+
toolRuntimeRepos: config.assistant?.toolRuntimeRepos || {},
|
|
149
150
|
});
|
|
150
151
|
|
|
151
152
|
this.scheduledMessageJob = new ScheduledMessageJob({
|
|
@@ -635,24 +636,33 @@ class NexusMessaging {
|
|
|
635
636
|
|
|
636
637
|
async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true } = {}) {
|
|
637
638
|
let capturedResult = null;
|
|
639
|
+
const discardResponseFn = async (result) => {
|
|
640
|
+
await this.assistantProcessor.discardResponse(chatId, result);
|
|
641
|
+
};
|
|
638
642
|
|
|
639
643
|
const processingFn = async (runId) => {
|
|
640
644
|
const shouldContinue = () => this.batchingManager.isActiveRun(chatId, runId);
|
|
641
645
|
capturedResult = await this.pipeline.run(
|
|
642
646
|
{ chatId, runId, type },
|
|
643
647
|
executeFn,
|
|
644
|
-
shouldContinue
|
|
648
|
+
shouldContinue,
|
|
649
|
+
discardResponseFn,
|
|
645
650
|
);
|
|
646
651
|
return capturedResult;
|
|
647
652
|
};
|
|
648
653
|
|
|
649
654
|
const sendResponseFn = async (result) => {
|
|
650
|
-
if (sendResponse)
|
|
655
|
+
if (!sendResponse) return;
|
|
656
|
+
if (result?.turnId && !this.batchingManager.isActiveRun(chatId, result.turnId)) {
|
|
657
|
+
await discardResponseFn(result);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
await this.assistantProcessor.sendResponse(chatId, result);
|
|
651
661
|
};
|
|
652
662
|
|
|
653
663
|
const admission = mode === 'queue'
|
|
654
|
-
? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn)
|
|
655
|
-
: await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
|
|
664
|
+
? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn, discardResponseFn)
|
|
665
|
+
: await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn, discardResponseFn);
|
|
656
666
|
|
|
657
667
|
if (admission?.accepted === false) return { deferred: true, reason: admission.reason };
|
|
658
668
|
|
|
@@ -691,7 +701,14 @@ class NexusMessaging {
|
|
|
691
701
|
preProcessed.messages[0]
|
|
692
702
|
);
|
|
693
703
|
|
|
694
|
-
|
|
704
|
+
try {
|
|
705
|
+
if (storeRunMetrics) {
|
|
706
|
+
await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
|
|
707
|
+
}
|
|
708
|
+
} catch (error) {
|
|
709
|
+
await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
710
|
+
throw error;
|
|
711
|
+
}
|
|
695
712
|
return { ...result, timings: preProcessed.timings };
|
|
696
713
|
}, shouldContinue, runId);
|
|
697
714
|
}
|
|
@@ -1012,9 +1029,10 @@ class NexusMessaging {
|
|
|
1012
1029
|
async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
|
|
1013
1030
|
const query = { numero: chatId, from_me: false, processed: false };
|
|
1014
1031
|
const unprocessed = await getMessages(query, { select: '_id' });
|
|
1032
|
+
let result = null;
|
|
1015
1033
|
|
|
1016
1034
|
try {
|
|
1017
|
-
|
|
1035
|
+
result = await processingFn();
|
|
1018
1036
|
if (unprocessed.length > 0 && shouldFinalize()) {
|
|
1019
1037
|
const marks = runId ? { processed: true, processedByTurnId: runId } : { processed: true };
|
|
1020
1038
|
await Message.updateMany({ _id: { $in: unprocessed.map(m => m._id) } }, { $set: marks });
|
|
@@ -1022,6 +1040,7 @@ class NexusMessaging {
|
|
|
1022
1040
|
}
|
|
1023
1041
|
return result;
|
|
1024
1042
|
} catch (error) {
|
|
1043
|
+
if (result) await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
1025
1044
|
logger.debug('[_processMessages] Processing failed', { chatId });
|
|
1026
1045
|
throw error;
|
|
1027
1046
|
}
|