@peopl-health/nexus 5.58.2 → 5.58.4

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.
@@ -14,7 +14,7 @@ const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
14
14
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
15
15
  const { getRecordByFilter } = require('../../services/airtableService');
16
16
  const { getMessages, countMessages } = require('../../services/messageService');
17
- const { getTurnScopedToolNames } = require('../../services/toolRegistryService');
17
+ const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
18
18
  const { CURRENT_TURN } = require('../promptPlacement');
19
19
 
20
20
  const { MemoryManager } = require('./MemoryManager');
@@ -79,9 +79,10 @@ class DefaultMemoryManager extends MemoryManager {
79
79
  const turnStart = ordered.length - currentTurn.length;
80
80
 
81
81
  const skipTools = new Set(getTurnScopedToolNames());
82
+ const replayArgs = getReplayArgsByTool();
82
83
 
83
84
  const context = ordered.flatMap((msg, index) => {
84
- const toolItems = getMessageTools(msg, { skipTools });
85
+ const toolItems = getMessageTools(msg, { skipTools, replayArgs });
85
86
  if (index >= turnStart) return toolItems;
86
87
  const role = this._resolveContextRole(msg);
87
88
  const prefix = this._speakerPrefix(msg, role);
@@ -221,6 +221,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
221
221
  const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
222
222
  const priorRank = prior ? EMERGENCY_URGENCY_RANK[prior.urgencyFhir] : undefined;
223
223
  const mergeable = Boolean(prior) && rank !== undefined && priorRank !== undefined && rank <= priorRank;
224
+ const belowPrior = mergeable && rank < priorRank;
224
225
  const meta = {};
225
226
 
226
227
  return auditedWrite({
@@ -241,14 +242,21 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
241
242
 
242
243
  const open = mergeable ? await readEmergencyRow(prior.recordId, code) : null;
243
244
  if (open) {
244
- const merged = [open['Documentación_emergencia'], documentation].filter(Boolean).join('\n\n');
245
+ const incoming = belowPrior
246
+ ? [symptom && `Síntoma: ${symptom}`, suspectedCondition && `Sospecha: ${suspectedCondition}`, recommendedAction && `Acción recomendada: ${recommendedAction}`]
247
+ .filter(Boolean).join(' · ')
248
+ : '';
249
+ const note = [incoming, documentation].filter(Boolean).join('\n');
250
+ const merged = [open['Documentación_emergencia'], note].filter(Boolean).join('\n\n');
251
+ let update = merged ? { ...fields, 'Documentación_emergencia': merged } : fields;
252
+ if (belowPrior) update = { 'Documentación_emergencia': merged };
245
253
  const updated = await airtableService.updateRecordByFilter(
246
- Monitoreo_ID, 'emergencies', `RECORD_ID() = '${prior.recordId}'`,
247
- merged ? { ...fields, 'Documentación_emergencia': merged } : fields, code
254
+ Monitoreo_ID, 'emergencies', `RECORD_ID() = '${prior.recordId}'`, update, code
248
255
  );
249
256
  if (updated?.length) {
250
257
  meta.mergedInto = prior.recordId;
251
- await rememberEmergency(code, prior.recordId, urgencyFhir);
258
+ if (belowPrior) meta.keptUrgencyFhir = prior.urgencyFhir;
259
+ await rememberEmergency(code, prior.recordId, belowPrior ? prior.urgencyFhir : urgencyFhir);
252
260
  return updated;
253
261
  }
254
262
  }
@@ -8,6 +8,7 @@ const EMPTY_OUTBOUND_FALLBACK = 'Recibí tu mensaje. Si quieres contarme más o
8
8
 
9
9
  const definition = {
10
10
  name: 'DeliverPatientMessage',
11
+ replayArgs: ['message_text', 'purpose'],
11
12
  description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
12
13
  strict: false,
13
14
  parameters: {
@@ -54,6 +54,7 @@ function registerClinicalTools() {
54
54
  parameters: tool.definition.parameters,
55
55
  strict: tool.definition.strict,
56
56
  replayScope: tool.definition.replayScope,
57
+ replayArgs: tool.definition.replayArgs,
57
58
  handler: tool.handler,
58
59
  });
59
60
  }
@@ -1,6 +1,7 @@
1
1
  const moment = require('moment-timezone');
2
2
 
3
3
  const { logger } = require('../utils/logger');
4
+ const { isPlainObject } = require('../utils/jsonUtils');
4
5
 
5
6
  function formatMessage(reply) {
6
7
  try {
@@ -38,7 +39,7 @@ function formatMessage(reply) {
38
39
  }
39
40
  }
40
41
 
41
- function getMessageTools(reply, { skipTools } = {}) {
42
+ function getMessageTools(reply, { skipTools, replayArgs } = {}) {
42
43
  const tools = reply?.tools_executed;
43
44
  if (!tools?.length) return [];
44
45
 
@@ -54,9 +55,13 @@ function getMessageTools(reply, { skipTools } = {}) {
54
55
  if (skipTools?.has(t.tool_name)) return;
55
56
  const safeId = `${msgId}_${i}`.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 80);
56
57
  const functionCallId = `fc_${safeId}`;
57
- const argsStr = JSON.stringify(t.tool_arguments ?? {});
58
+ const keepArgs = replayArgs?.get(t.tool_name);
59
+ const args = keepArgs
60
+ ? Object.fromEntries(keepArgs.filter(arg => isPlainObject(t.tool_arguments) && Object.hasOwn(t.tool_arguments, arg)).map(arg => [arg, t.tool_arguments[arg]]))
61
+ : t.tool_arguments ?? {};
62
+ const argsStr = JSON.stringify(args);
58
63
  let outputStr;
59
- if (t.tool_output != null) {
64
+ if (t.tool_output != null && !keepArgs) {
60
65
  outputStr = typeof t.tool_output === 'string'
61
66
  ? t.tool_output
62
67
  : JSON.stringify(t.tool_output);
@@ -9,7 +9,7 @@ const REPLAY_SCOPES = ['turn', 'thread'];
9
9
  const DEFAULT_REPLAY_SCOPE = 'thread';
10
10
 
11
11
  function registerTool(config) {
12
- const { name, handler, description, parameters, strict, replayScope } = config;
12
+ const { name, handler, description, parameters, strict, replayScope, replayArgs } = config;
13
13
 
14
14
  if (!name || typeof name !== 'string') {
15
15
  throw new Error('registerTool requires a string name');
@@ -20,6 +20,9 @@ function registerTool(config) {
20
20
  if (replayScope !== undefined && !REPLAY_SCOPES.includes(replayScope)) {
21
21
  throw new Error(`registerTool '${name}' got an unknown replayScope '${replayScope}'`);
22
22
  }
23
+ if (replayArgs !== undefined && (!Array.isArray(replayArgs) || replayArgs.some(arg => typeof arg !== 'string'))) {
24
+ throw new Error(`registerTool '${name}' needs replayArgs as an array of argument names`);
25
+ }
23
26
 
24
27
  const existing = registry.get(name);
25
28
  if (existing) {
@@ -49,6 +52,7 @@ function registerTool(config) {
49
52
  // re-registers with its own handler and omits the field would otherwise silently put a
50
53
  // turn-scoped payload back into cross-turn history, which is exactly what this prevents.
51
54
  replayScope: replayScope || existing?.replayScope || DEFAULT_REPLAY_SCOPE,
55
+ replayArgs: replayArgs || existing?.replayArgs || null,
52
56
  });
53
57
  }
54
58
 
@@ -60,6 +64,14 @@ function getTurnScopedToolNames() {
60
64
  return names;
61
65
  }
62
66
 
67
+ function getReplayArgsByTool() {
68
+ const byTool = new Map();
69
+ for (const [name, tool] of registry) {
70
+ if (tool.replayArgs) byTool.set(name, tool.replayArgs);
71
+ }
72
+ return byTool;
73
+ }
74
+
63
75
  function getToolSchemas(names) {
64
76
  if (names && names.length > 0) {
65
77
  return names
@@ -101,5 +113,6 @@ module.exports = {
101
113
  hasTool,
102
114
  getRegisteredToolNames,
103
115
  getTurnScopedToolNames,
116
+ getReplayArgsByTool,
104
117
  clearRegistry,
105
118
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.58.2",
3
+ "version": "5.58.4",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",