@peopl-health/nexus 5.61.1 → 5.62.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.
|
@@ -17,6 +17,7 @@ const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
|
|
|
17
17
|
const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
|
|
18
18
|
const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
|
|
19
19
|
const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
|
|
20
|
+
const SUPPORT_LIGHT_DEFAULTS = { presetId: '' };
|
|
20
21
|
|
|
21
22
|
const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
|
|
22
23
|
|
|
@@ -66,7 +67,11 @@ async function load() {
|
|
|
66
67
|
if (byKey.ESCALATION_NOTE_FACTS && !isPlainObject(parsedNoteFacts)) throw new Error('subAgents config ESCALATION_NOTE_FACTS is not a JSON object');
|
|
67
68
|
const escalationNoteFacts = { ...ESCALATION_NOTE_FACTS_DEFAULTS, ...(parsedNoteFacts || {}) };
|
|
68
69
|
|
|
69
|
-
const
|
|
70
|
+
const parsedSupportLight = safeParse(byKey.SUPPORT_LIGHT, null);
|
|
71
|
+
if (byKey.SUPPORT_LIGHT && !isPlainObject(parsedSupportLight)) throw new Error('subAgents config SUPPORT_LIGHT is not a JSON object');
|
|
72
|
+
const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(parsedSupportLight || {}) };
|
|
73
|
+
|
|
74
|
+
const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight };
|
|
70
75
|
cache.set(CACHE_KEY, config);
|
|
71
76
|
return config;
|
|
72
77
|
}
|
|
@@ -85,4 +90,5 @@ module.exports = {
|
|
|
85
90
|
getEscalationDraft: () => get('ESCALATION_DRAFT'),
|
|
86
91
|
getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
|
|
87
92
|
getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
|
|
93
|
+
getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
|
|
88
94
|
};
|
|
@@ -56,6 +56,13 @@ const supportLightEventSchema = new mongoose.Schema({
|
|
|
56
56
|
supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
|
|
57
57
|
supportLightEventSchema.index({ patientId: 1, at: -1 });
|
|
58
58
|
|
|
59
|
+
const supportLightSweepSchema = new mongoose.Schema({
|
|
60
|
+
patientId: { type: String, required: true, unique: true },
|
|
61
|
+
lastAttemptAt: { type: Date, required: true },
|
|
62
|
+
lastEvaluatedAt: { type: Date, default: null },
|
|
63
|
+
lastOutcome: { type: String, required: true },
|
|
64
|
+
}, { timestamps: true });
|
|
65
|
+
|
|
59
66
|
function getSupportLightModel() {
|
|
60
67
|
const conn = clinicalConnection();
|
|
61
68
|
return conn.models.SupportLight || conn.model('SupportLight', supportLightSchema, 'supportLights');
|
|
@@ -67,6 +74,17 @@ function getSupportLightEventModel() {
|
|
|
67
74
|
|| conn.model('SupportLightEvent', supportLightEventSchema, 'supportLightEvents');
|
|
68
75
|
}
|
|
69
76
|
|
|
77
|
+
function getSupportLightSweepModel() {
|
|
78
|
+
const conn = clinicalConnection();
|
|
79
|
+
return conn.models.SupportLightSweep
|
|
80
|
+
|| conn.model('SupportLightSweep', supportLightSweepSchema, 'supportLightSweeps');
|
|
81
|
+
}
|
|
82
|
+
|
|
70
83
|
module.exports = {
|
|
71
|
-
getSupportLightModel,
|
|
84
|
+
getSupportLightModel,
|
|
85
|
+
getSupportLightEventModel,
|
|
86
|
+
getSupportLightSweepModel,
|
|
87
|
+
supportLightSchema,
|
|
88
|
+
supportLightEventSchema,
|
|
89
|
+
supportLightSweepSchema,
|
|
72
90
|
};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
const { requireGatewayProvider } = require('../config/llmConfig');
|
|
2
|
+
const { getSupportLightEvaluator } = require('../config/subAgentsConfig');
|
|
3
|
+
const { getSupportLightSweepModel } = require('../models/supportLightModel');
|
|
4
|
+
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
5
|
+
const { getMessages, aggregateMessages } = require('../../services/messageService');
|
|
6
|
+
const { safeParse } = require('../../utils/jsonUtils');
|
|
7
|
+
const { logger } = require('../../utils/logger');
|
|
8
|
+
const { LIGHT_SCALE } = require('./supportInvitability');
|
|
9
|
+
const { applySupportLight } = require('./supportLightService');
|
|
10
|
+
|
|
11
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
12
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
13
|
+
const DEFAULT_CADENCE_HOURS = 48;
|
|
14
|
+
const RETRY_HOURS = 6;
|
|
15
|
+
const DEFAULT_WINDOW_DAYS = 14;
|
|
16
|
+
const MAX_MESSAGES = 60;
|
|
17
|
+
const MAX_PATIENT_MESSAGES = 20;
|
|
18
|
+
const CANDIDATE_PAGE = 200;
|
|
19
|
+
const SETTLED_OUTCOMES = ['evaluated', 'no_messages'];
|
|
20
|
+
const MAX_REASON_CHARS = 500;
|
|
21
|
+
const MAX_EVIDENCE = 5;
|
|
22
|
+
const INTERNAL_ORIGINS = ['system', 'instruction'];
|
|
23
|
+
const SERVICES = Object.keys(LIGHT_SCALE);
|
|
24
|
+
|
|
25
|
+
function transcriptOf(messages) {
|
|
26
|
+
return messages.map((message, index) => {
|
|
27
|
+
const at = new Date(message.createdAt).toISOString().slice(0, 16).replace('T', ' ');
|
|
28
|
+
return `[${index}] ${at} ${message.from_me ? 'Equipo' : 'Paciente'}: ${String(message.body || '').trim()}`;
|
|
29
|
+
}).join('\n');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function readingFor(service, raw, messages) {
|
|
33
|
+
const color = raw?.color;
|
|
34
|
+
if (color !== 'unknown' && !LIGHT_SCALE[service].includes(color)) return null;
|
|
35
|
+
const evidence = (Array.isArray(raw?.evidence) ? raw.evidence : [])
|
|
36
|
+
.filter((item) => Number.isInteger(item?.message_index) && messages[item.message_index] && typeof item.summary === 'string')
|
|
37
|
+
.slice(0, MAX_EVIDENCE)
|
|
38
|
+
.map((item) => ({ source: 'sweep', sourceId: String(messages[item.message_index]._id), summary: item.summary.slice(0, MAX_REASON_CHARS) }));
|
|
39
|
+
const reason = typeof raw?.reason === 'string' ? raw.reason.slice(0, MAX_REASON_CHARS) : null;
|
|
40
|
+
return { color, reason, evidence };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function readRecentMessages(patientId, { now, windowDays, readMessages }) {
|
|
44
|
+
const query = {
|
|
45
|
+
numero: patientId,
|
|
46
|
+
createdAt: { $gte: new Date(now.getTime() - windowDays * DAY_MS) },
|
|
47
|
+
origin: { $nin: INTERNAL_ORIGINS },
|
|
48
|
+
body: { $regex: '\\S' },
|
|
49
|
+
};
|
|
50
|
+
const options = { sort: { createdAt: -1 }, select: '_id body from_me createdAt' };
|
|
51
|
+
const [recent, fromPatient] = await Promise.all([
|
|
52
|
+
readMessages(query, { ...options, limit: MAX_MESSAGES }),
|
|
53
|
+
readMessages({ ...query, from_me: false }, { ...options, limit: MAX_PATIENT_MESSAGES }),
|
|
54
|
+
]);
|
|
55
|
+
const byId = new Map([...(recent || []), ...(fromPatient || [])].map((message) => [String(message._id), message]));
|
|
56
|
+
return [...byId.values()].sort((left, right) => new Date(left.createdAt) - new Date(right.createdAt));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function evaluatePatientSupport({
|
|
60
|
+
patientId, now = new Date(), windowDays = DEFAULT_WINDOW_DAYS,
|
|
61
|
+
}, {
|
|
62
|
+
provider = null, getConfig = getSupportLightEvaluator, readMessages = getMessages, applyLight = applySupportLight,
|
|
63
|
+
} = {}) {
|
|
64
|
+
const { presetId } = await getConfig();
|
|
65
|
+
if (!presetId) return { outcome: 'not_configured' };
|
|
66
|
+
const messages = await readRecentMessages(patientId, { now, windowDays, readMessages });
|
|
67
|
+
if (!messages.some((message) => !message.from_me)) return { outcome: 'no_messages' };
|
|
68
|
+
|
|
69
|
+
const result = await (provider || requireGatewayProvider()).runStructured({
|
|
70
|
+
presetId,
|
|
71
|
+
input: [{ role: 'user', content: transcriptOf(messages) }],
|
|
72
|
+
metadata: { subAgent: 'support-light' },
|
|
73
|
+
});
|
|
74
|
+
if (result?.status && result.status !== 'completed') return { outcome: 'incomplete' };
|
|
75
|
+
const parsed = safeParse(readStructuredText(result), null);
|
|
76
|
+
if (!parsed || typeof parsed !== 'object') return { outcome: 'unparseable' };
|
|
77
|
+
|
|
78
|
+
const changes = [];
|
|
79
|
+
let isPartial = false;
|
|
80
|
+
for (const service of SERVICES) {
|
|
81
|
+
const reading = readingFor(service, parsed[service], messages);
|
|
82
|
+
if (!reading) {
|
|
83
|
+
isPartial = true;
|
|
84
|
+
logger.warn('[supportLightEvaluation] reading skipped: missing or invalid colour', { code: patientId, service });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const { light, outcome } = await applyLight({ patientId, service, source: 'ai', now, ...reading });
|
|
88
|
+
if (outcome !== 'unchanged') changes.push({ service, outcome, color: reading.color, revision: light?.revision ?? null });
|
|
89
|
+
}
|
|
90
|
+
return { outcome: isPartial ? 'partial' : 'evaluated', changes };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel }) {
|
|
94
|
+
const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
|
|
95
|
+
const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
|
|
96
|
+
const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
|
|
97
|
+
const selected = [];
|
|
98
|
+
for (let page = 0; selected.length < limit; page += 1) {
|
|
99
|
+
const active = await aggregateMessages([
|
|
100
|
+
{ $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
|
|
101
|
+
{ $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
|
|
102
|
+
{ $sort: { lastInboundAt: -1, _id: 1 } },
|
|
103
|
+
{ $skip: page * CANDIDATE_PAGE },
|
|
104
|
+
{ $limit: CANDIDATE_PAGE },
|
|
105
|
+
]);
|
|
106
|
+
const ids = (active || []).map((row) => row._id);
|
|
107
|
+
if (!ids.length) break;
|
|
108
|
+
const recent = await SweepModel.find({
|
|
109
|
+
patientId: { $in: ids },
|
|
110
|
+
$or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }],
|
|
111
|
+
}).select('patientId').lean();
|
|
112
|
+
const done = new Set(recent.map((row) => row.patientId));
|
|
113
|
+
selected.push(...ids.filter((id) => !done.has(id)));
|
|
114
|
+
if (ids.length < CANDIDATE_PAGE) break;
|
|
115
|
+
}
|
|
116
|
+
return selected.slice(0, limit);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function validPatientIds(ids) {
|
|
120
|
+
return [...new Set(ids.filter((id) => /^whatsapp:\+\d{6,20}$/.test(String(id))))];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function sweepState(outcome, now) {
|
|
124
|
+
return { lastAttemptAt: now, lastOutcome: outcome, ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}) };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function runSupportLightSweep({
|
|
128
|
+
now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
|
|
129
|
+
} = {}, { SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, ...deps } = {}) {
|
|
130
|
+
const candidates = Array.isArray(patientIds)
|
|
131
|
+
? validPatientIds(patientIds).slice(0, limit)
|
|
132
|
+
: await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
|
|
133
|
+
const summary = { evaluated: 0, skipped: 0, failed: 0, changes: [] };
|
|
134
|
+
for (const patientId of candidates) {
|
|
135
|
+
let outcome = 'error';
|
|
136
|
+
try {
|
|
137
|
+
const result = await evaluate({ patientId, now, windowDays }, deps);
|
|
138
|
+
if (result.outcome === 'not_configured') return { ...summary, outcome: 'not_configured' };
|
|
139
|
+
outcome = result.outcome;
|
|
140
|
+
if (outcome === 'evaluated' || outcome === 'partial') {
|
|
141
|
+
summary.evaluated += 1;
|
|
142
|
+
summary.changes.push(...result.changes.map((change) => ({ patientId, ...change })));
|
|
143
|
+
} else {
|
|
144
|
+
summary.skipped += 1;
|
|
145
|
+
}
|
|
146
|
+
} catch (error) {
|
|
147
|
+
summary.failed += 1;
|
|
148
|
+
logger.error('[supportLightEvaluation] patient evaluation failed', { code: patientId, error: error.message, stack: error.stack });
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
await SweepModel.updateOne({ patientId }, { $set: sweepState(outcome, now) }, { upsert: true });
|
|
152
|
+
} catch (stateError) {
|
|
153
|
+
logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { ...summary, outcome: 'completed' };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = { evaluatePatientSupport, runSupportLightSweep };
|
package/lib/index.d.ts
CHANGED
|
@@ -1027,6 +1027,39 @@ declare module '@peopl-health/nexus' {
|
|
|
1027
1027
|
supportWeek(date: Date | string): string | null;
|
|
1028
1028
|
};
|
|
1029
1029
|
|
|
1030
|
+
export interface SupportLightSweepChange {
|
|
1031
|
+
patientId: string;
|
|
1032
|
+
service: SupportService;
|
|
1033
|
+
outcome: SupportLightOutcome;
|
|
1034
|
+
color: SupportLightColor;
|
|
1035
|
+
revision: number | null;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
export const supportLightEvaluationService: {
|
|
1039
|
+
evaluatePatientSupport(request: {
|
|
1040
|
+
patientId: string;
|
|
1041
|
+
now?: Date;
|
|
1042
|
+
windowDays?: number;
|
|
1043
|
+
}, options?: { provider?: unknown; getConfig?: unknown; readMessages?: unknown; applyLight?: unknown }): Promise<{
|
|
1044
|
+
outcome: 'evaluated' | 'partial' | 'not_configured' | 'no_messages' | 'incomplete' | 'unparseable';
|
|
1045
|
+
changes?: Omit<SupportLightSweepChange, 'patientId'>[];
|
|
1046
|
+
}>;
|
|
1047
|
+
runSupportLightSweep(request?: {
|
|
1048
|
+
now?: Date;
|
|
1049
|
+
patientIds?: string[] | null;
|
|
1050
|
+
scope?: string[] | null;
|
|
1051
|
+
cadenceHours?: number;
|
|
1052
|
+
windowDays?: number;
|
|
1053
|
+
limit?: number;
|
|
1054
|
+
}, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
|
|
1055
|
+
outcome: 'completed' | 'not_configured';
|
|
1056
|
+
evaluated: number;
|
|
1057
|
+
skipped: number;
|
|
1058
|
+
failed: number;
|
|
1059
|
+
changes: SupportLightSweepChange[];
|
|
1060
|
+
}>;
|
|
1061
|
+
};
|
|
1062
|
+
|
|
1030
1063
|
// BatchingManager — per-chatId concurrency control
|
|
1031
1064
|
export interface BatchingConfig {
|
|
1032
1065
|
enabled?: boolean;
|
package/lib/index.js
CHANGED
|
@@ -52,6 +52,7 @@ const { registerDashboardProvider } = require('./services/dashboard-provider-reg
|
|
|
52
52
|
const supportActionService = require('./clinical/services/supportActionService');
|
|
53
53
|
const supportLightService = require('./clinical/services/supportLightService');
|
|
54
54
|
const supportInvitability = require('./clinical/services/supportInvitability');
|
|
55
|
+
const supportLightEvaluationService = require('./clinical/services/supportLightEvaluationService');
|
|
55
56
|
const {
|
|
56
57
|
NutritionSafetyDecision,
|
|
57
58
|
FINDING_CODES,
|
|
@@ -379,6 +380,7 @@ module.exports = {
|
|
|
379
380
|
supportActionService,
|
|
380
381
|
supportLightService,
|
|
381
382
|
supportInvitability,
|
|
383
|
+
supportLightEvaluationService,
|
|
382
384
|
NutritionSafetyDecision,
|
|
383
385
|
FINDING_CODES,
|
|
384
386
|
FINDING_VALUES,
|