@peopl-health/nexus 5.59.7 → 5.59.9

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.
@@ -17,6 +17,7 @@ const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
17
17
  const { getRecordByFilter } = require('../../services/airtableService');
18
18
  const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
19
19
  const { getMessages, countMessages } = require('../../services/messageService');
20
+ const { hasInstructionInFlight } = require('../../services/instructionInFlightService');
20
21
  const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
21
22
  const { CURRENT_TURN } = require('../promptPlacement');
22
23
 
@@ -40,6 +41,8 @@ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
40
41
 
41
42
  const inline = (value) => sanitizeInlineText(value, Infinity);
42
43
 
44
+ const PENDING_INSTRUCTION_NOTE = `${OPERATOR_TURN_PREFIX} Hay un mensaje del sistema en curso para el paciente (por ejemplo, la confirmación de los botones que acaba de tocar) que se le enviará por separado. No lo anticipes ni lo confirmes tú; responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
45
+
43
46
  const deliveredWhileWaitingNote = (text) =>
44
47
  `${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
45
48
 
@@ -130,6 +133,10 @@ class DefaultMemoryManager extends MemoryManager {
130
133
  }
131
134
  }
132
135
 
136
+ if (this._hasPendingInstruction(thread.code, beforeCheckpoint, config)) {
137
+ context.push({ [CURRENT_TURN]: true, role: 'user', content: PENDING_INSTRUCTION_NOTE, type: 'message' });
138
+ }
139
+
133
140
  return [...context, ...additional];
134
141
  } catch (error) {
135
142
  logger.error('[DefaultMemoryManager] Context building failed', { threadCode: thread.code, error: error.message });
@@ -137,6 +144,10 @@ class DefaultMemoryManager extends MemoryManager {
137
144
  }
138
145
  }
139
146
 
147
+ _hasPendingInstruction(code, beforeCheckpoint, config) {
148
+ return Boolean(beforeCheckpoint) && !config.beforeCheckpoint && hasInstructionInFlight(code);
149
+ }
150
+
140
151
  async _outboundTail(code, beforeCheckpoint, config) {
141
152
  const upperBound = config.tailUpperBound ?? (config.beforeCheckpoint ? null : new Date());
142
153
  if (!beforeCheckpoint || !upperBound) return [];
@@ -0,0 +1,4 @@
1
+ const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
2
+ const DEFAULT_INSTRUCTION_SETTLE_MS = 2500;
3
+
4
+ module.exports = { PENDING_INSTRUCTION_WINDOW_MS, DEFAULT_INSTRUCTION_SETTLE_MS };
@@ -63,6 +63,10 @@ class BatchingManager {
63
63
  return (current === undefined || current === runId) && !this.abandonedRuns.has(runId);
64
64
  }
65
65
 
66
+ isAbandoned(runId) {
67
+ return this.abandonedRuns.has(runId);
68
+ }
69
+
66
70
  getAbortSignal(runId) {
67
71
  return this.abortControllers.get(runId)?.signal;
68
72
  }
@@ -4,6 +4,7 @@ const { airtable } = require('../config/airtableConfig');
4
4
  const { connect } = require('../config/mongoConfig');
5
5
  const { setMetaConfig } = require('../config/metaConfig');
6
6
  const runtimeConfig = require('../config/runtimeConfig');
7
+ const { DEFAULT_INSTRUCTION_SETTLE_MS, PENDING_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig');
7
8
  const { decodeUnicodeEscapes, decodeUnicodeEscapesDeep } = require('../utils/sanitizerUtils');
8
9
  const { runInShadowScope } = require('../utils/shadowScope');
9
10
 
@@ -26,6 +27,7 @@ const { ensureThreadExists } = require('../services/threadService');
26
27
 
27
28
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
28
29
  const { getMessages, updateMessage } = require('../services/messageService');
30
+ const { beginInstruction, endInstruction } = require('../services/instructionInFlightService');
29
31
  const { QueueReconciliationService } = require('../services/queueReconciliationService');
30
32
  const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMessageService');
31
33
 
@@ -53,8 +55,6 @@ const { invokeInteractiveRoute } = require('./interactiveRouteService');
53
55
 
54
56
  const { PhiProcessor } = require('./PhiProcessor');
55
57
 
56
- const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
57
-
58
58
  const unbatchedRoutes = {
59
59
  __proto__: null,
60
60
  flow: 'handleFlow',
@@ -113,6 +113,7 @@ class NexusMessaging {
113
113
  abortOnNewMessage: config.messageBatching?.abortOnNewMessage ?? true,
114
114
  immediateRestart: config.messageBatching?.immediateRestart ?? true,
115
115
  typingIndicator: config.messageBatching?.typingIndicator ?? false,
116
+ instructionSettleMs: config.messageBatching?.instructionSettleMs ?? DEFAULT_INSTRUCTION_SETTLE_MS,
116
117
  hooks: config.messageBatching?.hooks || {},
117
118
  };
118
119
 
@@ -698,7 +699,7 @@ class NexusMessaging {
698
699
  * PROCESSING PIPELINE
699
700
  */
700
701
 
701
- async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSent = null } = {}) {
702
+ async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSendSettled = null } = {}) {
702
703
  let capturedResult = null;
703
704
  const discardResponseFn = async (result) => {
704
705
  await this.assistantProcessor.discardResponse(chatId, result);
@@ -721,8 +722,13 @@ class NexusMessaging {
721
722
  await discardResponseFn(result);
722
723
  return;
723
724
  }
724
- await this.assistantProcessor.sendResponse(chatId, result);
725
- if (onSent && result?.delivery && deliveryOutcome(result.delivery) !== 'known_not_sent') await onSent(result);
725
+ try {
726
+ await this.assistantProcessor.sendResponse(chatId, result);
727
+ } catch (error) {
728
+ await onSendSettled?.('threw');
729
+ throw error;
730
+ }
731
+ await onSendSettled?.(result?.delivery ? deliveryOutcome(result.delivery) : 'not_sent');
726
732
  };
727
733
 
728
734
  const admission = mode === 'queue'
@@ -810,6 +816,7 @@ class NexusMessaging {
810
816
  }
811
817
 
812
818
  async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
819
+ const receivedAt = Date.now();
813
820
  const messageData = {
814
821
  pushName: 'Instruction',
815
822
  code,
@@ -823,50 +830,77 @@ class NexusMessaging {
823
830
  silent: true,
824
831
  };
825
832
 
826
- await this.phiProcessor.inData(
827
- messageData,
828
- this._saveMessageFn,
829
- async ({ body, _id }) => {
830
- let answered = [];
831
- const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
832
- async (preProcessResult, shouldContinue, runId) => {
833
- const batch = await this._pendingInstructionBatch(code, _id, body);
834
- if (!batch.length) {
835
- logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
836
- return null;
837
- }
838
- const result = await this.assistantProcessor.process({
839
- code,
840
- runOptions: {
841
- prePromptResult: preProcessResult,
842
- additionalInstructions: batch.map(m => m.body).join('\n\n'),
843
- toolChoice: 'none',
844
- turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
845
- runId,
846
- shouldContinue,
847
- signal: this.batchingManager.getAbortSignal(runId),
848
- }
849
- });
850
- answered = batch.map(m => m._id).filter(Boolean);
851
- return result;
852
- },
853
- {
854
- onSent: async () => {
855
- if (!answered.length) return;
856
- try {
857
- await updateMessage({ _id: { $in: answered } }, { $set: { processed: true } });
858
- } catch (err) {
859
- logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
860
- }
861
- },
862
- },
863
- );
864
- return runResult;
865
- },
866
- );
833
+ beginInstruction(code);
834
+ try {
835
+ await this.phiProcessor.inData(
836
+ messageData,
837
+ this._saveMessageFn,
838
+ async ({ body, _id }) => {
839
+ if (this.batchingConfig.instructionSettleMs > 0 && !this.batchingManager.isDraining()) {
840
+ await new Promise(resolve => setTimeout(resolve, this.batchingConfig.instructionSettleMs));
841
+ }
842
+ let batchIds = [];
843
+ let outcome = null;
844
+ let runId = null;
845
+ const answerPending = () => {
846
+ batchIds = [];
847
+ outcome = null;
848
+ runId = null;
849
+ return this._executeWithPipeline(code, 'instruction', 'queue',
850
+ async (preProcessResult, shouldContinue, currentRunId) => {
851
+ runId = currentRunId;
852
+ const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
853
+ if (!batch.length) {
854
+ logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
855
+ return null;
856
+ }
857
+ batchIds = batch.map(m => m._id).filter(Boolean);
858
+ return this.assistantProcessor.process({
859
+ code,
860
+ runOptions: {
861
+ prePromptResult: preProcessResult,
862
+ additionalInstructions: batch.map(m => m.body).join('\n\n'),
863
+ toolChoice: 'none',
864
+ turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
865
+ runId,
866
+ shouldContinue,
867
+ signal: this.batchingManager.getAbortSignal(runId),
868
+ }
869
+ });
870
+ },
871
+ {
872
+ onSendSettled: async (settled) => {
873
+ outcome = settled;
874
+ if (!batchIds.length || (settled !== 'sent' && settled !== 'unknown')) return;
875
+ try {
876
+ await updateMessage({ _id: { $in: batchIds } }, { $set: { processed: true } });
877
+ } catch (err) {
878
+ logger.error('[processInstruction] Could not mark instructions processed', { error: err.message, code });
879
+ }
880
+ },
881
+ },
882
+ );
883
+ };
884
+ const needsAnotherTurn = () => batchIds.length > 0
885
+ && ((outcome === null && this.batchingManager.isAbandoned(runId)) || outcome === 'known_not_sent');
886
+
887
+ let runResult = await answerPending();
888
+ if (needsAnotherTurn()) {
889
+ logger.warn('[processInstruction] Instruction reply was not sent; queueing one more turn', { code, outcome });
890
+ runResult = await answerPending();
891
+ }
892
+ if (batchIds.length && outcome !== 'sent' && outcome !== 'unknown') {
893
+ logger.error('[processInstruction] Instruction left unanswered', { code, outcome, instructionIds: batchIds.map(String) });
894
+ }
895
+ return runResult;
896
+ },
897
+ );
898
+ } finally {
899
+ endInstruction(code);
900
+ }
867
901
  }
868
902
 
869
- async _pendingInstructionBatch(code, ownId, ownBody) {
903
+ async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
870
904
  if (!ownId) return [{ _id: null, body: ownBody }];
871
905
  try {
872
906
  const rows = await getMessages(
@@ -874,7 +908,7 @@ class NexusMessaging {
874
908
  numero: code,
875
909
  origin: 'instruction',
876
910
  message_id: /^instruction_/,
877
- $or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(Date.now() - PENDING_INSTRUCTION_WINDOW_MS) } }],
911
+ $or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
878
912
  },
879
913
  { sort: { _id: 1 }, select: '_id body processed' },
880
914
  );
package/lib/index.d.ts CHANGED
@@ -924,6 +924,7 @@ declare module '@peopl-health/nexus' {
924
924
  abortOnNewMessage?: boolean;
925
925
  immediateRestart?: boolean;
926
926
  typingIndicator?: boolean;
927
+ instructionSettleMs?: number;
927
928
  hooks?: Record<string, Function | Function[]>;
928
929
  }
929
930
 
@@ -86,32 +86,12 @@ const audit = (review, updatedBy, requestId, changes) => logPatientChange({
86
86
  changes: { escalationReviewId: String(review._id), ...changes },
87
87
  });
88
88
 
89
- async function pauseAssistantFor(patientCode) {
90
- try {
91
- const result = await switchThreadStoppedStatus(patientCode, true, { byOperator: true });
92
- return Boolean(result?.modifiedCount);
93
- } catch (error) {
94
- logger.error('[EscalationReview] The assistant could not be paused for this patient', { error: error.message });
95
- return false;
96
- }
97
- }
98
-
99
- const passPauseToOpenReview = (review) => getEscalationReview().findOneAndUpdate(
100
- { patientCode: review.patientCode, closedAt: null, _id: { $ne: review._id } },
101
- { $set: { assistantPausedByReview: true } },
102
- ).lean();
103
-
104
89
  async function resumeAssistant(review, operator = null, requestId = null) {
105
90
  if (review.assistantPausedByReview !== true) return review;
106
91
  const stopClaiming = () => getEscalationReview()
107
92
  .updateOne({ _id: review._id }, { $set: { assistantPausedByReview: false } });
108
93
  try {
109
- if (!await passPauseToOpenReview(review)) {
110
- await switchThreadStoppedStatus(review.patientCode, false);
111
- if (await passPauseToOpenReview(review)) {
112
- await switchThreadStoppedStatus(review.patientCode, true, { byOperator: true });
113
- }
114
- }
94
+ await switchThreadStoppedStatus(review.patientCode, false);
115
95
  await stopClaiming();
116
96
  return { ...review, assistantPausedByReview: false };
117
97
  } catch (error) {
@@ -481,10 +461,7 @@ async function openEscalationReview({
481
461
  if (!patient) throw httpError(404, 'Patient not found');
482
462
 
483
463
  const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
484
- const pausedHere = await pauseAssistantFor(patientCode);
485
- const fields = {
486
- patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: pausedHere,
487
- };
464
+ const fields = { patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: false };
488
465
 
489
466
  const EscalationReview = getEscalationReview();
490
467
  let review;
@@ -492,19 +469,9 @@ async function openEscalationReview({
492
469
  await ensureActiveReviewIndex(EscalationReview);
493
470
  review = (await EscalationReview.create(fields)).toObject();
494
471
  } catch (error) {
495
- if (error?.code !== DUPLICATE_KEY_ERROR) {
496
- if (pausedHere) {
497
- await switchThreadStoppedStatus(patientCode, false).catch((resumeError) => {
498
- logger.error('[EscalationReview] A failed open left the assistant paused', {
499
- error: resumeError.message,
500
- });
501
- });
502
- }
503
- throw error;
504
- }
472
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
505
473
  let existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
506
474
  if (!existing) {
507
- if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
508
475
  throw httpError(409, 'This patient already has a review being opened; try again in a moment');
509
476
  }
510
477
  if (recordIds.length && !(existing.patientCaseRecordIds ?? []).length) {
@@ -519,29 +486,13 @@ async function openEscalationReview({
519
486
  } else {
520
487
  const fresh = await EscalationReview.findOne({ _id: existing._id, closedAt: null }).lean();
521
488
  if (!fresh) {
522
- if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
523
489
  throw httpError(409, 'The review closed while this one was being opened; try again');
524
490
  }
525
491
  existing = fresh;
526
492
  }
527
493
  }
528
- if (pausedHere && existing.assistantPausedByReview !== true) {
529
- try {
530
- await EscalationReview.updateOne({ _id: existing._id }, { $set: { assistantPausedByReview: true } });
531
- existing.assistantPausedByReview = true;
532
- } catch (error) {
533
- logger.error('[EscalationReview] The pause was not recorded against the open review', {
534
- escalationReviewId: String(existing._id), error: error.message,
535
- });
536
- }
537
- }
538
494
  return { review: existing, created: false };
539
495
  }
540
- const held = pausedHere || await pauseAssistantFor(patientCode);
541
- if (held !== review.assistantPausedByReview) {
542
- await EscalationReview.updateOne({ _id: review._id }, { $set: { assistantPausedByReview: held } });
543
- review.assistantPausedByReview = held;
544
- }
545
496
  await audit(review, operator, requestId, { action: 'opened', patientCaseRecordIds: recordIds });
546
497
  return { review, created: true };
547
498
  }
@@ -0,0 +1,17 @@
1
+ const inFlight = new Map();
2
+
3
+ function beginInstruction(code) {
4
+ inFlight.set(code, (inFlight.get(code) || 0) + 1);
5
+ }
6
+
7
+ function endInstruction(code) {
8
+ const remaining = (inFlight.get(code) || 0) - 1;
9
+ if (remaining > 0) inFlight.set(code, remaining);
10
+ else inFlight.delete(code);
11
+ }
12
+
13
+ function hasInstructionInFlight(code) {
14
+ return inFlight.has(code);
15
+ }
16
+
17
+ module.exports = { beginInstruction, endInstruction, hasInstructionInFlight };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.7",
3
+ "version": "5.59.9",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",