@peopl-health/nexus 5.49.0-dev.7464 → 5.49.0-dev.7465

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.
@@ -615,7 +615,8 @@ class BaseLLMProvider {
615
615
  if (aborted || isSuperseded(config.shouldContinue)) {
616
616
  logger.info('[runConversation] Superseded — abandoning after error', { attempt, shadow: config.shadow, aborted, error: error.message });
617
617
  const ctx = config?.assistant?.toolRuntimeContext;
618
- if (aborted && ctx) ctx.abort = { reason: 'superseded', iteration: ctx.trace ? (ctx.trace.iterations?.length ?? 0) + 1 : null };
618
+ const abortCode = typeof config.signal?.reason?.code === 'string' ? config.signal.reason.code : null;
619
+ if (aborted && ctx) ctx.abort = { reason: abortCode || 'superseded', iteration: ctx.trace ? (ctx.trace.iterations?.length ?? 0) + 1 : null };
619
620
  return { status: 'cancelled', output_text: '', tools_executed: [], retries: 0 };
620
621
  }
621
622
  if (attempt === maxRetries) {
@@ -2,6 +2,26 @@ 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
+
5
25
  class BatchingManager {
6
26
  constructor({ provider = null, config = {} }) {
7
27
  this.provider = provider;
@@ -18,6 +38,16 @@ class BatchingManager {
18
38
  this.abortControllers = new Map();
19
39
  this.typingIntervals = new Map();
20
40
  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;
21
51
  }
22
52
 
23
53
  setProvider(provider) {
@@ -38,6 +68,8 @@ class BatchingManager {
38
68
  }
39
69
 
40
70
  async handleBatchedProcessing(chatId, processingFn, sendResponseFn) {
71
+ if (this.draining) return this._refuse(chatId, false);
72
+
41
73
  if (this.processingLocks.has(chatId)) {
42
74
  if (this.config.abortOnNewMessage && this.activeRequests.has(chatId)) {
43
75
  const runId = this.activeRequests.get(chatId);
@@ -48,38 +80,55 @@ class BatchingManager {
48
80
  if (this.config.immediateRestart) {
49
81
  this._clearProcessingState(chatId);
50
82
  this.processingLocks.set(chatId, true);
51
- await this._runWithLock(chatId, processingFn, sendResponseFn);
83
+ return await this._runWithLock(chatId, processingFn, sendResponseFn);
52
84
  }
53
85
  }
54
- return;
86
+ return { accepted: true };
55
87
  }
56
88
 
57
89
  this.processingLocks.set(chatId, true);
58
- await this._runWithLock(chatId, processingFn, sendResponseFn);
90
+ return await this._runWithLock(chatId, processingFn, sendResponseFn);
59
91
  }
60
92
 
61
93
  async enqueueProcessing(chatId, processingFn, sendResponseFn) {
62
- await this._runWithLock(chatId, processingFn, sendResponseFn, { rethrow: true });
94
+ return await this._runWithLock(chatId, processingFn, sendResponseFn, { rethrow: true });
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' };
63
102
  }
64
103
 
65
104
  async _runWithLock(chatId, processingFn, sendResponseFn, { rethrow = false } = {}) {
105
+ if (this.draining) return this._refuse(chatId, rethrow);
106
+
66
107
  const prev = this.chatQueues.get(chatId) || Promise.resolve();
67
108
  let resolveGate;
68
109
  const gate = new Promise(r => { resolveGate = r; });
69
110
  this.chatQueues.set(chatId, gate);
70
111
  await prev;
71
112
 
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
+
72
120
  this.processingLocks.set(chatId, true);
73
121
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
74
122
  this.activeRequests.set(chatId, runId);
75
123
  this.abortControllers.set(runId, new AbortController());
124
+ this.runChats.set(runId, chatId);
76
125
 
77
126
  try {
78
127
  await this._startTypingRefresh(chatId, runId);
79
- if (this._checkAbandoned(runId)) return;
128
+ if (this._checkAbandoned(runId)) return { accepted: true };
80
129
 
81
130
  const result = await processingFn(runId);
82
- if (this._checkAbandoned(runId)) return;
131
+ if (this._checkAbandoned(runId)) return { accepted: true };
83
132
 
84
133
  if (sendResponseFn && result) {
85
134
  try {
@@ -96,6 +145,7 @@ class BatchingManager {
96
145
  this._clearProcessingState(chatId);
97
146
  }
98
147
  this.abortControllers.delete(runId);
148
+ this.runChats.delete(runId);
99
149
  resolveGate();
100
150
  if (this.chatQueues.get(chatId) === gate) this.chatQueues.delete(chatId);
101
151
  if (this.abandonedRuns.size > 100) {
@@ -104,6 +154,68 @@ class BatchingManager {
104
154
  toKeep.forEach(id => this.abandonedRuns.add(id));
105
155
  }
106
156
  }
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);
107
219
  }
108
220
 
109
221
  _clearProcessingState(chatId) {
@@ -146,4 +258,4 @@ class BatchingManager {
146
258
 
147
259
  }
148
260
 
149
- module.exports = { BatchingManager };
261
+ module.exports = { BatchingManager, DrainingError, DrainAbort, DEFAULT_DRAIN_MS, DEFAULT_ABORT_GRACE_MS };
@@ -9,6 +9,8 @@ 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');
12
14
  const { Message } = require('../models/messageModel');
13
15
  const { Thread } = require('../models/threadModel');
14
16
 
@@ -110,6 +112,10 @@ class NexusMessaging {
110
112
  this.batchingManager = new BatchingManager({
111
113
  config: this.batchingConfig
112
114
  });
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));
113
119
 
114
120
  this.pipeline = new ProcessingPipeline(this.batchingConfig.hooks);
115
121
 
@@ -593,6 +599,7 @@ class NexusMessaging {
593
599
  async handleMessageWithAssistant(messageData) {
594
600
  const { from, body } = messageData;
595
601
  if (!from || !body) return;
602
+ if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
596
603
 
597
604
  try {
598
605
  const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from }));
@@ -605,6 +612,7 @@ class NexusMessaging {
605
612
  async handleMediaWithAssistant(messageData) {
606
613
  const { from } = messageData;
607
614
  if (!from) return;
615
+ if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
608
616
 
609
617
  try {
610
618
  const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from }));
@@ -635,11 +643,11 @@ class NexusMessaging {
635
643
  if (sendResponse) await this.assistantProcessor.sendResponse(chatId, result);
636
644
  };
637
645
 
638
- if (mode === 'queue') {
639
- await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn);
640
- } else {
641
- await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
642
- }
646
+ const admission = mode === 'queue'
647
+ ? await this.batchingManager.enqueueProcessing(chatId, processingFn, sendResponseFn)
648
+ : await this.batchingManager.handleBatchedProcessing(chatId, processingFn, sendResponseFn);
649
+
650
+ if (admission?.accepted === false) return { deferred: true, reason: admission.reason };
643
651
 
644
652
  return capturedResult;
645
653
  }
@@ -702,7 +710,7 @@ class NexusMessaging {
702
710
  this._saveMessageFn,
703
711
  async ({ body, _id }) => {
704
712
  const runResult = await this._executeWithPipeline(code, 'instruction', 'queue',
705
- async (preProcessResult, _shouldContinue, runId) => this.assistantProcessor.process({
713
+ async (preProcessResult, shouldContinue, runId) => this.assistantProcessor.process({
706
714
  code,
707
715
  runOptions: {
708
716
  prePromptResult: preProcessResult,
@@ -710,6 +718,8 @@ class NexusMessaging {
710
718
  toolChoice: 'none',
711
719
  turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
712
720
  runId,
721
+ shouldContinue,
722
+ signal: this.batchingManager.getAbortSignal(runId),
713
723
  }
714
724
  }),
715
725
  );
@@ -759,10 +769,12 @@ class NexusMessaging {
759
769
 
760
770
  let runResult = null;
761
771
  const executeTurn = () => this._executeWithPipeline(code, 'outreach', 'queue',
762
- async (preProcessResult, _shouldContinue, runId) => this.assistantProcessor.process({
772
+ async (preProcessResult, shouldContinue, runId) => this.assistantProcessor.process({
763
773
  code,
764
774
  runOptions: {
765
775
  prePromptResult: preProcessResult,
776
+ shouldContinue,
777
+ signal: this.batchingManager.getAbortSignal(runId),
766
778
  toolChoice: 'auto',
767
779
  turnKind: TURN_KIND.PROACTIVE_OUTREACH,
768
780
  outreachBrief: brief,
@@ -974,7 +986,7 @@ class NexusMessaging {
974
986
  if (!reply) return;
975
987
 
976
988
  await this._executeWithPipeline(code, 'system', 'queue',
977
- async (preProcessResult, _shouldContinue, runId) => {
989
+ async (preProcessResult, shouldContinue, runId) => {
978
990
  return await this.assistantProcessor.process({
979
991
  code,
980
992
  runOptions: {
@@ -982,6 +994,8 @@ class NexusMessaging {
982
994
  toolChoice: 'none',
983
995
  turnKind: TURN_KIND.SYSTEM,
984
996
  runId,
997
+ shouldContinue,
998
+ signal: this.batchingManager.getAbortSignal(runId),
985
999
  }
986
1000
  });
987
1001
  }
@@ -1010,11 +1024,37 @@ class NexusMessaging {
1010
1024
  * LIFECYCLE
1011
1025
  */
1012
1026
 
1013
- async disconnect() {
1027
+ async shutdown({ drainMs, abortGraceMs, teardownMs = 5000 } = {}) {
1028
+ if (this._shutdownPromise) return this._shutdownPromise;
1029
+ this.batchingManager.draining = true;
1014
1030
  this.queueReconciliation?.stop();
1015
- if (this.provider) await this.provider.disconnect();
1016
- if (this.queueAdapter) await this.queueAdapter.shutdown();
1031
+ this._shutdownPromise = this._shutdown({ drainMs, abortGraceMs, teardownMs });
1032
+ return this._shutdownPromise;
1033
+ }
1034
+
1035
+ async _shutdown({ drainMs, abortGraceMs, teardownMs }) {
1036
+ const result = await this.batchingManager.drain({
1037
+ ...(drainMs === undefined ? {} : { timeoutMs: drainMs }),
1038
+ ...(abortGraceMs === undefined ? {} : { abortGraceMs }),
1039
+ });
1040
+
1041
+ if (this.queueAdapter) {
1042
+ await withTimeout(this.queueAdapter.shutdown(), teardownMs, 'queueAdapter.shutdown')
1043
+ .catch(error => logger.warn('[NexusMessaging] Queue shutdown did not finish', { error: error.message }));
1044
+ }
1045
+
1046
+ if (typeof this.provider?.disconnect === 'function') {
1047
+ const disconnecting = Promise.resolve().then(() => this.provider.disconnect());
1048
+ await withTimeout(disconnecting, teardownMs, 'provider.disconnect')
1049
+ .catch(error => logger.warn('[NexusMessaging] Provider disconnect skipped', { error: error.message }));
1050
+ }
1051
+
1017
1052
  this.events.removeAllListeners();
1053
+ return result;
1054
+ }
1055
+
1056
+ async disconnect(options = {}) {
1057
+ return this.shutdown(options);
1018
1058
  }
1019
1059
  }
1020
1060
 
package/lib/index.d.ts CHANGED
@@ -248,7 +248,8 @@ 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
- disconnect(): Promise<void>;
251
+ shutdown(options?: ShutdownOptions): Promise<DrainResult>;
252
+ disconnect(options?: ShutdownOptions): Promise<DrainResult>;
252
253
  }
253
254
 
254
255
  export class MongoStorage {
@@ -337,7 +338,10 @@ declare module '@peopl-health/nexus' {
337
338
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
338
339
  processMessage(rawMessage: any): Promise<any>;
339
340
  isConnected(): boolean;
340
- disconnect(): Promise<void>;
341
+ beginDrain(): void;
342
+ isDraining(): boolean;
343
+ shutdown(options?: ShutdownOptions & { closeStorage?: boolean }): Promise<DrainResult>;
344
+ disconnect(options?: ShutdownOptions & { closeStorage?: boolean }): Promise<DrainResult>;
341
345
  getMessaging(): NexusMessaging;
342
346
  getStorage(): MongoStorage | null;
343
347
  getMessageParser(): MessageParser | null;
@@ -665,6 +669,28 @@ declare module '@peopl-health/nexus' {
665
669
  hooks?: Record<string, Function | Function[]>;
666
670
  }
667
671
 
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
+
668
694
  export class BatchingManager {
669
695
  constructor(options: {
670
696
  provider?: MessageProvider;
@@ -673,17 +699,19 @@ declare module '@peopl-health/nexus' {
673
699
  setProvider(provider: MessageProvider): void;
674
700
  isProcessing(chatId: string): boolean;
675
701
  isActiveRun(chatId: string, runId: string): boolean;
702
+ isDraining(): boolean;
676
703
  getAbortSignal(runId: string): AbortSignal | undefined;
704
+ drain(options?: { timeoutMs?: number; abortGraceMs?: number }): Promise<DrainResult>;
677
705
  handleBatchedProcessing(
678
706
  chatId: string,
679
707
  processingFn: (runId: string) => Promise<any>,
680
708
  sendResponseFn: (result: any) => Promise<void>
681
- ): Promise<void>;
709
+ ): Promise<TurnAdmission>;
682
710
  enqueueProcessing(
683
711
  chatId: string,
684
712
  processingFn: (runId: string) => Promise<any>,
685
713
  sendResponseFn: (result: any) => Promise<void>
686
- ): Promise<void>;
714
+ ): Promise<TurnAdmission>;
687
715
  }
688
716
 
689
717
  // ProcessingPipeline — hook lifecycle for all LLM operations
package/lib/index.js CHANGED
@@ -28,6 +28,7 @@ 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');
31
32
  const routes = require('./routes');
32
33
  const { resetAll } = require('./config/lifecycle');
33
34
  const { EvalProvider } = require('./eval/EvalProvider');
@@ -215,11 +216,24 @@ class Nexus {
215
216
  return this.messaging.isConnected();
216
217
  }
217
218
 
218
- async disconnect() {
219
- await this.messaging.disconnect();
220
- if (this.storage) {
219
+ beginDrain() {
220
+ this.messaging.getBatchingManager().draining = true;
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) {
221
230
  await this.storage.disconnect();
222
231
  }
232
+ return result;
233
+ }
234
+
235
+ async disconnect(options = {}) {
236
+ return this.shutdown(options);
223
237
  }
224
238
 
225
239
  getMessaging() { return this.messaging; }
@@ -231,6 +245,7 @@ class Nexus {
231
245
  module.exports = {
232
246
  createWorkflowRunner,
233
247
  Nexus,
248
+ DrainingError,
234
249
  TwilioProvider,
235
250
  BaileysProvider,
236
251
  MongoStorage,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.49.0-dev.7464",
3
+ "version": "5.49.0-dev.7465",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",