@peopl-health/nexus 5.59.8 → 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.
- package/lib/clinical/memory/DefaultMemoryManager.js +11 -0
- package/lib/config/instructionConfig.js +4 -0
- package/lib/core/BatchingManager.js +4 -0
- package/lib/core/NexusMessaging.js +82 -48
- package/lib/index.d.ts +1 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/package.json +1 -1
|
@@ -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 [];
|
|
@@ -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,
|
|
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
|
-
|
|
725
|
-
|
|
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
|
-
|
|
827
|
-
|
|
828
|
-
this.
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
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(
|
|
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
|
@@ -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 };
|