@peopl-health/nexus 5.49.0-dev.7426 → 5.49.0-dev.7429
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/providers/BaseLLMProvider.js +7 -5
- package/lib/core/BatchingManager.js +7 -119
- package/lib/core/NexusMessaging.js +16 -55
- package/lib/index.d.ts +4 -32
- package/lib/index.js +3 -18
- package/lib/models/messageModel.js +1 -0
- package/package.json +1 -1
|
@@ -612,15 +612,17 @@ class BaseLLMProvider {
|
|
|
612
612
|
} catch (error) {
|
|
613
613
|
// Keyed on the signal, not the error type: an AbortError from some unrelated inner timeout is not a supersede.
|
|
614
614
|
const aborted = Boolean(config.signal?.aborted);
|
|
615
|
-
logger.error('[runConversation] Attempt failed', { attempt, error: error.message });
|
|
616
615
|
if (aborted || isSuperseded(config.shouldContinue)) {
|
|
617
|
-
logger.info('[runConversation] Superseded — abandoning after error', { attempt, shadow: config.shadow, aborted });
|
|
616
|
+
logger.info('[runConversation] Superseded — abandoning after error', { attempt, shadow: config.shadow, aborted, error: error.message });
|
|
618
617
|
const ctx = config?.assistant?.toolRuntimeContext;
|
|
619
|
-
|
|
620
|
-
if (aborted && ctx) ctx.abort = { reason: abortCode || 'superseded', iteration: ctx.trace ? (ctx.trace.iterations?.length ?? 0) + 1 : null };
|
|
618
|
+
if (aborted && ctx) ctx.abort = { reason: 'superseded', iteration: ctx.trace ? (ctx.trace.iterations?.length ?? 0) + 1 : null };
|
|
621
619
|
return { status: 'cancelled', output_text: '', tools_executed: [], retries: 0 };
|
|
622
620
|
}
|
|
623
|
-
if (attempt === maxRetries)
|
|
621
|
+
if (attempt === maxRetries) {
|
|
622
|
+
logger.error('[runConversation] Attempt failed', { attempt, error: error.message });
|
|
623
|
+
throw error;
|
|
624
|
+
}
|
|
625
|
+
logger.warn('[runConversation] Attempt failed, retrying', { attempt, maxRetries, error: error.message });
|
|
624
626
|
await new Promise(r => setTimeout(r, 500));
|
|
625
627
|
}
|
|
626
628
|
}
|
|
@@ -2,26 +2,6 @@ const { logger } = require('../utils/logger');
|
|
|
2
2
|
|
|
3
3
|
const { getMessages } = require('../services/messageService');
|
|
4
4
|
|
|
5
|
-
const DEFAULT_DRAIN_MS = 18000;
|
|
6
|
-
const DEFAULT_ABORT_GRACE_MS = 4000;
|
|
7
|
-
const DRAIN_POLL_MS = 250;
|
|
8
|
-
|
|
9
|
-
class DrainingError extends Error {
|
|
10
|
-
constructor(chatId) {
|
|
11
|
-
super(`Instance is draining; no turn was started for ${chatId}`);
|
|
12
|
-
this.name = 'DrainingError';
|
|
13
|
-
this.code = 'draining';
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
class DrainAbort extends Error {
|
|
18
|
-
constructor() {
|
|
19
|
-
super('Turn abandoned by shutdown drain');
|
|
20
|
-
this.name = 'DrainAbort';
|
|
21
|
-
this.code = 'shutdown_drain';
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
5
|
class BatchingManager {
|
|
26
6
|
constructor({ provider = null, config = {} }) {
|
|
27
7
|
this.provider = provider;
|
|
@@ -38,16 +18,6 @@ class BatchingManager {
|
|
|
38
18
|
this.abortControllers = new Map();
|
|
39
19
|
this.typingIntervals = new Map();
|
|
40
20
|
this.chatQueues = new Map();
|
|
41
|
-
this.runChats = new Map();
|
|
42
|
-
|
|
43
|
-
this.draining = false;
|
|
44
|
-
this._drainPromise = null;
|
|
45
|
-
this.onRefused = null;
|
|
46
|
-
this.onAbandoned = null;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
isDraining() {
|
|
50
|
-
return this.draining;
|
|
51
21
|
}
|
|
52
22
|
|
|
53
23
|
setProvider(provider) {
|
|
@@ -68,8 +38,6 @@ class BatchingManager {
|
|
|
68
38
|
}
|
|
69
39
|
|
|
70
40
|
async handleBatchedProcessing(chatId, processingFn, sendResponseFn) {
|
|
71
|
-
if (this.draining) return this._refuse(chatId, false);
|
|
72
|
-
|
|
73
41
|
if (this.processingLocks.has(chatId)) {
|
|
74
42
|
if (this.config.abortOnNewMessage && this.activeRequests.has(chatId)) {
|
|
75
43
|
const runId = this.activeRequests.get(chatId);
|
|
@@ -80,55 +48,38 @@ class BatchingManager {
|
|
|
80
48
|
if (this.config.immediateRestart) {
|
|
81
49
|
this._clearProcessingState(chatId);
|
|
82
50
|
this.processingLocks.set(chatId, true);
|
|
83
|
-
|
|
51
|
+
await this._runWithLock(chatId, processingFn, sendResponseFn);
|
|
84
52
|
}
|
|
85
53
|
}
|
|
86
|
-
return
|
|
54
|
+
return;
|
|
87
55
|
}
|
|
88
56
|
|
|
89
57
|
this.processingLocks.set(chatId, true);
|
|
90
|
-
|
|
58
|
+
await this._runWithLock(chatId, processingFn, sendResponseFn);
|
|
91
59
|
}
|
|
92
60
|
|
|
93
61
|
async enqueueProcessing(chatId, processingFn, sendResponseFn) {
|
|
94
|
-
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
_refuse(chatId, rethrow) {
|
|
98
|
-
logger.warn('[BatchingManager] Turn refused — instance is draining', { chatId });
|
|
99
|
-
this.onRefused?.(chatId);
|
|
100
|
-
if (rethrow) throw new DrainingError(chatId);
|
|
101
|
-
return { accepted: false, reason: 'draining' };
|
|
62
|
+
await this._runWithLock(chatId, processingFn, sendResponseFn, { rethrow: true });
|
|
102
63
|
}
|
|
103
64
|
|
|
104
65
|
async _runWithLock(chatId, processingFn, sendResponseFn, { rethrow = false } = {}) {
|
|
105
|
-
if (this.draining) return this._refuse(chatId, rethrow);
|
|
106
|
-
|
|
107
66
|
const prev = this.chatQueues.get(chatId) || Promise.resolve();
|
|
108
67
|
let resolveGate;
|
|
109
68
|
const gate = new Promise(r => { resolveGate = r; });
|
|
110
69
|
this.chatQueues.set(chatId, gate);
|
|
111
70
|
await prev;
|
|
112
71
|
|
|
113
|
-
if (this.draining) {
|
|
114
|
-
resolveGate();
|
|
115
|
-
if (this.chatQueues.get(chatId) === gate) this.chatQueues.delete(chatId);
|
|
116
|
-
this.processingLocks.delete(chatId);
|
|
117
|
-
return this._refuse(chatId, rethrow);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
72
|
this.processingLocks.set(chatId, true);
|
|
121
73
|
const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
|
|
122
74
|
this.activeRequests.set(chatId, runId);
|
|
123
75
|
this.abortControllers.set(runId, new AbortController());
|
|
124
|
-
this.runChats.set(runId, chatId);
|
|
125
76
|
|
|
126
77
|
try {
|
|
127
78
|
await this._startTypingRefresh(chatId, runId);
|
|
128
|
-
if (this._checkAbandoned(runId)) return
|
|
79
|
+
if (this._checkAbandoned(runId)) return;
|
|
129
80
|
|
|
130
81
|
const result = await processingFn(runId);
|
|
131
|
-
if (this._checkAbandoned(runId)) return
|
|
82
|
+
if (this._checkAbandoned(runId)) return;
|
|
132
83
|
|
|
133
84
|
if (sendResponseFn && result) {
|
|
134
85
|
try {
|
|
@@ -145,7 +96,6 @@ class BatchingManager {
|
|
|
145
96
|
this._clearProcessingState(chatId);
|
|
146
97
|
}
|
|
147
98
|
this.abortControllers.delete(runId);
|
|
148
|
-
this.runChats.delete(runId);
|
|
149
99
|
resolveGate();
|
|
150
100
|
if (this.chatQueues.get(chatId) === gate) this.chatQueues.delete(chatId);
|
|
151
101
|
if (this.abandonedRuns.size > 100) {
|
|
@@ -154,68 +104,6 @@ class BatchingManager {
|
|
|
154
104
|
toKeep.forEach(id => this.abandonedRuns.add(id));
|
|
155
105
|
}
|
|
156
106
|
}
|
|
157
|
-
|
|
158
|
-
return { accepted: true };
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
drain({ timeoutMs = DEFAULT_DRAIN_MS, abortGraceMs = DEFAULT_ABORT_GRACE_MS } = {}) {
|
|
162
|
-
if (this._drainPromise) return this._drainPromise;
|
|
163
|
-
this.draining = true;
|
|
164
|
-
this._drainPromise = this._drain({ timeoutMs, abortGraceMs, startedAt: Date.now() });
|
|
165
|
-
return this._drainPromise;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
async _drain({ timeoutMs, abortGraceMs, startedAt }) {
|
|
169
|
-
const deadline = startedAt + timeoutMs;
|
|
170
|
-
logger.warn('[BatchingManager] Drain started', {
|
|
171
|
-
chats: this.chatQueues.size, runs: this.abortControllers.size, timeoutMs,
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
while (this.chatQueues.size > 0 && Date.now() < deadline) {
|
|
175
|
-
await this._settleWithin(
|
|
176
|
-
Promise.allSettled([...this.chatQueues.values()]),
|
|
177
|
-
Math.min(deadline - Date.now(), DRAIN_POLL_MS),
|
|
178
|
-
);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
if (this.chatQueues.size === 0) {
|
|
182
|
-
this._disposeTimers();
|
|
183
|
-
const waitedMs = Date.now() - startedAt;
|
|
184
|
-
logger.info('[BatchingManager] Drain complete', { waitedMs });
|
|
185
|
-
return { drained: true, waitedMs, abandoned: [] };
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const abandoned = [];
|
|
189
|
-
for (const [runId, controller] of this.abortControllers) {
|
|
190
|
-
const chatId = this.runChats.get(runId) ?? null;
|
|
191
|
-
this.abandonedRuns.add(runId);
|
|
192
|
-
controller.abort(new DrainAbort());
|
|
193
|
-
abandoned.push({ chatId, runId });
|
|
194
|
-
logger.error('[BatchingManager] Turn abandoned by shutdown drain', { chatId, runId });
|
|
195
|
-
this.onAbandoned?.({ chatId, runId, reason: 'shutdown_drain_timeout' });
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
await this._settleWithin(
|
|
199
|
-
Promise.allSettled([...this.chatQueues.values()]),
|
|
200
|
-
abortGraceMs,
|
|
201
|
-
{ keepAlive: true },
|
|
202
|
-
);
|
|
203
|
-
|
|
204
|
-
this._disposeTimers();
|
|
205
|
-
return { drained: false, waitedMs: Date.now() - startedAt, abandoned };
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
_settleWithin(promise, ms, { keepAlive = false } = {}) {
|
|
209
|
-
let timer;
|
|
210
|
-
const expiry = new Promise(resolve => {
|
|
211
|
-
timer = setTimeout(resolve, Math.max(ms, 0));
|
|
212
|
-
if (!keepAlive) timer.unref?.();
|
|
213
|
-
});
|
|
214
|
-
return Promise.race([promise, expiry]).finally(() => clearTimeout(timer));
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
_disposeTimers() {
|
|
218
|
-
for (const chatId of [...this.typingIntervals.keys()]) this._stopTyping(chatId);
|
|
219
107
|
}
|
|
220
108
|
|
|
221
109
|
_clearProcessingState(chatId) {
|
|
@@ -258,4 +146,4 @@ class BatchingManager {
|
|
|
258
146
|
|
|
259
147
|
}
|
|
260
148
|
|
|
261
|
-
module.exports = { BatchingManager
|
|
149
|
+
module.exports = { BatchingManager };
|
|
@@ -9,8 +9,6 @@ const { runInShadowScope } = require('../utils/shadowScope');
|
|
|
9
9
|
|
|
10
10
|
const { logger } = require('../utils/logger');
|
|
11
11
|
|
|
12
|
-
const { createEvent, safeEmit } = require('../utils/eventUtils');
|
|
13
|
-
const { withTimeout } = require('../utils/timeoutUtils');
|
|
14
12
|
const { Message } = require('../models/messageModel');
|
|
15
13
|
const { Thread } = require('../models/threadModel');
|
|
16
14
|
|
|
@@ -112,10 +110,6 @@ class NexusMessaging {
|
|
|
112
110
|
this.batchingManager = new BatchingManager({
|
|
113
111
|
config: this.batchingConfig
|
|
114
112
|
});
|
|
115
|
-
this.batchingManager.onRefused = (chatId) =>
|
|
116
|
-
safeEmit(this.events, 'turn:deferred', createEvent('turn:deferred', { chatId, reason: 'draining' }));
|
|
117
|
-
this.batchingManager.onAbandoned = (payload) =>
|
|
118
|
-
safeEmit(this.events, 'turn:abandoned', createEvent('turn:abandoned', payload));
|
|
119
113
|
|
|
120
114
|
this.pipeline = new ProcessingPipeline(this.batchingConfig.hooks);
|
|
121
115
|
|
|
@@ -599,7 +593,6 @@ class NexusMessaging {
|
|
|
599
593
|
async handleMessageWithAssistant(messageData) {
|
|
600
594
|
const { from, body } = messageData;
|
|
601
595
|
if (!from || !body) return;
|
|
602
|
-
if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
|
|
603
596
|
|
|
604
597
|
try {
|
|
605
598
|
const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from }));
|
|
@@ -612,7 +605,6 @@ class NexusMessaging {
|
|
|
612
605
|
async handleMediaWithAssistant(messageData) {
|
|
613
606
|
const { from } = messageData;
|
|
614
607
|
if (!from) return;
|
|
615
|
-
if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
|
|
616
608
|
|
|
617
609
|
try {
|
|
618
610
|
const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from }));
|
|
@@ -643,11 +635,11 @@ class NexusMessaging {
|
|
|
643
635
|
if (sendResponse) await this.assistantProcessor.sendResponse(chatId, result);
|
|
644
636
|
};
|
|
645
637
|
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
638
|
+
if (mode === 'queue') {
|
|
639
|
+
await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn);
|
|
640
|
+
} else {
|
|
641
|
+
await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
|
|
642
|
+
}
|
|
651
643
|
|
|
652
644
|
return capturedResult;
|
|
653
645
|
}
|
|
@@ -686,7 +678,7 @@ class NexusMessaging {
|
|
|
686
678
|
|
|
687
679
|
if (storeRunMetrics) await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
|
|
688
680
|
return { ...result, timings: preProcessed.timings };
|
|
689
|
-
}, shouldContinue);
|
|
681
|
+
}, shouldContinue, runId);
|
|
690
682
|
}
|
|
691
683
|
);
|
|
692
684
|
}
|
|
@@ -710,7 +702,7 @@ class NexusMessaging {
|
|
|
710
702
|
this._saveMessageFn,
|
|
711
703
|
async ({ body, _id }) => {
|
|
712
704
|
const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
|
|
713
|
-
async (preProcessResult,
|
|
705
|
+
async (preProcessResult, _shouldContinue, runId) => this.assistantProcessor.process({
|
|
714
706
|
code,
|
|
715
707
|
runOptions: {
|
|
716
708
|
prePromptResult: preProcessResult,
|
|
@@ -718,8 +710,6 @@ class NexusMessaging {
|
|
|
718
710
|
toolChoice: 'none',
|
|
719
711
|
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
720
712
|
runId,
|
|
721
|
-
shouldContinue,
|
|
722
|
-
signal: this.batchingManager.getAbortSignal(runId),
|
|
723
713
|
}
|
|
724
714
|
}),
|
|
725
715
|
);
|
|
@@ -769,12 +759,10 @@ class NexusMessaging {
|
|
|
769
759
|
|
|
770
760
|
let runResult = null;
|
|
771
761
|
const executeTurn = () => this._executeWithPipeline(code, 'outreach', 'queue',
|
|
772
|
-
async (preProcessResult,
|
|
762
|
+
async (preProcessResult, _shouldContinue, runId) => this.assistantProcessor.process({
|
|
773
763
|
code,
|
|
774
764
|
runOptions: {
|
|
775
765
|
prePromptResult: preProcessResult,
|
|
776
|
-
shouldContinue,
|
|
777
|
-
signal: this.batchingManager.getAbortSignal(runId),
|
|
778
766
|
toolChoice: 'auto',
|
|
779
767
|
turnKind: TURN_KIND.PROACTIVE_OUTREACH,
|
|
780
768
|
outreachBrief: brief,
|
|
@@ -986,7 +974,7 @@ class NexusMessaging {
|
|
|
986
974
|
if (!reply) return;
|
|
987
975
|
|
|
988
976
|
await this._executeWithPipeline(code, 'system', 'queue',
|
|
989
|
-
async (preProcessResult,
|
|
977
|
+
async (preProcessResult, _shouldContinue, runId) => {
|
|
990
978
|
return await this.assistantProcessor.process({
|
|
991
979
|
code,
|
|
992
980
|
runOptions: {
|
|
@@ -994,23 +982,22 @@ class NexusMessaging {
|
|
|
994
982
|
toolChoice: 'none',
|
|
995
983
|
turnKind: TURN_KIND.SYSTEM,
|
|
996
984
|
runId,
|
|
997
|
-
shouldContinue,
|
|
998
|
-
signal: this.batchingManager.getAbortSignal(runId),
|
|
999
985
|
}
|
|
1000
986
|
});
|
|
1001
987
|
}
|
|
1002
988
|
);
|
|
1003
989
|
}
|
|
1004
990
|
|
|
1005
|
-
async _processMessages(chatId, processingFn, shouldFinalize = () => true) {
|
|
991
|
+
async _processMessages(chatId, processingFn, shouldFinalize = () => true, runId = null) {
|
|
1006
992
|
const query = { numero: chatId, from_me: false, processed: false };
|
|
1007
993
|
const unprocessed = await getMessages(query, { select: '_id' });
|
|
1008
994
|
|
|
1009
995
|
try {
|
|
1010
996
|
const result = await processingFn();
|
|
1011
997
|
if (unprocessed.length > 0 && shouldFinalize()) {
|
|
1012
|
-
|
|
1013
|
-
|
|
998
|
+
const marks = runId ? { processed: true, processedByTurnId: runId } : { processed: true };
|
|
999
|
+
await Message.updateMany({ _id: { $in: unprocessed.map(m => m._id) } }, { $set: marks });
|
|
1000
|
+
logger.info('[_processMessages] Marked messages as processed', { count: unprocessed.length, chatId, runId });
|
|
1014
1001
|
}
|
|
1015
1002
|
return result;
|
|
1016
1003
|
} catch (error) {
|
|
@@ -1023,37 +1010,11 @@ class NexusMessaging {
|
|
|
1023
1010
|
* LIFECYCLE
|
|
1024
1011
|
*/
|
|
1025
1012
|
|
|
1026
|
-
async
|
|
1027
|
-
if (this._shutdownPromise) return this._shutdownPromise;
|
|
1028
|
-
this.batchingManager.draining = true;
|
|
1013
|
+
async disconnect() {
|
|
1029
1014
|
this.queueReconciliation?.stop();
|
|
1030
|
-
this.
|
|
1031
|
-
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
async _shutdown({ drainMs, abortGraceMs, teardownMs }) {
|
|
1035
|
-
const result = await this.batchingManager.drain({
|
|
1036
|
-
...(drainMs === undefined ? {} : { timeoutMs: drainMs }),
|
|
1037
|
-
...(abortGraceMs === undefined ? {} : { abortGraceMs }),
|
|
1038
|
-
});
|
|
1039
|
-
|
|
1040
|
-
if (this.queueAdapter) {
|
|
1041
|
-
await withTimeout(this.queueAdapter.shutdown(), teardownMs, 'queueAdapter.shutdown')
|
|
1042
|
-
.catch(error => logger.warn('[NexusMessaging] Queue shutdown did not finish', { error: error.message }));
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
if (typeof this.provider?.disconnect === 'function') {
|
|
1046
|
-
const disconnecting = Promise.resolve().then(() => this.provider.disconnect());
|
|
1047
|
-
await withTimeout(disconnecting, teardownMs, 'provider.disconnect')
|
|
1048
|
-
.catch(error => logger.warn('[NexusMessaging] Provider disconnect skipped', { error: error.message }));
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1015
|
+
if (this.provider) await this.provider.disconnect();
|
|
1016
|
+
if (this.queueAdapter) await this.queueAdapter.shutdown();
|
|
1051
1017
|
this.events.removeAllListeners();
|
|
1052
|
-
return result;
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
async disconnect(options = {}) {
|
|
1056
|
-
return this.shutdown(options);
|
|
1057
1018
|
}
|
|
1058
1019
|
}
|
|
1059
1020
|
|
package/lib/index.d.ts
CHANGED
|
@@ -248,8 +248,7 @@ declare module '@peopl-health/nexus' {
|
|
|
248
248
|
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
|
|
249
249
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
250
250
|
isConnected(): boolean;
|
|
251
|
-
|
|
252
|
-
disconnect(options?: ShutdownOptions): Promise<DrainResult>;
|
|
251
|
+
disconnect(): Promise<void>;
|
|
253
252
|
}
|
|
254
253
|
|
|
255
254
|
export class MongoStorage {
|
|
@@ -338,10 +337,7 @@ declare module '@peopl-health/nexus' {
|
|
|
338
337
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
339
338
|
processMessage(rawMessage: any): Promise<any>;
|
|
340
339
|
isConnected(): boolean;
|
|
341
|
-
|
|
342
|
-
isDraining(): boolean;
|
|
343
|
-
shutdown(options?: ShutdownOptions & { closeStorage?: boolean }): Promise<DrainResult>;
|
|
344
|
-
disconnect(options?: ShutdownOptions & { closeStorage?: boolean }): Promise<DrainResult>;
|
|
340
|
+
disconnect(): Promise<void>;
|
|
345
341
|
getMessaging(): NexusMessaging;
|
|
346
342
|
getStorage(): MongoStorage | null;
|
|
347
343
|
getMessageParser(): MessageParser | null;
|
|
@@ -669,28 +665,6 @@ declare module '@peopl-health/nexus' {
|
|
|
669
665
|
hooks?: Record<string, Function | Function[]>;
|
|
670
666
|
}
|
|
671
667
|
|
|
672
|
-
export interface DrainResult {
|
|
673
|
-
drained: boolean;
|
|
674
|
-
waitedMs: number;
|
|
675
|
-
abandoned: Array<{ chatId: string | null; runId: string }>;
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
export interface TurnAdmission {
|
|
679
|
-
accepted: boolean;
|
|
680
|
-
reason?: string;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
export interface ShutdownOptions {
|
|
684
|
-
drainMs?: number;
|
|
685
|
-
abortGraceMs?: number;
|
|
686
|
-
teardownMs?: number;
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
export class DrainingError extends Error {
|
|
690
|
-
constructor(chatId: string);
|
|
691
|
-
code: 'draining';
|
|
692
|
-
}
|
|
693
|
-
|
|
694
668
|
export class BatchingManager {
|
|
695
669
|
constructor(options: {
|
|
696
670
|
provider?: MessageProvider;
|
|
@@ -699,19 +673,17 @@ declare module '@peopl-health/nexus' {
|
|
|
699
673
|
setProvider(provider: MessageProvider): void;
|
|
700
674
|
isProcessing(chatId: string): boolean;
|
|
701
675
|
isActiveRun(chatId: string, runId: string): boolean;
|
|
702
|
-
isDraining(): boolean;
|
|
703
676
|
getAbortSignal(runId: string): AbortSignal | undefined;
|
|
704
|
-
drain(options?: { timeoutMs?: number; abortGraceMs?: number }): Promise<DrainResult>;
|
|
705
677
|
handleBatchedProcessing(
|
|
706
678
|
chatId: string,
|
|
707
679
|
processingFn: (runId: string) => Promise<any>,
|
|
708
680
|
sendResponseFn: (result: any) => Promise<void>
|
|
709
|
-
): Promise<
|
|
681
|
+
): Promise<void>;
|
|
710
682
|
enqueueProcessing(
|
|
711
683
|
chatId: string,
|
|
712
684
|
processingFn: (runId: string) => Promise<any>,
|
|
713
685
|
sendResponseFn: (result: any) => Promise<void>
|
|
714
|
-
): Promise<
|
|
686
|
+
): Promise<void>;
|
|
715
687
|
}
|
|
716
688
|
|
|
717
689
|
// ProcessingPipeline — hook lifecycle for all LLM operations
|
package/lib/index.js
CHANGED
|
@@ -28,7 +28,6 @@ const { setPreprocessingHandler, hasPreprocessingHandler, invokePreprocessingHan
|
|
|
28
28
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
29
29
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
30
30
|
const { createWorkflowRunner } = require('./core/workflowRunner');
|
|
31
|
-
const { DrainingError } = require('./core/BatchingManager');
|
|
32
31
|
const routes = require('./routes');
|
|
33
32
|
const { resetAll } = require('./config/lifecycle');
|
|
34
33
|
const { EvalProvider } = require('./eval/EvalProvider');
|
|
@@ -216,24 +215,11 @@ class Nexus {
|
|
|
216
215
|
return this.messaging.isConnected();
|
|
217
216
|
}
|
|
218
217
|
|
|
219
|
-
|
|
220
|
-
this.messaging.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
isDraining() {
|
|
224
|
-
return this.messaging.getBatchingManager().isDraining();
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
async shutdown({ drainMs, abortGraceMs, teardownMs, closeStorage = true } = {}) {
|
|
228
|
-
const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
|
|
229
|
-
if (closeStorage && this.storage) {
|
|
218
|
+
async disconnect() {
|
|
219
|
+
await this.messaging.disconnect();
|
|
220
|
+
if (this.storage) {
|
|
230
221
|
await this.storage.disconnect();
|
|
231
222
|
}
|
|
232
|
-
return result;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async disconnect(options = {}) {
|
|
236
|
-
return this.shutdown(options);
|
|
237
223
|
}
|
|
238
224
|
|
|
239
225
|
getMessaging() { return this.messaging; }
|
|
@@ -245,7 +231,6 @@ class Nexus {
|
|
|
245
231
|
module.exports = {
|
|
246
232
|
createWorkflowRunner,
|
|
247
233
|
Nexus,
|
|
248
|
-
DrainingError,
|
|
249
234
|
TwilioProvider,
|
|
250
235
|
BaileysProvider,
|
|
251
236
|
MongoStorage,
|
|
@@ -84,6 +84,7 @@ const messageSchema = new mongoose.Schema({
|
|
|
84
84
|
preset: { type: Object, default: null },
|
|
85
85
|
response_id: { type: String, default: null },
|
|
86
86
|
turnId: { type: String },
|
|
87
|
+
processedByTurnId: { type: String },
|
|
87
88
|
traceId: { type: String },
|
|
88
89
|
triggeredBy: { type: String, default: null }
|
|
89
90
|
}, { timestamps: true });
|