@peopl-health/nexus 5.76.5 → 5.76.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.
@@ -108,6 +108,7 @@ class AssistantProcessor {
108
108
  if (ctx) {
109
109
  ctx.outreachReminderType = runOptions.outreachCarrier?.reminderType || null;
110
110
  ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
111
+ ctx.outreachAllowsFollowUp = runOptions.outreachAllowsFollowUp !== false;
111
112
  ctx.checkInOtherPlans = runOptions.outreachBrief?.checkIn?.otherPlans ?? null;
112
113
  }
113
114
  if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
@@ -164,14 +164,15 @@ class BaseLLMProvider {
164
164
  const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
165
165
  const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
166
166
  const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
167
+ const allowFollowUp = assistant?.toolRuntimeContext?.outreachAllowsFollowUp !== false;
167
168
  const auditedPrompt = [
168
169
  devContent,
169
170
  catalogBlock,
170
171
  additionalInstructions ? this._operatorInstructionTurn(additionalInstructions, modelConfig).content : '',
171
- isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds })[0]?.content || '') : '',
172
+ isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds, allowFollowUp })[0]?.content || '') : '',
172
173
  ruleBlock,
173
174
  ].filter(Boolean).join('\n\n');
174
- const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null });
175
+ const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null, allowFollowUp });
175
176
 
176
177
  if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
177
178
  trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
@@ -306,7 +307,7 @@ class BaseLLMProvider {
306
307
  return { role: 'developer', content: `[DIRECTIVA DEL OPERADOR (prioritaria) para tu próxima respuesta al paciente]: ${additionalInstructions}` };
307
308
  }
308
309
 
309
- _buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null }) {
310
+ _buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null, allowFollowUp = true }) {
310
311
  let messages = this._convertItemsToApiFormat(context || []);
311
312
  if (Array.isArray(prePromptResult?.additionalMessages) && prePromptResult.additionalMessages.length > 0) {
312
313
  messages = [...messages, ...this._convertItemsToApiFormat(prePromptResult.additionalMessages)];
@@ -322,10 +323,10 @@ class BaseLLMProvider {
322
323
  ...this._buildFollowUpPolicyMessage(toolIds),
323
324
  ...this._buildFollowUpMessage(promptVariables),
324
325
  ...this._buildFollowUpCheckMessage(toolIds),
325
- ...this._buildContingencyCheckMessage(promptVariables, toolIds),
326
+ ...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
326
327
  ...this._buildClockMessage(promptVariables, interpolatedVariables),
327
328
  ...messages,
328
- ...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
329
+ ...this._buildOutreachBriefMessage({ outreachBrief, toolIds, allowFollowUp }),
329
330
  ...this._buildContingencyRuleMessage({ toolIds, promptVariables }),
330
331
  ]);
331
332
  }
@@ -347,7 +348,7 @@ class BaseLLMProvider {
347
348
 
348
349
  // Rides as a turn-scoped developer block, never as a stored message: a proactive brief is true for
349
350
  // this morning only, and anything persisted into history would still read as a standing rule weeks later.
350
- _buildOutreachBriefMessage({ outreachBrief = null, toolIds = [] }) {
351
+ _buildOutreachBriefMessage({ outreachBrief = null, toolIds = [], allowFollowUp = true }) {
351
352
  if (!outreachBrief || typeof outreachBrief !== 'object') return [];
352
353
  if (!(toolIds || []).includes(OUTREACH_DECISION_TOOL)) return [];
353
354
 
@@ -381,8 +382,13 @@ class BaseLLMProvider {
381
382
  if (since.length) parts.push('', '## Qué ha pasado desde entonces', ...since);
382
383
  parts.push(
383
384
  '',
384
- `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
385
- 'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
385
+ ...(allowFollowUp ? [
386
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
387
+ 'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
388
+ ] : [
389
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora o sostener.`,
390
+ 'En este turno no programes seguimientos ni recordatorios, aunque otras reglas lo pidan: si te responde, la conversación decide lo que sigue. Si sostienes, deja next_check_at en null.',
391
+ ]),
386
392
  '',
387
393
  'Si escribes, que sea para ELLA: lo que te contó, lo que quedó abierto, lo que quieres saber ahora.',
388
394
  'Tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre, entra directo a lo que quieres decirle, breve (menos de 500 caracteres) y con un emoji como máximo. Es un contacto sobre su cuidado: no le sumes invitaciones a charlas, sesiones ni actividades.',
@@ -495,12 +501,16 @@ class BaseLLMProvider {
495
501
  // Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
496
502
  // because an unresolved net later asks the patient a question they had already answered.
497
503
  // Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
498
- _buildContingencyCheckMessage(promptVariables, toolIds = []) {
504
+ // A net is marked fired before its own check-in turn runs, so during that turn its check-in has not reached the patient yet.
505
+ _buildContingencyCheckMessage(promptVariables, toolIds = [], outreachBrief = null) {
499
506
  if (!(toolIds || []).includes('setContingencyPlan')) return [];
500
507
  const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
501
508
  if (!active.length) return [];
509
+ const dueNet = outreachBrief?.checkIn?.planId || null;
502
510
  const waiting = active.map(({ carePlan: plan = {} } = {}) => {
503
- const fired = plan.status === 'fired_reminder' ? ' Su check-in ya se envió.' : '';
511
+ let fired = '';
512
+ if (dueNet && plan.planId === dueNet) fired = ' Su check-in es el de este turno: todavía no le ha llegado.';
513
+ else if (plan.status === 'fired_reminder') fired = ' Su check-in ya se envió.';
504
514
  return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
505
515
  });
506
516
  return [{
@@ -101,6 +101,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
101
101
  checkIn = {
102
102
  type,
103
103
  reminderId,
104
+ planId,
104
105
  dueAt: null,
105
106
  question: netQuestion,
106
107
  concern: net.carePlan.concern,
@@ -118,6 +119,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
118
119
  checkIn = {
119
120
  type,
120
121
  reminderId,
122
+ planId: null,
121
123
  dueAt: plan.fireAt || null,
122
124
  question: plan.message || question,
123
125
  concern: plan.windowReasoning,
@@ -583,6 +583,7 @@ async function runOutreachSweep({
583
583
  dryRun,
584
584
  reminderType: 'seguimiento',
585
585
  reminderPrefix: mode === 'monday_triage_recovery' ? 'recovery' : null,
586
+ allowFollowUp: mode === 'monday_triage_recovery',
586
587
  triggeredBy: `seguimiento:${candidate.recordId}`,
587
588
  });
588
589
  counts.run++;
@@ -59,6 +59,7 @@ const MAX_PAUSE_DAYS = 30;
59
59
  const ROUTINE_OUTREACH_START_HOUR = 11;
60
60
  const ROUTINE_OUTREACH_END_HOUR = 21;
61
61
  const PAUSED_ERROR = 'thread_paused — do not schedule a seguimiento in this turn.';
62
+ const NO_FOLLOW_UP_ERROR = 'follow_up_not_allowed — this proactive contact cannot schedule a reminder: if she replies, the conversation decides what comes next. Close with write, or hold with next_check_at null.';
62
63
 
63
64
  const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?$/;
64
65
  const FIRE_AT_FORMATS = ['YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm'];
@@ -88,6 +89,9 @@ async function handler(args = {}, context = {}) {
88
89
  const requestedAction = (args?.reminder_action_type || '').toLowerCase();
89
90
  if (requestedAction === 'cancel') return await cancelSeguimiento(args, runtime);
90
91
  if (requestedAction === 'pause_checkins') return await pauseCheckIns(args, runtime);
92
+ if (runtime.outreachAllowsFollowUp === false) {
93
+ return JSON.stringify({ success: false, error: NO_FOLLOW_UP_ERROR, data: {} });
94
+ }
91
95
 
92
96
  const reminderDate = (args?.reminder_date || '').trim();
93
97
  const description = sanitizeVariable(args?.reminder_description || '');
@@ -87,6 +87,9 @@ async function handler(args = {}, context = {}) {
87
87
  }
88
88
 
89
89
  const { value: nextCheckAt, rejected } = normalizeNextCheck(args?.next_check_at);
90
+ if (rawDecision === 'hold' && nextCheckAt && runtime.outreachAllowsFollowUp === false) {
91
+ return JSON.stringify({ success: false, error: 'next_check_at must be null: this proactive contact cannot plan a later check. Write now, or hold with next_check_at null.', data: {} });
92
+ }
90
93
  if (holdReason === 'contingency_already_armed' && !nextCheckAt && runtime.checkInOtherPlans === 0) {
91
94
  return JSON.stringify({ success: false, error: 'contingency_already_armed needs another active net or pending seguimiento, and this check-in has none: write now, or schedule a seguimiento and hold with rescheduled_for_cadence.', data: {} });
92
95
  }
@@ -1038,6 +1038,7 @@ class NexusMessaging {
1038
1038
  reminderType = 'seguimiento',
1039
1039
  reminderPrefix = null,
1040
1040
  replyToContact = false,
1041
+ allowFollowUp = true,
1041
1042
  dryRun = false,
1042
1043
  } = {}) {
1043
1044
  const outreachStartedAt = new Date().toISOString();
@@ -1069,6 +1070,7 @@ class NexusMessaging {
1069
1070
  outreachBrief: brief,
1070
1071
  preemptiveWindowRoute: true,
1071
1072
  outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
1073
+ outreachAllowsFollowUp: allowFollowUp,
1072
1074
  outreachStartedAt,
1073
1075
  // Stamped on the outbound so a delivered message joins back to the row that surfaced her.
1074
1076
  triggeredBy: triggeredBy || null,
package/lib/index.d.ts CHANGED
@@ -274,7 +274,7 @@ declare module '@peopl-health/nexus' {
274
274
  getWorkflowRunner(): WorkflowRunner;
275
275
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
276
276
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
277
- processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean }): Promise<OutreachDecision>;
277
+ processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
278
278
  processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
279
279
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
280
280
  isConnected(): boolean;
@@ -468,7 +468,7 @@ declare module '@peopl-health/nexus' {
468
468
  lastInboundAt?: string | null;
469
469
  lastOutboundAt?: string | null;
470
470
  lastOutreach?: string | null;
471
- checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
471
+ checkIn?: { type: string; reminderId?: string | null; planId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
472
472
  recentCheckIns?: string[];
473
473
  exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
474
474
  asOf?: string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.76.5",
3
+ "version": "5.76.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",