@peopl-health/nexus 3.1.6 → 3.2.0

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.
@@ -59,11 +59,17 @@ async function getLastMessages(code) {
59
59
  }
60
60
  }
61
61
 
62
- async function getLastNMessages(code, n) {
62
+ // Create a variable to use as a chackpoint
63
+ async function getLastNMessages(code, n, before=null) {
63
64
  try {
64
- const lastMessages = await Message.find({ numero: code })
65
+ const query = { numero: code };
66
+
67
+ if (before) query.createdAt = { $lte: before };
68
+
69
+ const lastMessages = await Message.find(query)
65
70
  .sort({ createdAt: -1 })
66
- .limit(n);
71
+ .limit(n)
72
+ .lean();
67
73
 
68
74
  if (!lastMessages || lastMessages.length === 0) {
69
75
  logger.info(`[getLastNMessages] No messages found for code: ${code ? `${code.substring(0, 3)}***${code.slice(-4)}` : 'unknown'}, limit: ${n}`);
@@ -201,7 +201,7 @@ class OpenAIResponsesProvider {
201
201
  logger.info('[OpenAIResponsesProvider] Context built', {
202
202
  conversationId,
203
203
  assistantId,
204
- lastContext: context[-1] || null
204
+ context
205
205
  });
206
206
 
207
207
  const filter = thread.code ? { code: thread.code, active: true } : null;
@@ -292,7 +292,7 @@ class OpenAIResponsesProvider {
292
292
 
293
293
  const promptConfig = { id: assistantId };
294
294
  if (promptVariables) promptConfig.variables = promptVariables;
295
- if (promptVersion) promptConfig.version = promptVersion;
295
+ if (promptVersion) promptConfig.version = String(promptVersion);
296
296
  logger.info('[OpenAIResponsesProvider] Prompt config', { promptConfig });
297
297
 
298
298
  const makeAPICall = (inputData) => retryWithBackoff(() =>
@@ -158,7 +158,9 @@ const replyAssistantCore = async (code, message_ = null, thread_ = null, runOpti
158
158
  const finalThread = thread;
159
159
 
160
160
  const messagesStart = Date.now();
161
- const lastMessage = await getLastNMessages(code, 1);
161
+ const beforeCheckpoint = message_?.createdAt ?
162
+ (message_.createdAt.$date ? new Date(message_.createdAt.$date) : message_.createdAt) : null;
163
+ const lastMessage = await getLastNMessages(code, 1, beforeCheckpoint);
162
164
  timings.get_messages_ms = Date.now() - messagesStart;
163
165
 
164
166
  if (!lastMessage || lastMessage.length === 0 || lastMessage[0].from_me) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "3.1.6",
3
+ "version": "3.2.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,80 +0,0 @@
1
- # Migration Guide
2
-
3
- This guide summarizes changes introduced in the current Nexus library refresh to help you migrate quickly with minimal breakage.
4
-
5
- ## TL;DR
6
- - Twilio remains first‑class; Baileys is supported for messaging but not for templates/flows (returns clear errors).
7
- - Message sends accept both `to` (preferred) and legacy `code` (normalized internally).
8
- - Templates and flows are supported through Twilio Content API; provider is auto‑injected into template controllers on `Nexus.initialize()` when Twilio is active.
9
- - New event bus + middleware model; existing handlers continue to work.
10
- - Storage adapter registry; use built‑in `mongo`/`noop` or plug your own adapter or instance.
11
- - Interactive/flows now have a provider‑agnostic API with Twilio mapping and event‑driven routing.
12
- - Assistant registry with optional override for `getAssistantById`.
13
-
14
- ## Messaging API
15
- - BREAKING (soft): Prefer `to` over `code` in `sendMessage`. Legacy `code` is still accepted and normalized internally.
16
-
17
- Before:
18
- ```js
19
- await nexus.sendMessage({ code: 'whatsapp:+521555...', message: 'Hi' });
20
- ```
21
- After (preferred):
22
- ```js
23
- await nexus.sendMessage({ code: '+521555...', message: 'Hi' });
24
- ```
25
-
26
- ## Templates & Flows (Twilio)
27
- - Twilio provider now implements content operations: `listTemplates`, `getTemplate`, `createTemplate`, `deleteTemplate`, `submitForApproval`, `checkApprovalStatus`.
28
- - On `Nexus.initialize()` with Twilio, the provider is auto‑injected into template controllers — default routes under `/api/template` work immediately.
29
- - Baileys: content/template operations are not supported; a clear error is thrown if called.
30
-
31
- ## Interactive & Flows (Provider‑agnostic)
32
- - New helper APIs:
33
- - `registerFlow(id, spec)`, `sendInteractive(nexus, { to, id | spec, variables })`.
34
- - Twilio: spec is converted to Content API payload and sent; if `spec.contentSid` is provided, it is used directly.
35
- - Baileys: currently unsupported.
36
- - Event‑driven routing:
37
- - `registerInteractiveHandler(match, handler)` and `attachInteractiveRouter(nexus)`; handlers are called when interactive messages are received.
38
-
39
- ## Middleware & Events
40
- - New event bus on `NexusMessaging`: subscribe to `*:received` and `*:handled` (message, media, interactive, command, keyword, flow).
41
- - New middleware: `nexus.getMessaging().use(type?, async (msg, nexus, next) => { ... })`.
42
- - Existing `setHandlers` and `onMessage`/`onInteractive`/etc. continue to work.
43
-
44
- ## Storage
45
- - Storage is now pluggable via a registry:
46
- - Built‑ins: `mongo` (default), `noop`.
47
- - Register your adapter: `registerStorage('src', MyStorageClass)` then `storage: 'src'`.
48
- - Or pass an instance: `storage: new MyStorageClass()`.
49
- - If the adapter has `connect()`, Nexus calls it automatically.
50
- - Controllers that rely on your Mongo models can continue to do so — no change required.
51
-
52
- ## Assistants
53
- - Register assistant classes at init:
54
- ```js
55
- await nexus.initialize({
56
- provider: 'twilio',
57
- llm: 'openai', llmConfig: { apiKey: process.env.OPENAI_API_KEY },
58
- assistants: {
59
- registry: { SUPPORT: SupportAssistantClass, SALES: SalesAssistantClass },
60
- getAssistantById: (id, thread) => null // optional override
61
- }
62
- });
63
- ```
64
- - An internal override for `getAssistantById` is supported; if provided, it is tried first, then fallback to registry.
65
-
66
- ## Utilities & Fixes
67
- - Utils index corrected to export existing files: `{ DefaultLLMProvider, MessageParser, logger }`.
68
- - Default OpenAI import fixed for CommonJS: `const OpenAI = require('openai');`.
69
- - Message model helpers unified; `LegacyMessage` references replaced with `Message` and a new exported `insertMessage`.
70
- - Types `declare module` now matches package name: `@peopl-health/nexus`.
71
-
72
- ## Routes
73
- - Built‑in route bundles remain available and importable via `setupDefaultRoutes(app)` or per‑group via `routes` + `createRouter()`.
74
-
75
- ## Testing
76
- - If your environment restricts forking, run Jest in‑band: `jest --runInBand`.
77
-
78
- ## Notes
79
- - Twilio approvals data shape varies by account/region. The provider looks up `content.links` and falls back to the documented REST path; data is normalized where possible.
80
- - Baileys: templates/flows remain unsupported; messaging and media send/receive are supported.