@peopl-health/nexus 5.52.0-dev.7663 → 5.52.0-dev.7684

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.
@@ -60,7 +60,7 @@ class GatewayProvider extends BaseLLMProvider {
60
60
  sessionManager: this.sessionManager,
61
61
  });
62
62
  } catch (err) {
63
- throw new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`);
63
+ throw Object.assign(new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`), { permanent: true });
64
64
  }
65
65
  return this._subs[vendor];
66
66
  }
@@ -80,7 +80,7 @@ class GatewayProvider extends BaseLLMProvider {
80
80
  }
81
81
  const { vendor, model: routedModel } = this._route(model);
82
82
  if (vendor !== 'openai' && vendor !== 'anthropic') {
83
- throw new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`);
83
+ throw Object.assign(new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`), { permanent: true });
84
84
  }
85
85
  return this._sub(vendor).runStructured({ ...params, model: routedModel });
86
86
  }
@@ -1,3 +1,4 @@
1
+ const { Types } = require('mongoose');
1
2
  const { getTriageGate, getTriagePlan } = require('../config/subAgentsConfig');
2
3
  const { getSafetyFlagPatterns, getRedFlagMinRoutes } = require('../config/divergenceConfig');
3
4
  const { requireGatewayProvider } = require('../config/llmConfig');
@@ -19,6 +20,8 @@ const {
19
20
  hasActionableFindings,
20
21
  } = require('../helpers/triageCaseBaseHelper');
21
22
  const { buildLegacyStep1, buildLegacyStep2, buildLegacyStep3 } = require('../helpers/legacyRecommendationFormatHelper');
23
+
24
+ const runtimeConfig = require('../../config/runtimeConfig');
22
25
  const { triageRecommendationLive } = require('../flags/triageRecommendationFlags');
23
26
  const { Symptoms_ID } = require('../../config/airtableConfig');
24
27
  const { TRIAGE_RUN_PREFIX } = require('../../fhir/helpers/recommendationIds');
@@ -67,6 +70,8 @@ const { prepareSupportAction } = require('./supportActionService');
67
70
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
68
71
  const GATE_MAX_ATTEMPTS = 2;
69
72
  const PLAN_MAX_ATTEMPTS = 2;
73
+ const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
74
+ const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
70
75
  const RAW_EXCERPT_MAX = 2000;
71
76
  const PRIOR_TRIAGE_RX = /^rec[A-Za-z0-9]{14,}$/;
72
77
  const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_recommendations)';
@@ -147,23 +152,94 @@ function defaultRunId(payload) {
147
152
  return `${TRIAGE_RUN_PREFIX}${payload.triageRecordId}`;
148
153
  }
149
154
 
155
+ function sleep(ms, { keepAlive = false } = {}) {
156
+ return new Promise((resolve) => {
157
+ const t = setTimeout(resolve, ms);
158
+ if (!keepAlive) t.unref?.();
159
+ });
160
+ }
161
+
162
+ function isPermanentProviderError(error) {
163
+ if (error?.permanent === true) return true;
164
+ const status = Number(error?.status ?? error?.statusCode);
165
+ return Number.isFinite(status) && status >= 400 && status < 500 && status !== 408 && status !== 429;
166
+ }
167
+
168
+ function alreadyRetriedByProvider(error) {
169
+ return error?.originalError !== undefined;
170
+ }
171
+
172
+ function jittered(ms) {
173
+ return Math.round(ms * (0.75 + (Math.random() * 0.5)));
174
+ }
175
+
176
+ function backoffSchedule(key, fallback) {
177
+ const raw = runtimeConfig.get(key);
178
+ if (raw == null) return fallback;
179
+ if (String(raw).trim() === '') return [];
180
+ const pieces = String(raw).split(',').map((piece) => piece.trim());
181
+ if (pieces.some((piece) => piece === '')) return fallback;
182
+ const parsed = pieces.map(Number);
183
+ if (!parsed.length || parsed.some((ms) => !Number.isFinite(ms) || ms < 0)) return fallback;
184
+ return parsed;
185
+ }
186
+
187
+ function newIdempotentEventId() {
188
+ return new Types.ObjectId();
189
+ }
190
+
191
+ function settleLossIsCritical(status) {
192
+ return status !== 'success' && status !== 'skipped' && status !== 'skipped_duplicate';
193
+ }
194
+
195
+ function newTransientBudget() {
196
+ return { schedule: backoffSchedule('TRIAGE_PROVIDER_RETRY_BACKOFF_MS', DEFAULT_PROVIDER_RETRY_BACKOFF_MS), used: 0 };
197
+ }
198
+
199
+ async function callProviderWithBackoff(run, { code, rid, stage, attempt, budget }) {
200
+ for (;;) {
201
+ try {
202
+ return await run();
203
+ } catch (err) {
204
+ const permanent = isPermanentProviderError(err) || alreadyRetriedByProvider(err);
205
+ const waitMs = permanent ? null : budget.schedule[budget.used];
206
+ logger.warn(`[triageRecommendation] ${stage} provider call failed`, {
207
+ code, runId: rid, attempt, transientRetriesUsed: budget.used, retryInMs: waitMs ?? null, permanent, error: err?.message,
208
+ });
209
+ if (waitMs == null) throw err;
210
+ budget.used += 1;
211
+ await sleep(jittered(waitMs));
212
+ }
213
+ }
214
+ }
215
+
150
216
  async function recordSettleEvent({ payload, trigger, totalLatencyMs, ...settle }) {
151
217
  const event = { patientCode: payload.patientCode, triageRecordId: payload.triageRecordId, trigger };
152
218
  if (totalLatencyMs != null) event.totalLatencyMs = totalLatencyMs;
153
219
  for (const [key, value] of Object.entries(settle)) {
154
220
  if (value != null) event[key] = value;
155
221
  }
156
- try {
157
- await getTriageRecommendationEventModel().create(event);
158
- } catch (err) {
159
- logger.warn('[triageRecommendation] settle event write failed', {
160
- code: payload.patientCode,
161
- triageRecordId: payload.triageRecordId,
162
- status: event.status,
163
- reason: event.reason,
164
- error: err?.message,
165
- });
222
+ event._id = newIdempotentEventId();
223
+ let lastError;
224
+ const settleSchedule = backoffSchedule('TRIAGE_SETTLE_WRITE_BACKOFF_MS', DEFAULT_SETTLE_WRITE_BACKOFF_MS);
225
+ for (let tries = 0; tries <= settleSchedule.length; tries += 1) {
226
+ try {
227
+ await getTriageRecommendationEventModel().create(event);
228
+ return;
229
+ } catch (err) {
230
+ if (err?.code === 11000) return;
231
+ lastError = err;
232
+ const waitMs = settleSchedule[tries];
233
+ if (waitMs == null) break;
234
+ await sleep(jittered(waitMs), { keepAlive: true });
235
+ }
236
+ }
237
+ const lost = { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: event.status, reason: event.reason, error: lastError?.message };
238
+ if (!settleLossIsCritical(event.status)) {
239
+ logger.warn('[triageRecommendation] settle event write failed', lost);
240
+ return;
166
241
  }
242
+ logger.error('[triageRecommendation] failure lost before it was recorded', lost);
167
243
  }
168
244
 
169
245
  async function generateTriageRecommendations({ payload, provider, runId = null, supportRouting = {} }) {
@@ -655,6 +731,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
655
731
  let gateRepairs = [];
656
732
  let accepted = null;
657
733
  let priorIssues = null;
734
+ const budget = newTransientBudget();
658
735
  for (let attempt = 1; attempt <= GATE_MAX_ATTEMPTS; attempt += 1) {
659
736
  attempts = attempt;
660
737
  const last = attempt === GATE_MAX_ATTEMPTS;
@@ -662,13 +739,12 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
662
739
  if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues) });
663
740
  let result;
664
741
  try {
665
- result = await provider.runStructured({
742
+ result = await callProviderWithBackoff(() => provider.runStructured({
666
743
  presetId,
667
744
  input,
668
745
  metadata: { subAgent: 'triage-gate', runId: rid },
669
- });
670
- } catch (err) {
671
- logger.warn('[triageRecommendation] gate provider call failed', { code, runId: rid, attempt, error: err?.message });
746
+ }), { code, rid, stage: 'gate', attempt, budget });
747
+ } catch {
672
748
  if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_provider_failed' } };
673
749
  continue;
674
750
  }
@@ -772,6 +848,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
772
848
  let rankReordered = 0;
773
849
  let deniedCardsDropped = 0;
774
850
  let deniedTargetsStripped = 0;
851
+ const budget = newTransientBudget();
775
852
  for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
776
853
  const content = attempt === 1 || !lastIssues.length
777
854
  ? planInput
@@ -779,13 +856,12 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
779
856
  const last = attempt === PLAN_MAX_ATTEMPTS;
780
857
  let result;
781
858
  try {
782
- result = await provider.runStructured({
859
+ result = await callProviderWithBackoff(() => provider.runStructured({
783
860
  presetId,
784
861
  input: [{ role: 'user', content }],
785
862
  metadata: { subAgent: 'triage-plan', runId: rid },
786
- });
787
- } catch (err) {
788
- logger.warn('[triageRecommendation] plan provider call failed', { code, runId: rid, attempt, error: err?.message });
863
+ }), { code, rid, stage: 'plan', attempt, budget });
864
+ } catch {
789
865
  lastIssues = [];
790
866
  if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } });
791
867
  continue;
@@ -987,6 +1063,9 @@ async function recordTriageAdherence({ code, entries, patientRecordId, priorReso
987
1063
  }
988
1064
 
989
1065
  module.exports = {
1066
+ recordSettleEvent,
1067
+ backoffSchedule,
1068
+ settleLossIsCritical,
990
1069
  handleTriageCompleted,
991
1070
  generateTriageRecommendations,
992
1071
  };
@@ -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,
@@ -7,7 +7,6 @@ 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_STATUSES = ['open', 'documenting', 'draft_ready'];
11
10
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
12
11
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
13
12
 
@@ -84,7 +83,6 @@ const escalationReviewSchema = new mongoose.Schema({
84
83
  'indications_queued',
85
84
  'indications_sent',
86
85
  'closed',
87
- 'cancelled',
88
86
  ],
89
87
  default: 'open',
90
88
  },
@@ -102,7 +100,6 @@ const escalationReviewSchema = new mongoose.Schema({
102
100
 
103
101
  escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
104
102
  escalationReviewSchema.index({ activeCaseKey: 1 }, { unique: true, sparse: true });
105
- escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
106
103
 
107
104
  const getEscalationReview = () => {
108
105
  const dbName = getModelDatabase('EscalationReview');
@@ -113,7 +110,6 @@ const getEscalationReview = () => {
113
110
 
114
111
  module.exports = {
115
112
  CALL_OUTCOMES,
116
- CANCELLABLE_STATUSES,
117
113
  DECISION_SOURCES,
118
114
  DOCTOR_DECISIONS,
119
115
  HANDOFF_MODES,
@@ -126,7 +126,6 @@ const escalationReviewRouteDefinitions = {
126
126
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
127
127
  'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
128
128
  'POST /:id/close': 'closeEscalationReviewController',
129
- 'POST /:id/cancel': 'cancelEscalationReviewController',
130
129
  'POST /:id/case-sync': 'syncEscalationReviewCaseController'
131
130
  };
132
131
 
@@ -286,7 +285,6 @@ const builtInControllers = {
286
285
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
287
286
  sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
288
287
  closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
289
- cancelEscalationReviewController: escalationReviewController.cancelEscalationReviewController,
290
288
  syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
291
289
  };
292
290
 
@@ -6,7 +6,6 @@ const { logger } = require('../utils/logger');
6
6
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
7
  const {
8
8
  CALL_OUTCOMES,
9
- CANCELLABLE_STATUSES,
10
9
  DECISION_SOURCES,
11
10
  DOCTOR_DECISIONS,
12
11
  HANDOFF_MODES,
@@ -249,24 +248,6 @@ const deliveryTransport = (message, result) => {
249
248
  return result.deferred ? 'template_recovery' : 'text';
250
249
  };
251
250
 
252
- let indexesReady = new WeakMap();
253
-
254
- function ensureActiveReviewIndex(EscalationReview) {
255
- const pending = indexesReady.get(EscalationReview);
256
- if (pending) return pending;
257
-
258
- const building = EscalationReview.ensureIndexes().catch((error) => {
259
- indexesReady.delete(EscalationReview);
260
- if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
261
- logger.error('[EscalationReview] A uniqueness index could not be built', { error: redactedError(error) });
262
- throw httpError(409, 'Escalation reviews cannot be opened: a uniqueness index could not be built. The server log names the index and the conflict; resolve it and retry.');
263
- });
264
- indexesReady.set(EscalationReview, building);
265
- return building;
266
- }
267
-
268
- const _resetEscalationReviewIndexes = () => { indexesReady = new WeakMap(); };
269
-
270
251
  async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
271
252
  const patientCode = patientCodeOf(code);
272
253
  const operator = requiredText(openedBy, 'openedBy');
@@ -283,14 +264,14 @@ async function openEscalationReview({ code, patientCaseRecordId = null, openedBy
283
264
  }
284
265
 
285
266
  const EscalationReview = getEscalationReview();
286
- await ensureActiveReviewIndex(EscalationReview);
267
+ await EscalationReview.init();
287
268
  let review;
288
269
  try {
289
270
  review = (await EscalationReview.create(fields)).toObject();
290
271
  } catch (error) {
291
- if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
292
- const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
293
- if (!existing) throw httpError(409, 'A closed review still holds this patient case; try again in a moment');
272
+ if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
273
+ const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
274
+ if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
294
275
  return { review: existing, created: false };
295
276
  }
296
277
  await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
@@ -543,17 +524,6 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
543
524
  return syncCase(review, operator, requestId);
544
525
  }
545
526
 
546
- async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
547
- const reviewId = reviewIdOf(id);
548
- const operator = requiredText(cancelledBy, 'cancelledBy');
549
- const review = await updateReview(reviewId, CANCELLABLE_STATUSES, {
550
- $set: { status: 'cancelled', closedBy: operator, closedAt: new Date() },
551
- $unset: { activeCaseKey: '' },
552
- });
553
- await audit(review, operator, requestId, { action: 'cancelled', reason: optionalText(reason) });
554
- return review;
555
- }
556
-
557
527
  async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
558
528
  const reviewId = reviewIdOf(id);
559
529
  const operator = requiredText(syncedBy, 'syncedBy');
@@ -561,10 +531,8 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
561
531
  }
562
532
 
563
533
  module.exports = {
564
- _resetEscalationReviewIndexes,
565
534
  addCallLog,
566
535
  addDraft,
567
- cancelEscalationReview,
568
536
  closeEscalationReview,
569
537
  getEscalationReviewById,
570
538
  handOffToDoctor,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.52.0-dev.7663",
3
+ "version": "5.52.0-dev.7684",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",