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

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 +0 -21
  2. package/lib/clinical/AssistantProcessor.js +12 -156
  3. package/lib/clinical/context/ToolRuntimeContext.js +1 -39
  4. package/lib/clinical/context/turnContext.js +0 -10
  5. package/lib/clinical/models/triageRecommendationEventModel.js +0 -28
  6. package/lib/clinical/providers/BaseLLMProvider.js +5 -45
  7. package/lib/clinical/services/clinicalAirtableService.js +5 -8
  8. package/lib/clinical/services/divergenceService.js +2 -9
  9. package/lib/clinical/services/triageRecommendationService.js +251 -453
  10. package/lib/clinical/tools/deliverPatientMessageTool.js +23 -82
  11. package/lib/clinical/tools/registerClinicalTools.js +0 -2
  12. package/lib/controllers/dashboardController.js +2 -5
  13. package/lib/controllers/escalationReviewController.js +12 -0
  14. package/lib/core/BatchingManager.js +9 -20
  15. package/lib/core/NexusMessaging.js +6 -25
  16. package/lib/core/ProcessingPipeline.js +3 -32
  17. package/lib/index.d.ts +6 -334
  18. package/lib/index.js +0 -22
  19. package/lib/models/escalationReviewModel.js +4 -0
  20. package/lib/routes/index.js +2 -0
  21. package/lib/services/airtableService.js +1 -8
  22. package/lib/services/dashboardService.js +3 -30
  23. package/lib/services/escalationReviewService.js +43 -11
  24. package/package.json +1 -1
  25. package/lib/clinical/models/supportCandidateModel.js +0 -90
  26. package/lib/clinical/services/deliverySettlementService.js +0 -39
  27. package/lib/clinical/services/supportActionService.js +0 -129
  28. package/lib/clinical/services/supportCandidateService.js +0 -532
  29. package/lib/clinical/services/supportRoutingAgentService.js +0 -118
  30. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +0 -200
  31. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +0 -141
  32. package/lib/core/runtimeToolPolicy.js +0 -3
  33. package/lib/services/dashboard-provider-registry.js +0 -38
  34. package/lib/shared/dtos/NutritionSafetyDecision.js +0 -128
  35. package/lib/shared/dtos/SupportAction.js +0 -28
  36. package/lib/shared/dtos/SupportRoutingRecommendation.js +0 -124
@@ -166,33 +166,6 @@ 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
-
196
169
  async function handler(args = {}, context = {}) {
197
170
  const runtime = context?.toolRuntimeContext || null;
198
171
  const trace = runtime?.trace || null;
@@ -200,29 +173,24 @@ async function handler(args = {}, context = {}) {
200
173
  return fail('DeliverPatientMessage requires an active turn context (turnId, patientCode, trace).');
201
174
  }
202
175
 
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,
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,
209
185
  });
210
- if (prerequisite) {
211
- return fail(prerequisite.error, {
212
- recovery: prerequisite.recovery,
213
- required_tool_ids: prerequisite.requiredToolIds,
214
- });
215
- }
216
186
  }
217
187
 
218
188
  const rawPurpose = typeof args.purpose === 'string' ? args.purpose.trim() : '';
219
- const purpose = directive
220
- ? 'ask_clarifying_question'
221
- : (PURPOSES.includes(rawPurpose) ? rawPurpose : 'ask_clarifying_question');
189
+ const purpose = PURPOSES.includes(rawPurpose) ? rawPurpose : 'ask_clarifying_question';
222
190
  const messageText = typeof args.message_text === 'string' ? args.message_text : '';
223
191
 
224
- let outbound = directive?.body || messageText;
225
- if (!directive && isComposerEnabled() && !isAgentSelfRenderEnabled() && args.intent_payload) {
192
+ let outbound = messageText;
193
+ if (isComposerEnabled() && !isAgentSelfRenderEnabled() && args.intent_payload) {
226
194
  let provider = null;
227
195
  try {
228
196
  provider = requireGatewayProvider();
@@ -236,51 +204,24 @@ async function handler(args = {}, context = {}) {
236
204
  }
237
205
  if (!(outbound || '').trim()) outbound = EMPTY_OUTBOUND_FALLBACK;
238
206
 
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
- }
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
- });
207
+ trace.setSignals({ outboundPurpose: purpose });
275
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;
216
+ }
276
217
  return JSON.stringify({
277
218
  success: true,
278
219
  data: {
279
220
  purpose,
280
221
  recorded: true,
281
222
  delivered: false,
282
- still_active: live && (!directive || directive.claimed === true),
283
- means: live && (!directive || directive.claimed === true)
223
+ still_active: live,
224
+ means: live
284
225
  ? '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.'
285
226
  : '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.',
286
227
  },
@@ -29,8 +29,6 @@ const TOOLS = [
29
29
  require('./submitPalliativeCarePlanTool'),
30
30
  require('./submitSafetyGateTool'),
31
31
  require('./submitRecommendationPlanTool'),
32
- require('./submitSupportRoutingRecommendationTool'),
33
- require('./submitNutritionSafetyDecisionTool'),
34
32
  require('./getActiveRecommendationsTool'),
35
33
  require('./recordRecommendationOutcomeTool'),
36
34
  require('./getPatientRiskAssessmentTool'),
@@ -8,7 +8,6 @@ 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');
12
11
  try {
13
12
  const shouldForce = req.query.force === 'true';
14
13
  const boxes = await getAllBoxes(shouldForce);
@@ -20,7 +19,6 @@ const getDashboardController = async (req, res) => {
20
19
  };
21
20
 
22
21
  const getDashboardStatsControllerById = async (req, res) => {
23
- res.set('Cache-Control', 'private, no-store');
24
22
  try {
25
23
  const { id } = req.params;
26
24
  const { type } = req.query;
@@ -45,17 +43,16 @@ const updateDashboardControllerById = async (req, res) => {
45
43
  return res.status(400).json({ success: false, error });
46
44
  }
47
45
 
48
- const updatedBox = await updateBox(box.id, box);
49
-
50
46
  res.json({ success: true, message: 'Box updated', id: box.id });
51
47
 
48
+ const updatedBox = await updateBox(box.id, box);
49
+
52
50
  safeEmit(getStatusEventBus(), 'dashboard:updated', createEvent('dashboard:updated', {
53
51
  ...updatedBox
54
52
  }));
55
53
 
56
54
  } catch (error) {
57
55
  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' });
59
56
  }
60
57
  };
61
58
 
@@ -4,6 +4,7 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const {
5
5
  addCallLog,
6
6
  addDraft,
7
+ cancelEscalationReview,
7
8
  closeEscalationReview,
8
9
  getEscalationReviewById,
9
10
  handOffToDoctor,
@@ -135,6 +136,16 @@ const closeEscalationReviewController = async (req, res) => {
135
136
  }
136
137
  };
137
138
 
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
+
138
149
  const syncEscalationReviewCaseController = async (req, res) => {
139
150
  try {
140
151
  const { triggeredBy } = req.body || {};
@@ -152,6 +163,7 @@ const syncEscalationReviewCaseController = async (req, res) => {
152
163
  module.exports = {
153
164
  addEscalationReviewCallLogController,
154
165
  addEscalationReviewDraftController,
166
+ cancelEscalationReviewController,
155
167
  closeEscalationReviewController,
156
168
  getEscalationReviewController,
157
169
  handOffEscalationReviewController,
@@ -67,8 +67,9 @@ class BatchingManager {
67
67
  return this.abortControllers.get(runId)?.signal;
68
68
  }
69
69
 
70
- async handleBatchedProcessing(chatId, processingFn, sendResponseFn, discardResponseFn = null) {
70
+ async handleBatchedProcessing(chatId, processingFn, sendResponseFn) {
71
71
  if (this.draining) return this._refuse(chatId, false);
72
+
72
73
  if (this.processingLocks.has(chatId)) {
73
74
  if (this.config.abortOnNewMessage && this.activeRequests.has(chatId)) {
74
75
  const runId = this.activeRequests.get(chatId);
@@ -79,18 +80,18 @@ class BatchingManager {
79
80
  if (this.config.immediateRestart) {
80
81
  this._clearProcessingState(chatId);
81
82
  this.processingLocks.set(chatId, true);
82
- return await this._runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn);
83
+ return await this._runWithLock(chatId, processingFn, sendResponseFn);
83
84
  }
84
85
  }
85
86
  return { accepted: true };
86
87
  }
87
88
 
88
89
  this.processingLocks.set(chatId, true);
89
- return await this._runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn);
90
+ return await this._runWithLock(chatId, processingFn, sendResponseFn);
90
91
  }
91
92
 
92
- async enqueueProcessing(chatId, processingFn, sendResponseFn, discardResponseFn = null) {
93
- return await this._runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn, { rethrow: true });
93
+ async enqueueProcessing(chatId, processingFn, sendResponseFn) {
94
+ return await this._runWithLock(chatId, processingFn, sendResponseFn, { rethrow: true });
94
95
  }
95
96
 
96
97
  _refuse(chatId, rethrow) {
@@ -100,8 +101,9 @@ class BatchingManager {
100
101
  return { accepted: false, reason: 'draining' };
101
102
  }
102
103
 
103
- async _runWithLock(chatId, processingFn, sendResponseFn, discardResponseFn = null, { rethrow = false } = {}) {
104
+ async _runWithLock(chatId, processingFn, sendResponseFn, { rethrow = false } = {}) {
104
105
  if (this.draining) return this._refuse(chatId, rethrow);
106
+
105
107
  const prev = this.chatQueues.get(chatId) || Promise.resolve();
106
108
  let resolveGate;
107
109
  const gate = new Promise(r => { resolveGate = r; });
@@ -126,20 +128,7 @@ class BatchingManager {
126
128
  if (this._checkAbandoned(runId)) return { accepted: true };
127
129
 
128
130
  const result = await processingFn(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
- }
131
+ if (this._checkAbandoned(runId)) return { accepted: true };
143
132
 
144
133
  if (sendResponseFn && result) {
145
134
  try {
@@ -146,7 +146,6 @@ class NexusMessaging {
146
146
  phiProcessor: this.phiProcessor,
147
147
  storeRunMetrics,
148
148
  llmMonitor: this.llmMonitor,
149
- toolRuntimeRepos: config.assistant?.toolRuntimeRepos || {},
150
149
  });
151
150
 
152
151
  this.scheduledMessageJob = new ScheduledMessageJob({
@@ -636,33 +635,24 @@ class NexusMessaging {
636
635
 
637
636
  async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true } = {}) {
638
637
  let capturedResult = null;
639
- const discardResponseFn = async (result) => {
640
- await this.assistantProcessor.discardResponse(chatId, result);
641
- };
642
638
 
643
639
  const processingFn = async (runId) => {
644
640
  const shouldContinue = () => this.batchingManager.isActiveRun(chatId, runId);
645
641
  capturedResult = await this.pipeline.run(
646
642
  { chatId, runId, type },
647
643
  executeFn,
648
- shouldContinue,
649
- discardResponseFn,
644
+ shouldContinue
650
645
  );
651
646
  return capturedResult;
652
647
  };
653
648
 
654
649
  const sendResponseFn = async (result) => {
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);
650
+ if (sendResponse) await this.assistantProcessor.sendResponse(chatId, result);
661
651
  };
662
652
 
663
653
  const admission = mode === 'queue'
664
- ? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn, discardResponseFn)
665
- : await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn, discardResponseFn);
654
+ ? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn)
655
+ : await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
666
656
 
667
657
  if (admission?.accepted === false) return { deferred: true, reason: admission.reason };
668
658
 
@@ -701,14 +691,7 @@ class NexusMessaging {
701
691
  preProcessed.messages[0]
702
692
  );
703
693
 
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
- }
694
+ if (storeRunMetrics) await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
712
695
  return { ...result, timings: preProcessed.timings };
713
696
  }, shouldContinue, runId);
714
697
  }
@@ -1029,10 +1012,9 @@ class NexusMessaging {
1029
1012
  async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
1030
1013
  const query = { numero: chatId, from_me: false, processed: false };
1031
1014
  const unprocessed = await getMessages(query, { select: '_id' });
1032
- let result = null;
1033
1015
 
1034
1016
  try {
1035
- result = await processingFn();
1017
+ const result = await processingFn();
1036
1018
  if (unprocessed.length > 0 && shouldFinalize()) {
1037
1019
  const marks = runId ? { processed: true, processedByTurnId: runId } : { processed: true };
1038
1020
  await Message.updateMany({ _id: { $in: unprocessed.map(m => m._id) } }, { $set: marks });
@@ -1040,7 +1022,6 @@ class NexusMessaging {
1040
1022
  }
1041
1023
  return result;
1042
1024
  } catch (error) {
1043
- if (result) await this.assistantProcessor.discardResponse?.(chatId, result);
1044
1025
  logger.debug('[_processMessages] Processing failed', { chatId });
1045
1026
  throw error;
1046
1027
  }
@@ -1,7 +1,6 @@
1
1
  const { isPlainObject } = require('../utils/jsonUtils');
2
2
  const { describeThrown } = require('../utils/errorUtils');
3
3
  const { logger } = require('../utils/logger');
4
- const { MAX_ADDITIONAL_TOOL_IDS } = require('./runtimeToolPolicy');
5
4
 
6
5
  const VALID_HOOKS = ['preProcess', 'postProcess'];
7
6
 
@@ -34,7 +33,7 @@ class ProcessingPipeline {
34
33
  return this;
35
34
  }
36
35
 
37
- async run(context, executeFn, shouldContinue = () => true, discardResult = null) {
36
+ async run(context, executeFn, shouldContinue = () => true) {
38
37
  const ctx = { metadata: {}, ...context };
39
38
  const preProcessCount = this._hooks.preProcess.length;
40
39
  const postProcessCount = this._hooks.postProcess.length;
@@ -50,7 +49,6 @@ class ProcessingPipeline {
50
49
  skip: preProcessResult.skip,
51
50
  hasAdditionalInstructions: !!preProcessResult.additionalInstructions,
52
51
  additionalMessagesCount: preProcessResult.additionalMessages.length,
53
- additionalToolIdsCount: preProcessResult.additionalToolIds?.length || 0,
54
52
  hasToolChoice: preProcessResult.toolChoice != null,
55
53
  });
56
54
 
@@ -64,21 +62,7 @@ class ProcessingPipeline {
64
62
 
65
63
  const result = await executeFn(preProcessResult, shouldContinue, ctx.runId);
66
64
 
67
- if (!shouldContinue()) {
68
- if (result && typeof discardResult === 'function') {
69
- try {
70
- await discardResult(result);
71
- } catch (error) {
72
- logger.warn('[ProcessingPipeline] result discard failed', {
73
- chatId: ctx.chatId,
74
- type: ctx.type,
75
- reason: 'result_discard_failed',
76
- errorType: error?.constructor?.name || typeof error,
77
- });
78
- }
79
- }
80
- return null;
81
- }
65
+ if (!shouldContinue()) return null;
82
66
 
83
67
  this._runPostProcessHooks(ctx, result, null);
84
68
  return result;
@@ -132,15 +116,6 @@ class ProcessingPipeline {
132
116
  if (result.toolChoice) {
133
117
  merged.toolChoice = result.toolChoice;
134
118
  }
135
- if (Array.isArray(result.additionalToolIds)) {
136
- const existing = new Set(merged.additionalToolIds || []);
137
- for (const toolId of result.additionalToolIds) {
138
- if (existing.size >= MAX_ADDITIONAL_TOOL_IDS) break;
139
- if (typeof toolId !== 'string' || !toolId.trim()) continue;
140
- existing.add(toolId.trim());
141
- }
142
- if (existing.size > 0) merged.additionalToolIds = [...existing];
143
- }
144
119
  if (isPlainObject(result.signals)) {
145
120
  Object.assign(merged.signals, result.signals);
146
121
  }
@@ -158,11 +133,7 @@ class ProcessingPipeline {
158
133
  if (hooks.length === 0) return;
159
134
 
160
135
  setImmediate(() => {
161
- const postContext = {
162
- chatId: context.chatId,
163
- type: context.type,
164
- ...(Object.keys(context.metadata || {}).length > 0 && { metadata: context.metadata }),
165
- };
136
+ const postContext = { chatId: context.chatId, type: context.type };
166
137
  if (result) postContext.result = result;
167
138
  if (error) postContext.error = error;
168
139