@peopl-health/nexus 5.59.8 → 5.60.0-dev.11092

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.
@@ -26,6 +26,7 @@ class TwilioMessageAdapter extends MessageAdapter {
26
26
  processed: false,
27
27
  pushName: rawMessage.ProfileName || null,
28
28
  body,
29
+ normalizedContent: contactBody ? { type: 'extracted_contact', text: contactBody } : null,
29
30
  media,
30
31
  interactive,
31
32
  quotedMessageId: rawMessage.OriginalRepliedMessageSid || null,
@@ -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,32 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const { clinicalConnection } = require('../config/connection');
4
+
5
+ const clinicalSourceEventSchema = new mongoose.Schema({
6
+ _id: { type: String, required: true },
7
+ tenantId: { type: String, required: true, immutable: true },
8
+ sourceSystem: { type: String, required: true, immutable: true },
9
+ sourceRecordId: { type: String, required: true, immutable: true },
10
+ sourceRevision: { type: String, required: true, immutable: true },
11
+ sourceMessageId: { type: String, default: null, immutable: true },
12
+ patientId: { type: String, default: null, immutable: true },
13
+ identity: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
14
+ actor: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
15
+ experiencer: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
16
+ validTime: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
17
+ recordTime: { type: Date, required: true, immutable: true },
18
+ evidenceRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
19
+ artifactRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
20
+ normalizedContent: { type: mongoose.Schema.Types.Mixed, default: null, immutable: true },
21
+ payload: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
22
+ schemaVersion: { type: String, required: true, immutable: true },
23
+ policyVersion: { type: String, default: null, immutable: true },
24
+ }, { versionKey: false, autoCreate: false, autoIndex: false });
25
+
26
+ function getClinicalSourceEventModel() {
27
+ const connection = clinicalConnection();
28
+ return connection.models.ClinicalSourceEvent
29
+ || connection.model('ClinicalSourceEvent', clinicalSourceEventSchema, 'clinicalSourceEvent');
30
+ }
31
+
32
+ module.exports = { getClinicalSourceEventModel, clinicalSourceEventSchema };
@@ -0,0 +1,132 @@
1
+ const { createHash } = require('crypto');
2
+
3
+ class ClinicalSourceError extends Error {
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = 'ClinicalSourceError';
7
+ this.code = code;
8
+ }
9
+ }
10
+
11
+ function invalidSource() {
12
+ return new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
13
+ }
14
+
15
+ function isStableId(value) {
16
+ return typeof value === 'string' && value.length > 0 && value.trim() === value;
17
+ }
18
+
19
+ // JSON only: reject values that would silently disappear or change during persistence.
20
+ function canonical(value, ancestors = new Set()) {
21
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
22
+ if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
23
+ if (typeof value !== 'object' || ancestors.has(value)) throw invalidSource();
24
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw invalidSource();
25
+ ancestors.add(value);
26
+ const result = Array.isArray(value)
27
+ ? '[' + Array.from(value, item => canonical(item, ancestors)).join(',') + ']'
28
+ : '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key], ancestors)).join(',') + '}';
29
+ ancestors.delete(value);
30
+ return result;
31
+ }
32
+
33
+ function validateClinicalSourceEvent(envelope) {
34
+ if (!envelope || typeof envelope !== 'object') throw invalidSource();
35
+ for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'schemaVersion']) {
36
+ if (!isStableId(envelope[field])) throw invalidSource();
37
+ }
38
+ if (envelope.sourceMessageId != null && !isStableId(envelope.sourceMessageId)) throw invalidSource();
39
+ if (envelope.patientId !== null && !isStableId(envelope.patientId)) throw invalidSource();
40
+ if (!['unknown', 'ambiguous', 'resolved'].includes(envelope.identity?.status) || !Array.isArray(envelope.identity.sourceRefs)) throw invalidSource();
41
+ if ((envelope.patientId !== null) !== (envelope.identity.status === 'resolved')) throw invalidSource();
42
+ for (const field of ['actor', 'experiencer', 'payload']) {
43
+ if (!envelope[field] || typeof envelope[field] !== 'object' || Array.isArray(envelope[field])) throw invalidSource();
44
+ }
45
+ if (!Array.isArray(envelope.evidenceRefs)) throw invalidSource();
46
+ const artifactRefs = envelope.artifactRefs === undefined ? [] : envelope.artifactRefs;
47
+ if (!Array.isArray(artifactRefs)) throw invalidSource();
48
+ const attachmentIndexes = new Set();
49
+ for (const ref of artifactRefs) {
50
+ if (!ref || typeof ref !== 'object' || Array.isArray(ref)
51
+ || Object.keys(ref).some(key => !['attachmentIndex', 'bucket', 'key'].includes(key))
52
+ || !Number.isSafeInteger(ref.attachmentIndex) || ref.attachmentIndex < 0
53
+ || attachmentIndexes.has(ref.attachmentIndex) || !isStableId(ref.bucket) || !isStableId(ref.key)) throw invalidSource();
54
+ attachmentIndexes.add(ref.attachmentIndex);
55
+ }
56
+ const normalizedContent = envelope.normalizedContent ?? null;
57
+ if (normalizedContent !== null && (typeof normalizedContent !== 'object' || Array.isArray(normalizedContent)
58
+ || Object.keys(normalizedContent).some(key => !['type', 'text'].includes(key))
59
+ || normalizedContent.type !== 'extracted_contact' || typeof normalizedContent.text !== 'string'
60
+ || !normalizedContent.text.trim())) throw invalidSource();
61
+ if (!['known', 'unknown'].includes(envelope.validTime?.status)) throw invalidSource();
62
+ if (envelope.validTime.status === 'known' && (typeof envelope.validTime.at !== 'string' || !Number.isFinite(Date.parse(envelope.validTime.at)))) throw invalidSource();
63
+ if (envelope.validTime.status === 'unknown' && envelope.validTime.at != null) throw invalidSource();
64
+ if (envelope.policyVersion !== null && !isStableId(envelope.policyVersion)) throw invalidSource();
65
+ const document = {};
66
+ for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'patientId', 'identity', 'actor', 'experiencer', 'validTime', 'evidenceRefs', 'payload', 'schemaVersion', 'policyVersion']) document[field] = envelope[field];
67
+ document.sourceMessageId = envelope.sourceMessageId ?? null;
68
+ document.artifactRefs = artifactRefs;
69
+ document.normalizedContent = normalizedContent;
70
+ return JSON.parse(canonical(document));
71
+ }
72
+
73
+ function sourceFingerprint(document) {
74
+ // Identity adjudication, policy selection, capture artifacts and observation time are not source revisions.
75
+ const omitted = new Set(['artifactRefs', 'normalizedContent', 'patientId', 'identity', 'policyVersion', 'recordTime', '_id']);
76
+ const source = Object.fromEntries(Object.entries(document).filter(([key]) => !omitted.has(key)));
77
+ return canonical({ ...source, identitySourceRefs: document.identity.sourceRefs });
78
+ }
79
+
80
+ function persistenceClassification(stage, error) {
81
+ if (stage === 'unacknowledged') return 'unacknowledged';
82
+ if (stage === 'missing_duplicate') return 'not_found';
83
+ if ([50, 64].includes(error?.code) || error?.name === 'MongoNetworkTimeoutError') return 'timeout';
84
+ if ([13, 18].includes(error?.code)) return 'authorization';
85
+ if ([6, 7, 89, 91].includes(error?.code)
86
+ || ['MongoNetworkError', 'MongoServerSelectionError'].includes(error?.name)) return 'unavailable';
87
+ return 'unknown';
88
+ }
89
+
90
+ async function ingestClinicalSourceEvent(envelope) {
91
+ const document = validateClinicalSourceEvent(envelope);
92
+ const eventId = createHash('sha256').update(JSON.stringify([
93
+ document.tenantId, document.sourceSystem, document.sourceRecordId, document.sourceRevision,
94
+ ])).digest('hex');
95
+ const fingerprint = sourceFingerprint(document);
96
+ let stage = 'model';
97
+ try {
98
+ const { getClinicalSourceEventModel } = require('../models/clinicalSourceEventModel');
99
+ const { collection } = getClinicalSourceEventModel();
100
+ try {
101
+ stage = 'write';
102
+ const result = await collection.insertOne({ ...document, _id: eventId, recordTime: new Date() }, { writeConcern: { w: 'majority', j: true, wtimeoutMS: 10000 } });
103
+ if (!result?.acknowledged) {
104
+ stage = 'unacknowledged';
105
+ throw new Error();
106
+ }
107
+ return { eventId, state: document.patientId === null ? 'identity_pending' : 'recorded' };
108
+ } catch (error) {
109
+ if (error.code !== 11000) throw error;
110
+ stage = 'duplicate_read';
111
+ const existing = await collection.findOne({ _id: eventId }, { readPreference: 'primary', readConcern: { level: 'majority' } });
112
+ if (!existing) {
113
+ stage = 'missing_duplicate';
114
+ throw new Error();
115
+ }
116
+ stage = 'duplicate_verify';
117
+ if (sourceFingerprint(existing) !== fingerprint) throw new ClinicalSourceError('CLINICAL_SOURCE_CONFLICT', 'Clinical source revision conflict');
118
+ return { eventId, state: 'duplicate' };
119
+ }
120
+ } catch (error) {
121
+ if (error instanceof ClinicalSourceError && error.code === 'CLINICAL_SOURCE_CONFLICT') throw error;
122
+ try {
123
+ const { logger } = require('../../utils/logger');
124
+ logger.error('[clinicalEventService] Source persistence failed', { stage, classification: persistenceClassification(stage, error) });
125
+ } catch {
126
+ // Diagnostic availability must not change the safe public failure contract.
127
+ }
128
+ throw new ClinicalSourceError('CLINICAL_SOURCE_PERSISTENCE', 'Clinical source persistence failed');
129
+ }
130
+ }
131
+
132
+ module.exports = { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError };
@@ -0,0 +1,69 @@
1
+ const { isBenchMode } = require('../../utils/benchModeHelper');
2
+ const { isShadowRun } = require('../../utils/shadowScope');
3
+ const { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError } = require('./clinicalEventService');
4
+
5
+ function pick(source, fields) {
6
+ if (!source || typeof source !== 'object') return null;
7
+ return Object.fromEntries(fields.filter(field => source[field] !== undefined).map(field => [field, source[field]]));
8
+ }
9
+
10
+ function mediaEvidence(media) {
11
+ const fields = ['key', 'bucket', 'bucketName', 'mimeType', 'mediaType', 'contentType', 'filename', 'fileName', 'fileSize', 'caption', 'url', 'size', 'sha256'];
12
+ const evidence = pick(media, fields);
13
+ if (evidence && Array.isArray(media.metadata?.attachments)) {
14
+ evidence.attachments = media.metadata.attachments.map(item => pick(item, fields));
15
+ }
16
+ return evidence;
17
+ }
18
+
19
+ function privateArtifactRefs(media) {
20
+ const attachments = Array.isArray(media?.metadata?.attachments) ? media.metadata.attachments : [];
21
+ return [media, ...attachments].flatMap((item, attachmentIndex) => {
22
+ const bucket = item?.bucketName ?? item?.bucket;
23
+ if (bucket == null || item?.key == null) return [];
24
+ return [{ attachmentIndex, bucket, key: item.key }];
25
+ });
26
+ }
27
+
28
+ function buildClinicalMessageEnvelope(values, tenantId) {
29
+ const raw = values.raw ?? {};
30
+ if (typeof raw !== 'object' || Array.isArray(raw)) throw new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
31
+ const sourceSystem = values.sourceSystem || values.sourceProvider || (raw.MessageSid ? 'twilio' : raw.key?.id ? 'baileys' : 'whatsapp_platform');
32
+ const sourceId = values.sourceRecordId ?? values.message_id;
33
+ const actorId = values.contact_code || values.sourceActorId || raw.From || raw.key?.remoteJid || values.numero || null;
34
+ const providerEvidence = pick(raw, ['MessageSid', 'SmsSid', 'OriginalRepliedMessageSid', 'Body', 'ButtonPayload', 'ButtonText', 'ListId', 'ListTitle', 'ListDescription', 'FlowData', 'InteractiveData', 'NumMedia', 'MediaUrl0', 'MediaContentType0']);
35
+ const mediaFields = Object.keys(raw).filter(key => /^Media(?:Url|ContentType)\d+$/.test(key));
36
+ Object.assign(providerEvidence, pick(raw, mediaFields));
37
+ const hasProviderMedia = mediaFields.some(key => /^MediaUrl\d+$/.test(key));
38
+ const event = {
39
+ tenantId, sourceSystem, sourceRecordId: sourceId, sourceRevision: values.sourceRevision ?? '1',
40
+ sourceMessageId: values.message_id ?? null, patientId: null,
41
+ identity: { status: 'unknown', sourceRefs: values.numero ? [{ system: 'message_transport', id: values.numero }] : [] },
42
+ actor: { type: 'transport_contact', sourceId: actorId, reportedRole: values.contact_role || null, authenticatedRole: null },
43
+ experiencer: { patientId: null, status: 'unknown' },
44
+ validTime: { status: 'unknown' },
45
+ evidenceRefs: [],
46
+ artifactRefs: privateArtifactRefs(values.media),
47
+ normalizedContent: values.normalizedContent ?? null,
48
+ payload: {
49
+ sourceTimestamp: values.sourceTimestamp ?? null,
50
+ text: typeof raw.Body === 'string' ? raw.Body : values.sourceText ?? values.plainBody ?? values.body ?? '',
51
+ interactive: pick(values.interactive_data, ['type', 'payload', 'title', 'id', 'description', 'replyId', 'flowData', 'interactiveData']) || (values.interactive_type ? { type: values.interactive_type } : null),
52
+ media: hasProviderMedia ? null : mediaEvidence(values.media),
53
+ providerEvidence,
54
+ quotedMessageId: values.quotedMessageId ?? raw.OriginalRepliedMessageSid ?? null,
55
+ },
56
+ schemaVersion: '1', policyVersion: null,
57
+ };
58
+ return validateClinicalSourceEvent(event);
59
+ }
60
+
61
+ async function captureClinicalMessage(values, settings = {}) {
62
+ const enabled = settings?.enabled;
63
+ if (enabled !== true && enabled !== 'true') return { state: 'skipped', reason: 'disabled' };
64
+ if (isShadowRun() || isBenchMode(values?.numero) || isBenchMode(values?.contact_code)) return { state: 'skipped', reason: 'isolated_run' };
65
+ if (values?.from_me !== false || !['patient', 'whatsapp_platform'].includes(values?.origin)) return { state: 'skipped', reason: 'excluded_message' };
66
+ return ingestClinicalSourceEvent(buildClinicalMessageEnvelope(values, settings.tenantId));
67
+ }
68
+
69
+ module.exports = { buildClinicalMessageEnvelope, captureClinicalMessage };
@@ -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
@@ -11,6 +11,8 @@ declare module '@peopl-health/nexus' {
11
11
  contactName?: string | null;
12
12
  contactLabel?: string | null;
13
13
  body?: string;
14
+ /** Derived first-capture contact evidence; never canonical patient identity. */
15
+ normalizedContent?: { type: 'extracted_contact'; text: string } | null;
14
16
  message?: string;
15
17
  timestamp?: string | Date;
16
18
  createdAt?: string | Date;
@@ -86,6 +88,8 @@ declare module '@peopl-health/nexus' {
86
88
  }
87
89
 
88
90
  export interface StorageConfig {
91
+ /** Explicit prospective journal configuration; omitted or false keeps capture disabled. */
92
+ clinicalEventCapture?: { enabled?: boolean | 'true' | 'false'; tenantId?: string };
89
93
  mongoUri: string;
90
94
  dbName: string;
91
95
  collections?: {
@@ -924,6 +928,7 @@ declare module '@peopl-health/nexus' {
924
928
  abortOnNewMessage?: boolean;
925
929
  immediateRestart?: boolean;
926
930
  typingIndicator?: boolean;
931
+ instructionSettleMs?: number;
927
932
  hooks?: Record<string, Function | Function[]>;
928
933
  }
929
934
 
@@ -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 };
@@ -9,6 +9,8 @@ const { getClinicalContext } = require('../helpers/patientInformationHelper');
9
9
 
10
10
  const { updateRecordByFilter } = require('../services/airtableService');
11
11
 
12
+ const { captureClinicalMessage } = require('../clinical/services/clinicalMessageCaptureService');
13
+
12
14
  const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
13
15
 
14
16
  async function getMessages(query, options = {}) {
@@ -28,8 +30,9 @@ async function aggregateMessages(pipeline, options = {}) {
28
30
  return Message.aggregate(pipeline, options);
29
31
  }
30
32
 
31
- async function insertMessage(values) {
33
+ async function insertMessage(values, options = {}) {
32
34
  try {
35
+ await captureClinicalMessage(values, options?.clinicalEventCapture);
33
36
  if (!values.clinical_context) {
34
37
  const { clinicalContext } = await getClinicalContext(values.numero);
35
38
  values.clinical_context = clinicalContext;
@@ -16,6 +16,7 @@ const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
16
16
  class MongoStorage {
17
17
  constructor(config) {
18
18
  this.mongoUri = config.mongoUri;
19
+ this.clinicalEventCapture = config.clinicalEventCapture;
19
20
  this.dbName = config.dbName;
20
21
  this.collections = config.collections || {
21
22
  messages: 'messages',
@@ -39,7 +40,7 @@ class MongoStorage {
39
40
  async saveMessage(messageData) {
40
41
  try {
41
42
  const values = this.buildMessageValues(messageData);
42
- const { doc } = await insertMessage(values);
43
+ const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
43
44
  logger.info('[MongoStorage] Message stored');
44
45
  if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId);
45
46
  return doc;
@@ -54,7 +55,7 @@ class MongoStorage {
54
55
  ...messageData,
55
56
  statusInfo: { status: 'queued', updatedAt: new Date() }
56
57
  });
57
- const { doc } = await insertMessage(values);
58
+ const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
58
59
  if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId, 'queued');
59
60
  return doc;
60
61
  }
@@ -112,6 +113,15 @@ class MongoStorage {
112
113
  plainBody: messageData.plainBody || '',
113
114
  processed: messageData.processed || false,
114
115
  message_id: messageId,
116
+ sourceText: messageData.plainBody ?? messageData.body,
117
+ normalizedContent: messageData.normalizedContent,
118
+ sourceSystem: messageData.sourceSystem,
119
+ sourceProvider: messageData.provider,
120
+ sourceRecordId: messageData.sourceRecordId,
121
+ sourceRevision: messageData.sourceRevision,
122
+ sourceTimestamp: messageData.sourceTimestamp,
123
+ sourceActorId: messageData.from,
124
+ quotedMessageId: messageData.quotedMessageId,
115
125
  interactive_type: messageData.interactive?.type || null,
116
126
  interactive_data: messageData.interactive || null,
117
127
  from_me: messageData.fromMe !== undefined ? messageData.fromMe : true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.8",
3
+ "version": "5.60.0-dev.11092",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",