@peopl-health/nexus 5.74.0 → 5.74.1

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.
@@ -1,4 +1,5 @@
1
1
  const PENDING_INSTRUCTION_WINDOW_MS = 2 * 60 * 1000;
2
2
  const DEFAULT_INSTRUCTION_SETTLE_MS = 2500;
3
+ const DUPLICATE_INSTRUCTION_WINDOW_MS = 60 * 60 * 1000;
3
4
 
4
- module.exports = { PENDING_INSTRUCTION_WINDOW_MS, DEFAULT_INSTRUCTION_SETTLE_MS };
5
+ module.exports = { PENDING_INSTRUCTION_WINDOW_MS, DEFAULT_INSTRUCTION_SETTLE_MS, DUPLICATE_INSTRUCTION_WINDOW_MS };
@@ -1,5 +1,6 @@
1
1
  const { Config_ID } = require('../config/airtableConfig');
2
2
  const runtimeConfig = require('../config/runtimeConfig');
3
+ const { DUPLICATE_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig');
3
4
 
4
5
  const { logger } = require('../utils/logger');
5
6
  const { isArchivedPatientCode } = require('../helpers/twilioHelper');
@@ -62,7 +63,10 @@ const addInsAssistantController = async (req, res) => {
62
63
  if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
63
64
 
64
65
  try {
65
- await processInstruction(code, instruction, 'developer', { triggeredBy });
66
+ const result = await processInstruction(code, instruction, 'developer', { triggeredBy, dedupeWithinMs: DUPLICATE_INSTRUCTION_WINDOW_MS });
67
+ if (result?.outcome === 'duplicate') {
68
+ return res.status(200).json({ success: true, duplicate: true, message: 'Instruction already answered' });
69
+ }
66
70
  return res.status(200).json({ success: true, message: 'Instruction added to assistant' });
67
71
  } catch (error) {
68
72
  logger.error('[AssistantController] Add instruction error', { error: error.message, code });
@@ -843,7 +843,11 @@ class NexusMessaging {
843
843
  * batch, and is marked processed when vetoed or refused by a draining instance, so it can only ever
844
844
  * run behind its own gate.
845
845
  */
846
- async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null } = {}) {
846
+ async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0 } = {}) {
847
+ if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs)) {
848
+ logger.info('[processInstruction] Identical instruction already answered; skipping the resend', { code, triggeredBy: triggeredBy || null });
849
+ return { outcome: 'duplicate' };
850
+ }
847
851
  const receivedAt = Date.now();
848
852
  const messageData = {
849
853
  pushName: 'Instruction',
@@ -880,12 +884,14 @@ class NexusMessaging {
880
884
  let runId = null;
881
885
  let gate = null;
882
886
  let alreadyAnswered = false;
887
+ let duplicate = false;
883
888
  const answerPending = () => {
884
889
  batchIds = [];
885
890
  outcome = null;
886
891
  runId = null;
887
892
  gate = null;
888
893
  alreadyAnswered = false;
894
+ duplicate = false;
889
895
  return this._executeWithPipeline(code, 'instruction', 'queue',
890
896
  async (preProcessResult, shouldContinue, currentRunId) => {
891
897
  runId = currentRunId;
@@ -901,6 +907,12 @@ class NexusMessaging {
901
907
  return null;
902
908
  }
903
909
  }
910
+ if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id)) {
911
+ logger.info('[processInstruction] Identical instruction answered while this one waited; skipping it', { code, triggeredBy: triggeredBy || null });
912
+ duplicate = true;
913
+ await markOwnProcessed();
914
+ return null;
915
+ }
904
916
  const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
905
917
  if (!batch.length) {
906
918
  logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
@@ -956,6 +968,7 @@ class NexusMessaging {
956
968
  // Only the send outcome goes back: the turn's output was already delivered, and handing it to
957
969
  // the caller would invite a second send.
958
970
  if (gate) return gate;
971
+ if (duplicate) return { outcome: 'duplicate' };
959
972
  return { outcome: outcome === null && alreadyAnswered ? 'already_answered' : outcome };
960
973
  },
961
974
  );
@@ -964,6 +977,28 @@ class NexusMessaging {
964
977
  }
965
978
  }
966
979
 
980
+ async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null) {
981
+ try {
982
+ const rows = await getMessages(
983
+ {
984
+ numero: code,
985
+ origin: 'instruction',
986
+ message_id: /^instruction_/,
987
+ plainBody: instruction,
988
+ processed: true,
989
+ 'raw.gated': { $ne: true },
990
+ createdAt: { $gte: new Date(Date.now() - windowMs) },
991
+ ...(ownId ? { _id: { $ne: ownId } } : {}),
992
+ },
993
+ { sort: { _id: -1 }, limit: 1, select: '_id' },
994
+ );
995
+ return Array.isArray(rows) && rows.length > 0;
996
+ } catch (err) {
997
+ logger.error('[processInstruction] Could not check for an answered duplicate', { error: err.message, code });
998
+ return false;
999
+ }
1000
+ }
1001
+
967
1002
  async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
968
1003
  if (!ownId) return [{ _id: null, body: ownBody }];
969
1004
  try {
package/lib/index.d.ts CHANGED
@@ -272,7 +272,7 @@ declare module '@peopl-health/nexus' {
272
272
  getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
273
273
  initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
274
274
  getWorkflowRunner(): WorkflowRunner;
275
- processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
275
+ processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
276
276
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
277
277
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
278
278
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.74.0",
3
+ "version": "5.74.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",