@peopl-health/nexus 5.49.0-dev.7483 → 5.49.0-dev.7485

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.
@@ -66,7 +66,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
66
66
  instructions, input, toolSchemas = [], toolChoice = 'auto', followUpToolChoice = 'auto',
67
67
  modelConfig, metadata = {}, assistant, phiProcessor = null,
68
68
  promptVariables = null, promptVersion = null, resolvedPromptId = null, resolvedPresetId = null, trace = null,
69
- shadow = false, shouldContinue = null, onFirstIteration = null, isOutreach = false
69
+ shadow = false, shouldContinue = null, onFirstIteration = null, isOutreach = false, signal = null
70
70
  }, options = {}) {
71
71
  const executeTools = options.toolExecutor || handleFunctionCalls;
72
72
  const superseded = () => isSuperseded(shouldContinue);
@@ -105,8 +105,9 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
105
105
  });
106
106
  }
107
107
 
108
+ const requestOptions = signal ? { signal } : undefined;
108
109
  const makeAPICall = (inputData) => retryWithBackoff(
109
- () => this.client.responses.create({ input: inputData, ...apiCallConfig }),
110
+ () => this.client.responses.create({ input: inputData, ...apiCallConfig }, requestOptions),
110
111
  { providerName: this.constructor.name }
111
112
  );
112
113
 
@@ -39,7 +39,7 @@ class OpenRouterProvider extends OpenAIResponsesProvider {
39
39
 
40
40
  async _invokeModel({
41
41
  instructions, input, toolSchemas = [], toolChoice = 'auto', followUpToolChoice = 'auto',
42
- modelConfig, assistant, phiProcessor = null, trace = null, shouldContinue = null
42
+ modelConfig, assistant, phiProcessor = null, trace = null, shouldContinue = null, signal = null
43
43
  }, options = {}) {
44
44
  const executeTools = options.toolExecutor || handleFunctionCalls;
45
45
  let totalRetries = 0;
@@ -60,8 +60,9 @@ class OpenRouterProvider extends OpenAIResponsesProvider {
60
60
  apiCallConfig.tool_choice = toolChoice;
61
61
  }
62
62
 
63
+ const requestOptions = signal ? { signal } : undefined;
63
64
  const makeAPICall = (msgs) => retryWithBackoff(
64
- () => this.client.chat.completions.create({ messages: msgs, ...apiCallConfig }),
65
+ () => this.client.chat.completions.create({ messages: msgs, ...apiCallConfig }, requestOptions),
65
66
  { providerName: this.constructor.name }
66
67
  );
67
68
 
@@ -195,22 +195,15 @@ class BatchingManager {
195
195
  this.onAbandoned?.({ chatId, runId, reason: 'shutdown_drain_timeout' });
196
196
  }
197
197
 
198
- await this._settleWithin(
199
- Promise.allSettled([...this.chatQueues.values()]),
200
- abortGraceMs,
201
- { keepAlive: true },
202
- );
198
+ await this._settleWithin(Promise.allSettled([...this.chatQueues.values()]), abortGraceMs);
203
199
 
204
200
  this._disposeTimers();
205
201
  return { drained: false, waitedMs: Date.now() - startedAt, abandoned };
206
202
  }
207
203
 
208
- _settleWithin(promise, ms, { keepAlive = false } = {}) {
204
+ _settleWithin(promise, ms) {
209
205
  let timer;
210
- const expiry = new Promise(resolve => {
211
- timer = setTimeout(resolve, Math.max(ms, 0));
212
- if (!keepAlive) timer.unref?.();
213
- });
206
+ const expiry = new Promise(resolve => { timer = setTimeout(resolve, Math.max(ms, 0)); });
214
207
  return Promise.race([promise, expiry]).finally(() => clearTimeout(timer));
215
208
  }
216
209
 
@@ -653,7 +653,7 @@ class NexusMessaging {
653
653
  }
654
654
 
655
655
  async _handleWithCheckAfter(chatId) {
656
- await this._executeWithPipeline(chatId, 'message', 'preempt',
656
+ return await this._executeWithPipeline(chatId, 'message', 'preempt',
657
657
  async (preProcessResult, shouldContinue, runId) => {
658
658
  return await this._processMessages(chatId, async () => {
659
659
  const resolved = await this.assistantProcessor.resolveThread(chatId);
@@ -1027,7 +1027,8 @@ class NexusMessaging {
1027
1027
  async shutdown({ drainMs, abortGraceMs, teardownMs = 5000 } = {}) {
1028
1028
  if (this._shutdownPromise) return this._shutdownPromise;
1029
1029
  this.batchingManager.draining = true;
1030
- this.queueReconciliation?.stop();
1030
+ this._reconciliationStopped = Promise.resolve(this.queueReconciliation?.stop())
1031
+ .catch(error => logger.warn('[NexusMessaging] Reconciliation sweep did not settle', { error: error.message }));
1031
1032
  this._shutdownPromise = this._shutdown({ drainMs, abortGraceMs, teardownMs });
1032
1033
  return this._shutdownPromise;
1033
1034
  }
@@ -1038,6 +1039,9 @@ class NexusMessaging {
1038
1039
  ...(abortGraceMs === undefined ? {} : { abortGraceMs }),
1039
1040
  });
1040
1041
 
1042
+ await withTimeout(this._reconciliationStopped, teardownMs, 'queueReconciliation.stop')
1043
+ .catch(error => logger.warn('[NexusMessaging] Reconciliation sweep did not settle in time', { error: error.message }));
1044
+
1041
1045
  if (this.queueAdapter) {
1042
1046
  await withTimeout(this.queueAdapter.shutdown(), teardownMs, 'queueAdapter.shutdown')
1043
1047
  .catch(error => logger.warn('[NexusMessaging] Queue shutdown did not finish', { error: error.message }));
package/lib/index.js CHANGED
@@ -20,6 +20,7 @@ const {
20
20
  } = require('./clinical');
21
21
  const { initialize: initializeFhir } = require('./fhir');
22
22
  const { logger } = require('./utils/logger');
23
+ const { withTimeout } = require('./utils/timeoutUtils');
23
24
  const runtimeConfig = require('./config/runtimeConfig');
24
25
  const { setModelDatabases, setModelDatabase, getModelDatabase, connect: mongoConnect, disconnect: mongoDisconnect, getConnection: mongoGetConnection } = require('./config/mongoConfig');
25
26
  const { TwilioProvider } = require('./adapters/TwilioProvider');
@@ -225,11 +226,16 @@ class Nexus {
225
226
  }
226
227
 
227
228
  async shutdown({ drainMs, abortGraceMs, teardownMs, closeStorage = true } = {}) {
228
- const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
229
- if (closeStorage && this.storage) {
230
- await this.storage.disconnect();
231
- }
232
- return result;
229
+ if (this._shutdownPromise) return this._shutdownPromise;
230
+ this._shutdownPromise = (async () => {
231
+ const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
232
+ if (closeStorage && this.storage) {
233
+ await withTimeout(this.storage.disconnect(), teardownMs ?? 5000, 'storage.disconnect')
234
+ .catch(error => logger.warn('[Nexus] Storage disconnect did not finish', { error: error.message }));
235
+ }
236
+ return result;
237
+ })();
238
+ return this._shutdownPromise;
233
239
  }
234
240
 
235
241
  async disconnect(options = {}) {
@@ -26,20 +26,24 @@ class QueueReconciliationService {
26
26
  this.staleAfterMs = staleAfterMs;
27
27
  this.batchLimit = batchLimit;
28
28
  this.timer = null;
29
+ this.stopped = false;
30
+ this.inFlight = new Set();
29
31
  }
30
32
 
31
33
  start() {
32
34
  if (this.timer) return this.timer;
35
+ this.stopped = false;
33
36
 
34
- this.runOnce().catch((error) =>
35
- logger.warn('[QueueReconciliation] Startup pass failed', { error: error.message })
36
- );
37
+ const launch = (label) => {
38
+ const pass = this.runOnce()
39
+ .catch((error) => logger.warn(`[QueueReconciliation] ${label} failed`, { error: error.message }))
40
+ .finally(() => this.inFlight.delete(pass));
41
+ this.inFlight.add(pass);
42
+ };
37
43
 
38
- this.timer = setInterval(() => {
39
- this.runOnce().catch((error) =>
40
- logger.warn('[QueueReconciliation] Sweep failed', { error: error.message })
41
- );
42
- }, this.intervalMs);
44
+ launch('Startup pass');
45
+
46
+ this.timer = setInterval(() => launch('Sweep'), this.intervalMs);
43
47
 
44
48
  if (typeof this.timer.unref === 'function') this.timer.unref();
45
49
 
@@ -47,12 +51,16 @@ class QueueReconciliationService {
47
51
  }
48
52
 
49
53
  stop() {
50
- if (!this.timer) return;
51
- clearInterval(this.timer);
52
- this.timer = null;
54
+ this.stopped = true;
55
+ if (this.timer) {
56
+ clearInterval(this.timer);
57
+ this.timer = null;
58
+ }
59
+ return Promise.allSettled([...this.inFlight]).then(() => undefined);
53
60
  }
54
61
 
55
62
  async runOnce() {
63
+ if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0 };
56
64
  const since = new Date(Date.now() - this.lookbackMs);
57
65
  const [scheduledMessages, recoveries, heldMessages] = await Promise.all([
58
66
  this._reEnqueueScheduledMessages(since),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.49.0-dev.7483",
3
+ "version": "5.49.0-dev.7485",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",