@peopl-health/nexus 4.7.0-dev.449 → 4.7.0-dev.451

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.
@@ -5,7 +5,6 @@ const { withTracing } = require('../../utils/tracingDecorator');
5
5
  const { logger } = require('../../utils/logger');
6
6
 
7
7
  const { getRecordByFilter } = require('../../services/airtableService.js');
8
- const { withThreadRecovery } = require('./threadRecoveryHelper');
9
8
 
10
9
  function getCurRow(baseID, code) {
11
10
  if (code.endsWith('@g.us')) {
@@ -29,11 +28,7 @@ const runAssistantAndWait = async ({ thread, assistant, message = null, runConfi
29
28
  const { polling, tools: configTools, ...config } = runConfig;
30
29
  const tools = assistant.getToolSchemas?.() || configTools || [];
31
30
 
32
- return withThreadRecovery(
33
- (currentThread = thread) => provider.executeRun({ thread: currentThread, message, assistant, tools, config, polling }),
34
- thread,
35
- variant
36
- );
31
+ return provider.executeRun({ thread, message, assistant, tools, config, polling });
37
32
  };
38
33
 
39
34
  const runAssistantWithRetries = async (thread, assistant, runConfig, patientReply = null) => {
@@ -15,7 +15,6 @@ const { BaseAssistant } = require('./assistants/BaseAssistant');
15
15
  const { AssistantProcessor } = require('./AssistantProcessor');
16
16
 
17
17
  const { getCurRow, runAssistantAndWait, runAssistantWithRetries } = require('./helpers/assistantHelper');
18
- const { withThreadRecovery } = require('./helpers/threadRecoveryHelper');
19
18
  const { analyzeImage, buildPrompt } = require('./helpers/llmsHelper');
20
19
 
21
20
  const { getProviderVariant, getAnthropicClient, setOpenAIProvider, getOpenAIProvider, requireOpenAIProvider, configureOpenAIProvider } = require('./config/llmConfig');
@@ -47,7 +46,6 @@ module.exports = {
47
46
  getCurRow,
48
47
  runAssistantAndWait,
49
48
  runAssistantWithRetries,
50
- withThreadRecovery,
51
49
  analyzeImage,
52
50
  buildPrompt,
53
51
  getProviderVariant,
@@ -160,14 +160,6 @@ class BaseLLMProvider {
160
160
  throw new Error(`${this.constructor.name} must implement _invokeModel()`);
161
161
  }
162
162
 
163
- async createConversation() {
164
- throw new Error(`createConversation is not supported by ${this.constructor.name}`);
165
- }
166
-
167
- async listMessages() {
168
- throw new Error(`listMessages is not supported by ${this.constructor.name}`);
169
- }
170
-
171
163
  async transcribeAudio() {
172
164
  throw new Error(`transcribeAudio is not supported by ${this.constructor.name}`);
173
165
  }
@@ -420,13 +412,6 @@ class BaseLLMProvider {
420
412
  if (segments.length > 1) logger.debug(`[${this.constructor.name}] Concatenated transcript detected, using last segment`, { segmentCount: segments.length });
421
413
  return segments[segments.length - 1].trim();
422
414
  }
423
-
424
- _ensureId(value) {
425
- if (!value) throw new Error('Identifier value is required');
426
- if (typeof value === 'string') return value;
427
- if (value?.id) return value.id;
428
- throw new Error('Unable to resolve identifier value');
429
- }
430
415
  }
431
416
 
432
417
  module.exports = {
@@ -10,9 +10,6 @@ const { logger } = require('../../utils/logger');
10
10
  const { BaseLLMProvider } = require('./BaseLLMProvider');
11
11
  const { handleFunctionCalls } = require('./OpenAIResponsesProviderTools');
12
12
 
13
- const CONVERSATION_PREFIX = 'conv_';
14
- const MAX_ITEMS_ON_CREATE = 20;
15
- const MAX_ITEMS_PER_BATCH = 20;
16
13
  const DEFAULT_MAX_FUNCTION_ROUNDS = 5;
17
14
 
18
15
  class OpenAIResponsesProvider extends BaseLLMProvider {
@@ -46,76 +43,12 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
46
43
  this.supportsPromptRegistry = true;
47
44
 
48
45
  this.responses = this.client.responses;
49
- this.conversations = this.client.conversations;
50
46
  }
51
47
 
52
48
  _operatorInstructionTurn(additionalInstructions) {
53
49
  return { role: 'developer', content: `[Instrucción del operador para tu próxima respuesta al paciente]: ${additionalInstructions}` };
54
50
  }
55
51
 
56
- async createConversation({ metadata, messages = [], toolResources } = {}) {
57
- const maxHistoricalMessages = this.conversationManager.maxHistoricalMessages;
58
- const capped = messages.length > maxHistoricalMessages;
59
- const messagesToProcess = capped ? messages.slice(-maxHistoricalMessages) : messages;
60
- if (capped) {
61
- logger.warn(`[createConversation] Capped ${messages.length} → ${maxHistoricalMessages} messages`);
62
- }
63
-
64
- const allItems = this._convertItemsToApiFormat(messagesToProcess);
65
- const initialItems = allItems.slice(0, MAX_ITEMS_ON_CREATE);
66
- const remainingItems = allItems.slice(MAX_ITEMS_ON_CREATE);
67
-
68
- if (remainingItems.length) {
69
- logger.info(`[createConversation] Batching: ${initialItems.length} initial + ${remainingItems.length} remaining`);
70
- }
71
-
72
- const conversation = await this._createConversationWithItems(metadata, initialItems, toolResources);
73
-
74
- if (remainingItems.length) {
75
- try {
76
- await this._addItemsInBatches(conversation.id, remainingItems);
77
- } catch (error) {
78
- logger.error('[createConversation] Failed to add remaining messages', { error: error.message });
79
- }
80
- }
81
-
82
- return conversation;
83
- }
84
-
85
- async _createConversationWithItems(metadata, items, toolResources) {
86
- const payload = {
87
- metadata,
88
- items: items.length ? items : undefined,
89
- tool_resources: toolResources
90
- };
91
- const { result } = await retryWithBackoff(
92
- () => this.conversations.create(payload),
93
- { providerName: this.constructor.name }
94
- );
95
- return result;
96
- }
97
-
98
- async _addItemsInBatches(threadId, items, batchSize = MAX_ITEMS_PER_BATCH) {
99
- if (!items?.length) return;
100
-
101
- const id = this._ensurethreadId(threadId);
102
- for (let i = 0; i < items.length; i += batchSize) {
103
- const batch = this._convertItemsToApiFormat(items.slice(i, i + batchSize));
104
- await retryWithBackoff(
105
- () => this.conversations.items.create(id, { items: batch }),
106
- { providerName: this.constructor.name }
107
- );
108
- }
109
- logger.info(`[_addItemsInBatches] Added ${items.length} messages in ${Math.ceil(items.length / batchSize)} batches`);
110
- }
111
-
112
- async listMessages({ threadId, order = 'desc', limit } = {}) {
113
- return this.client.conversations.items.list(
114
- this._ensurethreadId(threadId),
115
- { order, limit }
116
- );
117
- }
118
-
119
52
  async _invokeModel({
120
53
  instructions, input, toolSchemas = [], toolChoice = 'auto', followUpToolChoice = 'auto',
121
54
  modelConfig, metadata = {}, assistant, phiProcessor = null,
@@ -237,15 +170,6 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
237
170
  file, language, response_format: responseFormat, temperature, prompt,
238
171
  });
239
172
  }
240
-
241
- _ensurethreadId(value) {
242
- const id = this._ensureId(value);
243
- if (!id.startsWith(CONVERSATION_PREFIX)) {
244
- throw new Error(`Expected conversation id to start with '${CONVERSATION_PREFIX}'`);
245
- }
246
- return id;
247
- }
248
-
249
173
  }
250
174
 
251
175
  module.exports = {
@@ -196,14 +196,6 @@ class OpenRouterProvider extends OpenAIResponsesProvider {
196
196
  file, language, response_format: responseFormat, temperature, prompt,
197
197
  });
198
198
  }
199
-
200
- async createConversation() {
201
- throw new Error('createConversation is not supported by OpenRouterProvider');
202
- }
203
-
204
- async listMessages() {
205
- throw new Error('listMessages is not supported by OpenRouterProvider');
206
- }
207
199
  }
208
200
 
209
201
  module.exports = {
@@ -14,7 +14,7 @@ const { fetchConversationData, processConversations, startConversation } = requi
14
14
  const { getMessages, countMessages, aggregateMessages } = require('../services/messageService');
15
15
 
16
16
  const { sendMessage } = require('../core/NexusMessaging');
17
- const { withThreadRecovery, getProviderVariant, getOpenAIProvider } = require('../clinical');
17
+ const { getProviderVariant } = require('../clinical');
18
18
 
19
19
  const Message = mongoose.models.Message;
20
20
 
@@ -470,65 +470,45 @@ const markMessagesAsReadController = async (req, res) => {
470
470
  const getOpenAIThreadMessagesController = async (req, res) => {
471
471
  try {
472
472
  const { code } = req.params;
473
- const { limit = 50, order = 'desc', runId } = req.query;
474
- const variant = getProviderVariant();
475
-
473
+ const { order = 'desc' } = req.query;
474
+
476
475
  if (!code) {
477
476
  return res.status(400).json({
478
477
  success: false,
479
478
  error: 'Phone number is required'
480
479
  });
481
480
  }
482
-
483
- let thread = await Thread.findOne({ code: code }).sort({ createdAt: -1 });
481
+
482
+ const thread = await Thread.findOne({ code: code }).sort({ createdAt: -1 });
484
483
  if (!thread) {
485
484
  return res.status(404).json({
486
485
  success: false,
487
- error: 'No active OpenAI thread found for this phone number'
486
+ error: 'No active thread found for this phone number'
488
487
  });
489
488
  }
490
-
491
- const provider = getOpenAIProvider({ instantiate: true, variant });
492
- if (!provider) throw new Error('OpenAI provider not initialized');
493
-
494
- const queryParams = {
495
- threadId: thread.conversation_id,
496
- order,
497
- limit: parseInt(limit),
498
- ...(runId && { runId })
499
- };
500
- let threadRecreated = false;
501
-
502
- const messages = await withThreadRecovery(
503
- async (currentThread = thread) => {
504
- if (currentThread !== thread) {
505
- thread = currentThread;
506
- queryParams.threadId = currentThread.getConversationId();
507
- threadRecreated = true;
508
- }
509
- return await provider.listMessages(queryParams);
510
- },
511
- thread,
512
- variant
489
+
490
+ const parsedLimit = Math.min(Math.max(parseInt(req.query.limit) || 50, 1), 100);
491
+ const messages = await getMessages(
492
+ { numero: code, group_id: null },
493
+ { sort: { createdAt: order === 'asc' ? 1 : -1 }, limit: parsedLimit }
513
494
  );
514
-
495
+ messages.forEach(msg => { msg.body = msg.plainBody || msg.body; });
496
+
515
497
  res.status(200).json({
516
498
  success: true,
517
- variant,
499
+ variant: getProviderVariant(),
518
500
  phoneNumber: code,
519
501
  code,
520
502
  threadId: thread.conversation_id,
521
503
  assistantId: thread.assistant_id,
522
- messages: messages.data || messages,
523
- hasMore: messages.has_more || false,
524
- threadRecreated,
525
- pagination: { limit: parseInt(limit), order }
504
+ messages,
505
+ pagination: { limit: parsedLimit, order }
526
506
  });
527
507
  } catch (error) {
528
- logger.error('Error fetching OpenAI thread messages:', { error: error.message });
529
- res.status(500).json({
530
- success: false,
531
- error: error.message || 'Failed to fetch OpenAI thread messages'
508
+ logger.error('Error fetching thread messages:', { error: error.message });
509
+ res.status(500).json({
510
+ success: false,
511
+ error: error.message || 'Failed to fetch thread messages'
532
512
  });
533
513
  }
534
514
  };
package/lib/index.d.ts CHANGED
@@ -273,8 +273,6 @@ declare module '@peopl-health/nexus' {
273
273
  constructor(options?: { apiKey?: string; organization?: string; client?: any; defaultModels?: Record<string, string>; conversationManager?: any });
274
274
  getVariant(): string;
275
275
  getClient(): any;
276
- createConversation(options?: any): Promise<any>;
277
- listMessages(options?: any): Promise<any>;
278
276
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
279
277
  runConversation(config?: any): Promise<any>;
280
278
  transcribeAudio(options?: any): Promise<any>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "4.7.0-dev.449",
3
+ "version": "4.7.0-dev.451",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,50 +0,0 @@
1
- const { createLLMProvider } = require('../providers/createLLMProvider');
2
- const { logger } = require('../../utils/logger');
3
-
4
- const { Thread } = require('../../models/threadModel');
5
-
6
- const THREAD_ERROR_CODES = ['thread_not_found', 'invalid_thread_id'];
7
- const THREAD_ERROR_MESSAGES = ['No thread found', 'thread does not exist', 'Invalid thread'];
8
-
9
- const isThreadNotFoundError = (error) =>
10
- error?.status === 404 ||
11
- THREAD_ERROR_CODES.includes(error?.code) ||
12
- THREAD_ERROR_MESSAGES.some(msg => error?.message?.includes(msg));
13
-
14
- const recreateThread = async (thread, variant) => {
15
- const provider = createLLMProvider({ variant });
16
- const newConversation = await provider.createConversation({
17
- metadata: { code: thread.code }
18
- });
19
-
20
- await Thread.updateOne(
21
- { code: thread.code },
22
- { $set: { conversation_id: newConversation.id } }
23
- );
24
-
25
- logger.info('[threadRecovery] Recreated', {
26
- oldId: thread.conversation_id,
27
- newId: newConversation.id,
28
- code: thread.code
29
- });
30
- return Thread.findOne({ code: thread.code });
31
- };
32
-
33
- const withThreadRecovery = async (operation, thread, variant) => {
34
- try {
35
- return await operation();
36
- } catch (error) {
37
- if (isThreadNotFoundError(error) && thread) {
38
- logger.warn('[threadRecovery] Thread not found, recreating', { code: thread.code });
39
- const recoveredThread = await recreateThread(thread, variant);
40
- return operation(recoveredThread);
41
- }
42
- throw error;
43
- }
44
- };
45
-
46
- module.exports = {
47
- isThreadNotFoundError,
48
- recreateThread,
49
- withThreadRecovery
50
- };