@peopl-health/nexus 5.57.5 → 5.57.7

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);
@@ -46,11 +46,12 @@ function contentSignature(variables) {
46
46
  return crypto.createHash('sha1').update(source).digest('hex').slice(0, 12);
47
47
  }
48
48
 
49
- function buildSendClaimKey({ code, contentSid, variables, idempotencyKey } = {}) {
49
+ function buildSendClaimKey({ code, contactCode, contentSid, variables, idempotencyKey } = {}) {
50
50
  if (idempotencyKey) return `idem:${idempotencyKey}`;
51
51
  if (!code || !contentSid) return null;
52
52
  const signature = contentSignature(variables);
53
- return `tpl:${ensureWhatsAppFormat(code)}:${contentSid}${signature ? `:${signature}` : ''}`;
53
+ const recipient = contactCode ? `${ensureWhatsAppFormat(code)}>${ensureWhatsAppFormat(contactCode)}` : ensureWhatsAppFormat(code);
54
+ return `tpl:${recipient}:${contentSid}${signature ? `:${signature}` : ''}`;
54
55
  }
55
56
 
56
57
  async function isCompletedClaim(key) {
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.5",
3
+ "version": "5.57.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",