@peopl-health/nexus 5.61.1 → 5.62.0-dev.11344
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.
- package/lib/clinical/config/subAgentsConfig.js +7 -1
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/models/supportLightModel.js +22 -1
- package/lib/clinical/services/supportLightEvaluationService.js +159 -0
- package/lib/clinical/services/supportLightService.js +76 -8
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +4 -1
- package/lib/index.d.ts +45 -0
- package/lib/index.js +2 -0
- package/package.json +1 -1
|
@@ -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
|
};
|
|
@@ -46,6 +46,7 @@ const supportLightSchema = new mongoose.Schema({
|
|
|
46
46
|
supportLightSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_light_per_service' });
|
|
47
47
|
supportLightSchema.index({ service: 1, color: 1 });
|
|
48
48
|
supportLightSchema.index({ 'pendingImprovement.proposedAt': 1 }, { sparse: true });
|
|
49
|
+
supportLightSchema.index({ 'outbox.at': 1 }, { sparse: true });
|
|
49
50
|
|
|
50
51
|
const supportLightEventSchema = new mongoose.Schema({
|
|
51
52
|
patientId: { type: String, required: true },
|
|
@@ -55,6 +56,15 @@ const supportLightEventSchema = new mongoose.Schema({
|
|
|
55
56
|
|
|
56
57
|
supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
|
|
57
58
|
supportLightEventSchema.index({ patientId: 1, at: -1 });
|
|
59
|
+
supportLightEventSchema.index({ service: 1, to: 1, at: 1 });
|
|
60
|
+
supportLightEventSchema.index({ at: 1 });
|
|
61
|
+
|
|
62
|
+
const supportLightSweepSchema = new mongoose.Schema({
|
|
63
|
+
patientId: { type: String, required: true, unique: true },
|
|
64
|
+
lastAttemptAt: { type: Date, required: true },
|
|
65
|
+
lastEvaluatedAt: { type: Date, default: null },
|
|
66
|
+
lastOutcome: { type: String, required: true },
|
|
67
|
+
}, { timestamps: true });
|
|
58
68
|
|
|
59
69
|
function getSupportLightModel() {
|
|
60
70
|
const conn = clinicalConnection();
|
|
@@ -67,6 +77,17 @@ function getSupportLightEventModel() {
|
|
|
67
77
|
|| conn.model('SupportLightEvent', supportLightEventSchema, 'supportLightEvents');
|
|
68
78
|
}
|
|
69
79
|
|
|
80
|
+
function getSupportLightSweepModel() {
|
|
81
|
+
const conn = clinicalConnection();
|
|
82
|
+
return conn.models.SupportLightSweep
|
|
83
|
+
|| conn.model('SupportLightSweep', supportLightSweepSchema, 'supportLightSweeps');
|
|
84
|
+
}
|
|
85
|
+
|
|
70
86
|
module.exports = {
|
|
71
|
-
getSupportLightModel,
|
|
87
|
+
getSupportLightModel,
|
|
88
|
+
getSupportLightEventModel,
|
|
89
|
+
getSupportLightSweepModel,
|
|
90
|
+
supportLightSchema,
|
|
91
|
+
supportLightEventSchema,
|
|
92
|
+
supportLightSweepSchema,
|
|
72
93
|
};
|
|
@@ -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 };
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
|
|
2
2
|
const { logger } = require('../../utils/logger');
|
|
3
|
+
const { supportLightFromChatLive } = require('../flags/supportLightFlags');
|
|
3
4
|
const { nextLight } = require('./supportInvitability');
|
|
4
5
|
|
|
5
6
|
const AI_ACTOR = 'ai';
|
|
6
7
|
const BOARD_LIMIT = 2000;
|
|
7
8
|
const HISTORY_READ_LIMIT = 200;
|
|
9
|
+
const EVENT_READ_LIMIT = 500;
|
|
10
|
+
const MAX_CHAT_REASON_CHARS = 1000;
|
|
11
|
+
const RISK_FIELD = { nutrition: 'nutritionRisk', psychology: 'psychologyRisk' };
|
|
8
12
|
|
|
9
13
|
function requireText(value, name) {
|
|
10
14
|
if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
|
|
@@ -136,6 +140,26 @@ async function readSupportLights(patientId, { Model = getSupportLightModel() } =
|
|
|
136
140
|
return Model.find({ patientId }).select('-outbox').lean();
|
|
137
141
|
}
|
|
138
142
|
|
|
143
|
+
function eventKey(event) {
|
|
144
|
+
return `${event.patientId}:${event.service}:${event.revision}`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function withOutboxEvents(stored, lights, isWanted = () => true) {
|
|
148
|
+
const byKey = new Map(stored.map((event) => [eventKey(event), event]));
|
|
149
|
+
for (const light of lights) {
|
|
150
|
+
for (const outboxEvent of light.outbox || []) {
|
|
151
|
+
const event = { ...outboxEvent, patientId: light.patientId, service: light.service };
|
|
152
|
+
if (isWanted(event) && !byKey.has(eventKey(event))) byKey.set(eventKey(event), event);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return [...byKey.values()];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function byTimeThenIdentity(left, right) {
|
|
159
|
+
return new Date(left.at) - new Date(right.at) || left.patientId.localeCompare(right.patientId)
|
|
160
|
+
|| left.service.localeCompare(right.service) || left.revision - right.revision;
|
|
161
|
+
}
|
|
162
|
+
|
|
139
163
|
async function readSupportLightHistory(patientId, {
|
|
140
164
|
service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
|
|
141
165
|
} = {}) {
|
|
@@ -146,14 +170,7 @@ async function readSupportLightHistory(patientId, {
|
|
|
146
170
|
EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
|
|
147
171
|
Model.find(scope).select('patientId service outbox').lean(),
|
|
148
172
|
]);
|
|
149
|
-
|
|
150
|
-
for (const light of lights) {
|
|
151
|
-
for (const event of light.outbox || []) {
|
|
152
|
-
const key = `${light.service}:${event.revision}`;
|
|
153
|
-
if (!byKey.has(key)) byKey.set(key, { ...event, patientId: light.patientId, service: light.service });
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
return [...byKey.values()]
|
|
173
|
+
return withOutboxEvents(stored, lights)
|
|
157
174
|
.sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
|
|
158
175
|
|| left.service.localeCompare(right.service))
|
|
159
176
|
.slice(0, bounded);
|
|
@@ -190,8 +207,59 @@ async function readSupportLightBoard({ service = null, color = null, isPendingOn
|
|
|
190
207
|
]).option({ maxTimeMS: 10000, allowDiskUse: true });
|
|
191
208
|
}
|
|
192
209
|
|
|
210
|
+
async function readSupportLightEvents({
|
|
211
|
+
since, service = null, outcome = null, to = null,
|
|
212
|
+
} = {}, { limit = EVENT_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
|
|
213
|
+
const from = since == null ? null : new Date(since);
|
|
214
|
+
if (!from || Number.isNaN(from.getTime())) throw new Error('since is required');
|
|
215
|
+
const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, EVENT_READ_LIMIT) : EVENT_READ_LIMIT;
|
|
216
|
+
const filters = { ...(outcome ? { outcome } : {}), ...(to ? { to } : {}) };
|
|
217
|
+
const [stored, lights] = await Promise.all([
|
|
218
|
+
EventModel.find({ at: { $gte: from }, ...(service ? { service } : {}), ...filters })
|
|
219
|
+
.sort({ at: 1, patientId: 1, service: 1, revision: 1 }).limit(bounded).lean(),
|
|
220
|
+
Model.find({ ...(service ? { service } : {}), outbox: { $elemMatch: { at: { $gte: from }, ...filters } } })
|
|
221
|
+
.select('patientId service outbox').sort({ 'outbox.at': 1, patientId: 1, service: 1 }).limit(bounded).lean(),
|
|
222
|
+
]);
|
|
223
|
+
const isWanted = (event) => new Date(event.at) >= from && Object.entries(filters).every(([field, value]) => event[field] === value);
|
|
224
|
+
return withOutboxEvents(stored, lights, isWanted).sort(byTimeThenIdentity).slice(0, bounded);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function chatReading(recommendation, decision) {
|
|
228
|
+
const color = decision[RISK_FIELD[decision.service]];
|
|
229
|
+
if (!color) return null;
|
|
230
|
+
const summaries = decision.evidence.map((item) => item.summary).filter(Boolean);
|
|
231
|
+
const reason = (summaries.length ? summaries : decision.reasonCodes).join('; ').slice(0, MAX_CHAT_REASON_CHARS) || null;
|
|
232
|
+
return {
|
|
233
|
+
patientId: recommendation.patientId,
|
|
234
|
+
service: decision.service,
|
|
235
|
+
color,
|
|
236
|
+
source: 'ai',
|
|
237
|
+
reason,
|
|
238
|
+
evidence: decision.evidence.map((item) => ({ source: 'chat', sourceId: item.sourceId, summary: item.summary ?? item.code ?? null })),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function applyChatSupportReadings(recommendation, { now = new Date(), isLive = supportLightFromChatLive, apply = applySupportLight } = {}) {
|
|
243
|
+
if (!isLive()) return [];
|
|
244
|
+
const results = [];
|
|
245
|
+
for (const decision of recommendation.decisions || []) {
|
|
246
|
+
const reading = chatReading(recommendation, decision);
|
|
247
|
+
if (!reading) continue;
|
|
248
|
+
try {
|
|
249
|
+
const { light, outcome } = await apply({ ...reading, now });
|
|
250
|
+
results.push({ service: reading.service, color: reading.color, outcome, revision: light?.revision ?? null });
|
|
251
|
+
} catch (error) {
|
|
252
|
+
logger.error('[supportLight] chat reading not applied', { code: recommendation.patientId, service: reading.service, error: error.message });
|
|
253
|
+
results.push({ service: reading.service, color: reading.color, outcome: 'error', revision: null });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return results;
|
|
257
|
+
}
|
|
258
|
+
|
|
193
259
|
module.exports = {
|
|
260
|
+
applyChatSupportReadings,
|
|
194
261
|
applySupportLight,
|
|
262
|
+
readSupportLightEvents,
|
|
195
263
|
readSupportLightBoard,
|
|
196
264
|
resolvePendingImprovement,
|
|
197
265
|
readSupportLights,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { ZodError } = require('zod');
|
|
2
2
|
|
|
3
3
|
const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
|
|
4
|
+
const { applyChatSupportReadings } = require('../services/supportLightService');
|
|
4
5
|
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
5
6
|
|
|
6
7
|
const decisionProperties = {
|
|
@@ -43,7 +44,7 @@ const decisionProperties = {
|
|
|
43
44
|
|
|
44
45
|
const definition = {
|
|
45
46
|
name: 'submitSupportRoutingRecommendation',
|
|
46
|
-
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
|
|
47
|
+
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. The specialty risk also updates the patient support light: a higher risk applies at once, a lower one waits for a specialist to confirm. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
|
|
47
48
|
strict: false,
|
|
48
49
|
parameters: {
|
|
49
50
|
type: 'object',
|
|
@@ -116,6 +117,7 @@ async function handler(args = {}, context = {}) {
|
|
|
116
117
|
});
|
|
117
118
|
if (!isRuntimeLive(runtime)) return inactiveTurn();
|
|
118
119
|
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
120
|
+
const lights = await applyChatSupportReadings(recommendation);
|
|
119
121
|
runtime.trace?.setSignals?.({
|
|
120
122
|
supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
|
|
121
123
|
});
|
|
@@ -128,6 +130,7 @@ async function handler(args = {}, context = {}) {
|
|
|
128
130
|
service: candidate.service,
|
|
129
131
|
disposition: candidate.disposition,
|
|
130
132
|
})),
|
|
133
|
+
lights,
|
|
131
134
|
invitation_sent: false,
|
|
132
135
|
},
|
|
133
136
|
});
|
package/lib/index.d.ts
CHANGED
|
@@ -1006,6 +1006,18 @@ declare module '@peopl-health/nexus' {
|
|
|
1006
1006
|
isPendingOnly?: boolean;
|
|
1007
1007
|
}, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
|
|
1008
1008
|
readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
1009
|
+
readSupportLightEvents(filters: {
|
|
1010
|
+
since: Date | string;
|
|
1011
|
+
service?: SupportService | null;
|
|
1012
|
+
outcome?: SupportLightEventRecord['outcome'] | null;
|
|
1013
|
+
to?: SupportLightColor | null;
|
|
1014
|
+
}, options?: { limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
1015
|
+
applyChatSupportReadings(recommendation: Pick<SupportRoutingRecommendationInput, 'patientId' | 'decisions'>, options?: { now?: Date; isLive?: () => boolean; apply?: unknown }): Promise<Array<{
|
|
1016
|
+
service: SupportService;
|
|
1017
|
+
color: SupportLightColor;
|
|
1018
|
+
outcome: SupportLightOutcome | 'stale' | 'error';
|
|
1019
|
+
revision: number | null;
|
|
1020
|
+
}>>;
|
|
1009
1021
|
};
|
|
1010
1022
|
|
|
1011
1023
|
export const supportInvitability: {
|
|
@@ -1027,6 +1039,39 @@ declare module '@peopl-health/nexus' {
|
|
|
1027
1039
|
supportWeek(date: Date | string): string | null;
|
|
1028
1040
|
};
|
|
1029
1041
|
|
|
1042
|
+
export interface SupportLightSweepChange {
|
|
1043
|
+
patientId: string;
|
|
1044
|
+
service: SupportService;
|
|
1045
|
+
outcome: SupportLightOutcome;
|
|
1046
|
+
color: SupportLightColor;
|
|
1047
|
+
revision: number | null;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
export const supportLightEvaluationService: {
|
|
1051
|
+
evaluatePatientSupport(request: {
|
|
1052
|
+
patientId: string;
|
|
1053
|
+
now?: Date;
|
|
1054
|
+
windowDays?: number;
|
|
1055
|
+
}, options?: { provider?: unknown; getConfig?: unknown; readMessages?: unknown; applyLight?: unknown }): Promise<{
|
|
1056
|
+
outcome: 'evaluated' | 'partial' | 'not_configured' | 'no_messages' | 'incomplete' | 'unparseable';
|
|
1057
|
+
changes?: Omit<SupportLightSweepChange, 'patientId'>[];
|
|
1058
|
+
}>;
|
|
1059
|
+
runSupportLightSweep(request?: {
|
|
1060
|
+
now?: Date;
|
|
1061
|
+
patientIds?: string[] | null;
|
|
1062
|
+
scope?: string[] | null;
|
|
1063
|
+
cadenceHours?: number;
|
|
1064
|
+
windowDays?: number;
|
|
1065
|
+
limit?: number;
|
|
1066
|
+
}, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
|
|
1067
|
+
outcome: 'completed' | 'not_configured';
|
|
1068
|
+
evaluated: number;
|
|
1069
|
+
skipped: number;
|
|
1070
|
+
failed: number;
|
|
1071
|
+
changes: SupportLightSweepChange[];
|
|
1072
|
+
}>;
|
|
1073
|
+
};
|
|
1074
|
+
|
|
1030
1075
|
// BatchingManager — per-chatId concurrency control
|
|
1031
1076
|
export interface BatchingConfig {
|
|
1032
1077
|
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,
|