@peopl-health/nexus 5.57.6 → 5.57.8

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.
@@ -32,6 +32,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
32
32
  gateAttempts: { type: Number, default: null },
33
33
  gateLatencyMs: { type: Number, default: null },
34
34
  planLatencyMs: { type: Number, default: null },
35
+ planMaxOutputTokens: { type: Number, default: null },
35
36
  totalLatencyMs: { type: Number, default: null },
36
37
  triageStored: { type: Boolean, default: null },
37
38
  unmappedAnswerCount: { type: Number, default: null },
@@ -331,7 +331,7 @@ class AnthropicProvider extends BaseLLMProvider {
331
331
  return { response: this._normalizeResponse(finalResponse), toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
332
332
  }
333
333
 
334
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
334
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
335
335
  let modelConfig = {};
336
336
  let resolvedInstructions = instructions;
337
337
  if (promptId || presetId) {
@@ -344,7 +344,7 @@ class AnthropicProvider extends BaseLLMProvider {
344
344
 
345
345
  const apiConfig = {
346
346
  model: model || (modelConfig.model && modelConfig.model.replace(/^anthropic\//, '')) || this.defaults.structuredModel,
347
- max_tokens: modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
347
+ max_tokens: maxOutputTokens || modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
348
348
  };
349
349
  if (system) apiConfig.system = system;
350
350
 
@@ -195,7 +195,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
195
195
  return { response: finalResponse, toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
196
196
  }
197
197
 
198
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
198
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
199
199
  let modelConfig = null;
200
200
  let resolvedInstructions = instructions;
201
201
  if (promptId || presetId) {
@@ -205,7 +205,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
205
205
  }
206
206
 
207
207
  const apiConfig = {
208
- ...this._mapModelConfig(modelConfig || {}),
208
+ ...this._mapModelConfig({ ...(modelConfig || {}), ...(maxOutputTokens ? { max_output_tokens: maxOutputTokens } : {}) }),
209
209
  instructions: resolvedInstructions || '',
210
210
  };
211
211
  if (model) apiConfig.model = model;
@@ -70,6 +70,7 @@ const { prepareSupportAction } = require('./supportActionService');
70
70
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
71
71
  const GATE_MAX_ATTEMPTS = 2;
72
72
  const PLAN_MAX_ATTEMPTS = 2;
73
+ const PLAN_TRUNCATION_MAX_TOKENS = 16000;
73
74
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
74
75
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
75
76
  const DEFAULT_CLASSIFIER_WAIT_MS = [15000, 30000, 45000, 60000, 90000];
@@ -593,6 +594,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
593
594
  });
594
595
  settle.planLatencyMs = Date.now() - planStart;
595
596
  settle.attempts = planOutcome.attempts;
597
+ settle.planMaxOutputTokens = planOutcome.planMaxOutputTokens;
596
598
  if (planOutcome.safetyUncertain) settle.supportSafetyCleared = false;
597
599
  if (planOutcome.failure) return finish({ ...planOutcome.failure, autoRepairs: [...gateRepairs, ...(planOutcome.repairs || [])] });
598
600
  const { plan, planRepairs, qualityWarnings } = planOutcome;
@@ -850,7 +852,8 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
850
852
  const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
851
853
  let lastIssues = [];
852
854
  let safetyUncertain = false;
853
- const outcome = (result) => ({ ...result, safetyUncertain });
855
+ let maxOutputTokens = null;
856
+ const outcome = (result) => ({ ...result, safetyUncertain, planMaxOutputTokens: maxOutputTokens });
854
857
  const buildPlan = (takeaways, elements) => new RecommendationPlan({
855
858
  runId: rid,
856
859
  patientId: code,
@@ -883,6 +886,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
883
886
  presetId,
884
887
  input: [{ role: 'user', content }],
885
888
  metadata: { subAgent: 'triage-plan', runId: rid },
889
+ ...(maxOutputTokens ? { maxOutputTokens } : {}),
886
890
  }), { code, rid, stage: 'plan', attempt, budget });
887
891
  } catch {
888
892
  lastIssues = [];
@@ -893,6 +897,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
893
897
  lastIssues = [{ path: 'plan', problem: `respuesta incompleta del proveedor (status=${result.status})` }];
894
898
  firstEvidence = firstEvidence ?? rawEvidence(result);
895
899
  if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
900
+ if (hitTokenLimit(result)) maxOutputTokens = truncationBudget(result, maxOutputTokens);
896
901
  continue;
897
902
  }
898
903
  const parsed = safeParse(readStructuredText(result), null);
@@ -955,6 +960,17 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
955
960
  return outcome({ attempts: PLAN_MAX_ATTEMPTS, failure: { status: 'failed', stage: 'plan', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
956
961
  }
957
962
 
963
+ // Anthropic reports stop_reason; OpenAI Responses reports incomplete_details.reason.
964
+ function hitTokenLimit(result) {
965
+ return result?.stop_reason === 'max_tokens' || result?.incomplete_details?.reason === 'max_output_tokens';
966
+ }
967
+
968
+ function truncationBudget(result, current) {
969
+ const used = Number(result?.usage?.output_tokens);
970
+ const next = Number.isFinite(used) && used > 0 ? used * 2 : PLAN_TRUNCATION_MAX_TOKENS;
971
+ return Math.min(Math.max(next, current || 0), PLAN_TRUNCATION_MAX_TOKENS);
972
+ }
973
+
958
974
  function rawEvidence(result) {
959
975
  const text = str(readStructuredText(result)).trim();
960
976
  if (text) return text.slice(0, RAW_EXCERPT_MAX);
@@ -40,8 +40,10 @@ const getOfficeMessagesController = async (req, res) => {
40
40
 
41
41
  const sendOfficeMessageController = async (req, res) => {
42
42
  try {
43
- const { triggeredBy, text, clientMessageId } = req.body || {};
44
- const delivery = await sendOfficeMessage({ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId });
43
+ const { triggeredBy, text, clientMessageId, fileUrl, fileName } = req.body || {};
44
+ const delivery = await sendOfficeMessage({
45
+ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId, fileUrl, fileName,
46
+ });
45
47
  res.status(201).json({ success: true, ...delivery });
46
48
  } catch (error) {
47
49
  respondWithError(res, error, 'sending office message', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
package/lib/index.d.ts CHANGED
@@ -314,7 +314,7 @@ declare module '@peopl-health/nexus' {
314
314
  getVariant(): string;
315
315
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
316
316
  runConversation(config?: any): Promise<any>;
317
- runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
317
+ runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
318
318
  }
319
319
 
320
320
  export interface LLMProvider {
@@ -322,7 +322,7 @@ declare module '@peopl-health/nexus' {
322
322
  getClient?(): any;
323
323
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
324
324
  runConversation(config?: any): Promise<any>;
325
- runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
325
+ runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
326
326
  transcribeAudio?(options?: any): Promise<any>;
327
327
  }
328
328
 
@@ -1,4 +1,5 @@
1
1
  const { Estado_General_ID, Monitoreo_ID } = require('../config/airtableConfig');
2
+ const runtimeConfig = require('../config/runtimeConfig');
2
3
 
3
4
  const { httpError, requiredText } = require('../utils/httpErrorUtils');
4
5
  const { inlineOf } = require('../utils/coercionUtils');
@@ -7,6 +8,7 @@ const { logger } = require('../utils/logger');
7
8
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
9
  const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
9
10
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
11
+ const { prepareMessageMedia } = require('../helpers/mediaHelper');
10
12
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
11
13
  const { sendMessage } = require('../core/NexusMessaging');
12
14
 
@@ -14,20 +16,23 @@ const { getRecordByFilter } = require('./airtableService');
14
16
  const { getMessages } = require('./messageService');
15
17
  const { getPatientInformation } = require('./patientService');
16
18
 
17
- const ASSISTANT_FIELDS = ['email', 'doctor_match', 'office_label', 'template_content_sid'];
18
19
  const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
19
20
  const HIDDEN_ORIGINS = ['system', 'instruction'];
20
21
  const DEFAULT_MESSAGE_LIMIT = 30;
21
22
  const MAX_MESSAGE_LIMIT = 50;
22
23
  const MAX_TEXT_LENGTH = 1500;
23
24
  const MAX_TEMPLATE_TEXT_LENGTH = 800;
25
+ const DOCUMENT_TEMPLATE_DEFAULT_TEXT = 'Le compartimos un documento.';
26
+ const DOCUMENT_FILE_TYPE = 'document';
24
27
 
25
28
  async function getOfficeAssistant(email) {
26
29
  const normalized = String(email ?? '').trim().toLowerCase();
27
30
  if (!normalized) return null;
28
31
 
29
32
  const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {active})`;
30
- const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, ASSISTANT_FIELDS, true) || [];
33
+ // No field list: Airtable rejects a listed column that does not exist yet, which would take the whole office view down
34
+ // until document_template_content_sid is added.
35
+ const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, undefined, true) || [];
31
36
  const doctor = inlineOf(assistant?.doctor_match);
32
37
  const label = inlineOf(assistant?.office_label);
33
38
  if (!doctor || !label) return null;
@@ -37,6 +42,7 @@ async function getOfficeAssistant(email) {
37
42
  doctor,
38
43
  label,
39
44
  templateContentSid: inlineOf(assistant.template_content_sid) || null,
45
+ documentTemplateContentSid: inlineOf(assistant.document_template_content_sid) || null,
40
46
  };
41
47
  }
42
48
 
@@ -100,34 +106,74 @@ async function readOfficeMessages({ requestedBy, code, limit }) {
100
106
  };
101
107
  }
102
108
 
103
- function officeMessage({ assistant, patientCode, text, inWindow }) {
109
+ function officeDocumentUrl(fileUrl) {
110
+ if (!fileUrl) return null;
111
+ const bucketName = runtimeConfig.get('AWS_S3_BUCKET_NAME');
112
+ let url = null;
113
+ try {
114
+ url = new URL(String(fileUrl));
115
+ } catch {
116
+ url = null;
117
+ }
118
+ // The approved document template pins the bucket host and takes the rest of the URL as a variable.
119
+ const bucketHost = new RegExp(`^${escapeRegExp(bucketName ?? '')}\\.s3(\\.[a-z0-9-]+)?\\.amazonaws\\.com$`);
120
+ if (!bucketName || url?.protocol !== 'https:' || !bucketHost.test(url.hostname)) {
121
+ throw httpError(400, 'The document must be uploaded before it is sent');
122
+ }
123
+ return url;
124
+ }
125
+
126
+ // Twilio needs the file type in a template's media URL, and uploads are stored without an
127
+ // extension, so the template gets the copy prepareMessageMedia stores with one.
128
+ async function templateDocumentOf(document, patientCode) {
129
+ const { mediaUrl } = await prepareMessageMedia({
130
+ code: patientCode, fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name,
131
+ });
132
+ // prepareMessageMedia answers with the original URL when the copy fails, and that one has no file type.
133
+ if (!mediaUrl || mediaUrl === document.url.href) throw httpError(502, 'The document could not be prepared for the template');
134
+ return { ...document, url: officeDocumentUrl(mediaUrl) };
135
+ }
136
+
137
+ function officeMessage({ assistant, patientCode, text, inWindow, document }) {
138
+ const attachment = document ? { fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name } : {};
104
139
  if (inWindow) {
105
140
  if (text.length > MAX_TEXT_LENGTH) throw httpError(422, `The message exceeds ${MAX_TEXT_LENGTH} characters`);
106
- return { code: patientCode, body: `${assistant.label}: ${text}` };
141
+ return { code: patientCode, body: text ? `${assistant.label}: ${text}` : assistant.label, ...attachment };
107
142
  }
108
143
 
109
- const templateText = text.replace(/\s+/g, ' ').trim();
144
+ const templateText = text.replace(/\s+/g, ' ').trim() || DOCUMENT_TEMPLATE_DEFAULT_TEXT;
110
145
  if (templateText.length > MAX_TEMPLATE_TEXT_LENGTH) {
111
146
  throw httpError(422, `Outside the 24-hour window the message is sent as a template and cannot exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters`);
112
147
  }
113
- if (!assistant.templateContentSid) throw httpError(503, 'The office template is not configured; the patient is outside the 24-hour window');
148
+ const contentSid = document ? assistant.documentTemplateContentSid : assistant.templateContentSid;
149
+ if (!contentSid) {
150
+ const template = document ? 'office document template' : 'office template';
151
+ throw httpError(503, `The ${template} is not configured; the patient is outside the 24-hour window`);
152
+ }
114
153
  return {
115
154
  code: patientCode,
116
155
  body: `${assistant.label}: ${templateText}`,
117
- contentSid: assistant.templateContentSid,
118
- variables: { 1: templateText },
156
+ contentSid,
157
+ variables: document
158
+ ? { 1: templateText, 2: `${document.url.pathname.slice(1)}${document.url.search}` }
159
+ : { 1: templateText },
160
+ ...attachment,
119
161
  };
120
162
  }
121
163
 
122
- async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
164
+ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId, fileUrl, fileName }) {
123
165
  const assistant = await requireOfficeAssistant(requestedBy);
124
166
  const patientCode = await officePatientCode(assistant, code);
125
- const messageText = requiredText(text, 'text');
167
+ const url = officeDocumentUrl(fileUrl);
168
+ const document = url ? { url, name: fileName } : null;
169
+ const messageText = document ? String(text ?? '').trim() : requiredText(text, 'text');
126
170
  const messageKey = requiredText(clientMessageId, 'clientMessageId');
127
171
 
128
172
  const inWindow = await isWithin24HourWindow(patientCode);
173
+ const isDocumentTemplate = Boolean(document && !inWindow && assistant.documentTemplateContentSid);
174
+ const sentDocument = isDocumentTemplate ? await templateDocumentOf(document, patientCode) : document;
129
175
  const message = {
130
- ...officeMessage({ assistant, patientCode, text: messageText, inWindow }),
176
+ ...officeMessage({ assistant, patientCode, text: messageText, inWindow, document: sentDocument }),
131
177
  triggeredBy: assistant.email,
132
178
  idempotencyKey: `office:${patientCode}:${messageKey}`,
133
179
  };
@@ -143,6 +189,7 @@ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
143
189
  assistant: assistant.email,
144
190
  code: redactDirectIdentifiers(patientCode),
145
191
  transport,
192
+ hasDocument: Boolean(document),
146
193
  duplicate: result?.duplicate === true,
147
194
  });
148
195
  return { transport, messageId: result?.messageId || null, duplicate: result?.duplicate === true };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.6",
3
+ "version": "5.57.8",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",