@peopl-health/nexus 5.51.0-dev.7633 → 5.51.0-dev.7635

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.
Files changed (36) hide show
  1. package/README.md +21 -0
  2. package/lib/clinical/AssistantProcessor.js +156 -12
  3. package/lib/clinical/context/ToolRuntimeContext.js +39 -1
  4. package/lib/clinical/context/turnContext.js +10 -0
  5. package/lib/clinical/models/supportCandidateModel.js +90 -0
  6. package/lib/clinical/models/triageRecommendationEventModel.js +28 -0
  7. package/lib/clinical/providers/BaseLLMProvider.js +45 -5
  8. package/lib/clinical/services/clinicalAirtableService.js +8 -5
  9. package/lib/clinical/services/deliverySettlementService.js +39 -0
  10. package/lib/clinical/services/divergenceService.js +9 -2
  11. package/lib/clinical/services/supportActionService.js +129 -0
  12. package/lib/clinical/services/supportCandidateService.js +532 -0
  13. package/lib/clinical/services/supportRoutingAgentService.js +118 -0
  14. package/lib/clinical/services/triageRecommendationService.js +453 -251
  15. package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
  16. package/lib/clinical/tools/registerClinicalTools.js +2 -0
  17. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
  18. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +142 -0
  19. package/lib/controllers/dashboardController.js +5 -2
  20. package/lib/controllers/escalationReviewController.js +0 -12
  21. package/lib/core/BatchingManager.js +20 -9
  22. package/lib/core/NexusMessaging.js +25 -6
  23. package/lib/core/ProcessingPipeline.js +32 -3
  24. package/lib/core/runtimeToolPolicy.js +3 -0
  25. package/lib/index.d.ts +334 -6
  26. package/lib/index.js +22 -0
  27. package/lib/models/escalationReviewModel.js +0 -4
  28. package/lib/routes/index.js +0 -2
  29. package/lib/services/airtableService.js +8 -1
  30. package/lib/services/dashboard-provider-registry.js +38 -0
  31. package/lib/services/dashboardService.js +30 -3
  32. package/lib/services/escalationReviewService.js +4 -36
  33. package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
  34. package/lib/shared/dtos/SupportAction.js +28 -0
  35. package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
  36. 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 prerequisite = validateClinicalDelivery(trace, {
177
- enabledSkills: runtime?.enabledSkills,
178
- skillActivationIteration: runtime?.skillActivationIteration,
179
- currentIteration: runtime?.currentIteration,
180
- });
181
- if (prerequisite) {
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 = PURPOSES.includes(rawPurpose) ? rawPurpose : 'ask_clarifying_question';
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
- trace.setSignals({ outboundPurpose: purpose });
208
- trace.setOutbound(outbound);
209
-
210
- let live = true;
211
- try {
212
- if (typeof runtime.isLive === 'function') live = runtime.isLive();
213
- } catch (error) {
214
- logger.warn('[DeliverPatientMessage] liveness check threw; reporting the reply as not sent', { message: error?.message });
215
- live = false;
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,142 @@
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
+ function inactiveTurn() {
85
+ return JSON.stringify({ success: false, error: 'support_routing_turn_inactive', data: {} });
86
+ }
87
+
88
+ function isRuntimeLive(runtime) {
89
+ if (typeof runtime?.isLive !== 'function') return false;
90
+ try {
91
+ return runtime.isLive() === true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ async function handler(args = {}, context = {}) {
98
+ const runtime = context?.toolRuntimeContext;
99
+ if (!runtime?.turnId || !runtime?.patientCode || runtime.turnKind !== 'patient') {
100
+ return inactiveTurn();
101
+ }
102
+ if (!isRuntimeLive(runtime)) {
103
+ return inactiveTurn();
104
+ }
105
+ try {
106
+ const observedAt = runtime.patientInput?.observedAt;
107
+ if (typeof observedAt !== 'string' || Number.isNaN(new Date(observedAt).getTime())) {
108
+ return JSON.stringify({ success: false, error: 'support_routing_source_time_missing', data: {} });
109
+ }
110
+ const recommendation = new SupportRoutingRecommendation({
111
+ patientId: runtime.patientCode,
112
+ origin: 'chat',
113
+ sourceId: runtime.turnId,
114
+ createdAt: new Date(observedAt).toISOString(),
115
+ decisions: (args.decisions || []).map((decision) => normalizedDecision(decision, runtime.turnId)),
116
+ });
117
+ if (!isRuntimeLive(runtime)) return inactiveTurn();
118
+ const candidates = await recordSupportRoutingRecommendation(recommendation);
119
+ runtime.trace?.setSignals?.({
120
+ supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
121
+ });
122
+ return JSON.stringify({
123
+ success: true,
124
+ data: {
125
+ accepted: true,
126
+ candidates: candidates.map((candidate) => ({
127
+ candidate_id: candidate.candidateId,
128
+ service: candidate.service,
129
+ disposition: candidate.disposition,
130
+ })),
131
+ invitation_sent: false,
132
+ },
133
+ });
134
+ } catch (error) {
135
+ if (error instanceof ZodError) {
136
+ return JSON.stringify({ success: false, error: 'support_routing_schema_invalid', data: { issues: error.issues.map((issue) => ({ path: issue.path.join('.'), problem: issue.message })) } });
137
+ }
138
+ return JSON.stringify({ success: false, error: error?.message || 'support routing failed', data: {} });
139
+ }
140
+ }
141
+
142
+ 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
 
@@ -4,7 +4,6 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const {
5
5
  addCallLog,
6
6
  addDraft,
7
- cancelEscalationReview,
8
7
  closeEscalationReview,
9
8
  getEscalationReviewById,
10
9
  handOffToDoctor,
@@ -136,16 +135,6 @@ const closeEscalationReviewController = async (req, res) => {
136
135
  }
137
136
  };
138
137
 
139
- const cancelEscalationReviewController = async (req, res) => {
140
- try {
141
- const { triggeredBy, reason = null } = req.body || {};
142
- const review = await cancelEscalationReview({ id: req.params.id, cancelledBy: triggeredBy, reason, requestId: req.requestId });
143
- res.status(200).json({ success: true, review });
144
- } catch (error) {
145
- respondWithError(res, error, 'cancelling escalation review', { reviewId: req.params?.id });
146
- }
147
- };
148
-
149
138
  const syncEscalationReviewCaseController = async (req, res) => {
150
139
  try {
151
140
  const { triggeredBy } = req.body || {};
@@ -163,7 +152,6 @@ const syncEscalationReviewCaseController = async (req, res) => {
163
152
  module.exports = {
164
153
  addEscalationReviewCallLogController,
165
154
  addEscalationReviewDraftController,
166
- cancelEscalationReviewController,
167
155
  closeEscalationReviewController,
168
156
  getEscalationReviewController,
169
157
  handOffEscalationReviewController,
@@ -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)) return { accepted: true };
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 {