@peopl-health/nexus 5.59.5 → 5.59.6

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.
@@ -439,4 +439,4 @@ class AssistantProcessor {
439
439
  }
440
440
  }
441
441
 
442
- module.exports = { AssistantProcessor };
442
+ module.exports = { AssistantProcessor, deliveryOutcome };
@@ -32,6 +32,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
32
32
  const { BatchingManager } = require('../core/BatchingManager');
33
33
  const { ProcessingPipeline } = require('../core/ProcessingPipeline');
34
34
  const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
35
+ const { deliveryOutcome } = require('../clinical/AssistantProcessor');
35
36
  const { UNASSIGNED, alertOpsForClaimedMessage, coverIfUnassigned, coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
36
37
  const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
37
38
  const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
@@ -52,6 +53,8 @@ const { invokeInteractiveRoute } = require('./interactiveRouteService');
52
53
 
53
54
  const { PhiProcessor } = require('./PhiProcessor');
54
55
 
56
+ const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
57
+
55
58
  const unbatchedRoutes = {
56
59
  __proto__: null,
57
60
  flow: 'handleFlow',
@@ -695,7 +698,7 @@ class NexusMessaging {
695
698
  * PROCESSING PIPELINE
696
699
  */
697
700
 
698
- async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true } = {}) {
701
+ async _executeWithPipeline(chatId, type, mode, executeFn, { sendResponse = true, onSent = null } = {}) {
699
702
  let capturedResult = null;
700
703
  const discardResponseFn = async (result) => {
701
704
  await this.assistantProcessor.discardResponse(chatId, result);
@@ -719,6 +722,7 @@ class NexusMessaging {
719
722
  return;
720
723
  }
721
724
  await this.assistantProcessor.sendResponse(chatId, result);
725
+ if (onSent && result?.delivery && deliveryOutcome(result.delivery) !== 'known_not_sent') await onSent(result);
722
726
  };
723
727
 
724
728
  const admission = mode === 'queue'
@@ -823,32 +827,67 @@ class NexusMessaging {
823
827
  messageData,
824
828
  this._saveMessageFn,
825
829
  async ({ body, _id }) => {
830
+ let answered = [];
826
831
  const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
827
- async (preProcessResult, shouldContinue, runId) => this.assistantProcessor.process({
828
- code,
829
- runOptions: {
830
- prePromptResult: preProcessResult,
831
- additionalInstructions: body,
832
- toolChoice: 'none',
833
- turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
834
- runId,
835
- shouldContinue,
836
- signal: this.batchingManager.getAbortSignal(runId),
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
837
  }
838
- }),
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
+ },
839
863
  );
840
- if (_id) {
841
- try {
842
- await updateMessage({ _id }, { $set: { processed: true } });
843
- } catch (err) {
844
- logger.error('[processInstruction] Could not mark instruction processed', { error: err.message, code });
845
- }
846
- }
847
864
  return runResult;
848
865
  },
849
866
  );
850
867
  }
851
868
 
869
+ async _pendingInstructionBatch(code, ownId, ownBody) {
870
+ if (!ownId) return [{ _id: null, body: ownBody }];
871
+ try {
872
+ const rows = await getMessages(
873
+ {
874
+ numero: code,
875
+ origin: 'instruction',
876
+ message_id: /^instruction_/,
877
+ $or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(Date.now() - PENDING_INSTRUCTION_WINDOW_MS) } }],
878
+ },
879
+ { sort: { _id: 1 }, select: '_id body processed' },
880
+ );
881
+ const own = rows.find(m => String(m._id) === String(ownId));
882
+ if (own?.processed) return [];
883
+ const batch = rows.filter(m => m === own || !m.processed).map(m => (m === own ? { _id: ownId, body: ownBody } : m));
884
+ return own ? batch : [...batch, { _id: ownId, body: ownBody }];
885
+ } catch (err) {
886
+ logger.error('[processInstruction] Could not read pending instructions', { error: err.message, code });
887
+ return [{ _id: ownId, body: ownBody }];
888
+ }
889
+ }
890
+
852
891
  /*
853
892
  * A turn nobody asked for: no inbound message, and no obligation to produce an outbound.
854
893
  * Unlike processInstruction this keeps the full clinical toolset and lets the agent end in a hold,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.5",
3
+ "version": "5.59.6",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",