@peopl-health/nexus 5.51.0 → 5.51.2
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/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/providers/GatewayProvider.js +2 -2
- package/lib/clinical/services/recommendationRecoveryService.js +175 -0
- package/lib/clinical/services/triageRecommendationService.js +97 -18
- package/lib/clinical/services/writeClaimStore.js +28 -0
- package/lib/controllers/triageRecommendationController.js +21 -86
- package/lib/core/NexusMessaging.js +2 -0
- package/lib/services/queueReconciliationService.js +31 -9
- package/package.json +1 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const runtimeConfig = require('../../config/runtimeConfig');
|
|
2
|
+
|
|
3
|
+
function recommendationRetryLive() {
|
|
4
|
+
return String(runtimeConfig.get('RECOMMENDATION_RETRY_LIVE', 'true')).trim().toLowerCase() === 'true';
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
recommendationRetryLive,
|
|
9
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
2
|
+
const { logger } = require('../../utils/logger');
|
|
3
|
+
const { getRecordByFilter } = require('../../services/airtableService');
|
|
4
|
+
const { buildPayloadFromTriageRow } = require('../../fhir/helpers/triagePayloadHelper');
|
|
5
|
+
|
|
6
|
+
const RECORD_ID_RX = /^rec[A-Za-z0-9]+$/;
|
|
7
|
+
const ITEM_TABLE = 'pro_ctcae_questions';
|
|
8
|
+
const ITEM_FIELD = 'item_proctcae';
|
|
9
|
+
|
|
10
|
+
const linkIdsOf = (value) => (Array.isArray(value) ? value : []).filter((id) => RECORD_ID_RX.test(String(id || '')));
|
|
11
|
+
|
|
12
|
+
const fail = (reason, message) => ({ ok: false, reason, message });
|
|
13
|
+
|
|
14
|
+
async function resolveLinkedItems(links, triageRecordId) {
|
|
15
|
+
const resolved = Object.fromEntries(Object.keys(links).map((field) => [field, []]));
|
|
16
|
+
const ids = [...new Set(Object.values(links).flatMap(linkIdsOf))];
|
|
17
|
+
const byId = new Map();
|
|
18
|
+
if (ids.length) {
|
|
19
|
+
const filter = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
|
|
20
|
+
let rows;
|
|
21
|
+
try {
|
|
22
|
+
rows = await getRecordByFilter(Symptoms_ID, ITEM_TABLE, filter, null, [ITEM_FIELD], true);
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
for (const row of (Array.isArray(rows) ? rows : [])) byId.set(row._recordId, row[ITEM_FIELD]);
|
|
27
|
+
}
|
|
28
|
+
for (const [field, value] of Object.entries(links)) {
|
|
29
|
+
const linked = (Array.isArray(value) ? value : []).length;
|
|
30
|
+
const wanted = linkIdsOf(value);
|
|
31
|
+
const items = wanted.map((id) => byId.get(id)).filter((item) => item != null && String(item).trim() !== '');
|
|
32
|
+
if (items.length !== linked) {
|
|
33
|
+
logger.warn('[TriageRecommendationController] unresolved triage item links', {
|
|
34
|
+
triageRecordId, field, linked, matchedIdShape: wanted.length, resolved: items.length,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
resolved[field] = items;
|
|
38
|
+
}
|
|
39
|
+
return resolved;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function buildRetriggerPayload({ triageRecordId, code }) {
|
|
43
|
+
if (typeof triageRecordId !== 'string' || !RECORD_ID_RX.test(triageRecordId.trim())) {
|
|
44
|
+
return fail('invalid_triage_id', 'triage_record_id must be an Airtable record id');
|
|
45
|
+
}
|
|
46
|
+
if (!code || typeof code !== 'string') return fail('missing_code', 'code is required');
|
|
47
|
+
|
|
48
|
+
const safeId = triageRecordId.trim();
|
|
49
|
+
const rows = await getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `RECORD_ID()='${safeId}'`).catch(() => undefined);
|
|
50
|
+
if (!Array.isArray(rows)) return fail('triage_read_failed', 'triage record read failed');
|
|
51
|
+
const row = rows[0];
|
|
52
|
+
if (!row) return fail('triage_not_found', 'triage record not found');
|
|
53
|
+
|
|
54
|
+
const patientLink = Array.isArray(row.patient_id) ? row.patient_id[0] : row.patient_id;
|
|
55
|
+
if (!patientLink) return fail('no_patient_link', 'triage row has no patient link');
|
|
56
|
+
|
|
57
|
+
const patients = await getRecordByFilter(Symptoms_ID, 'estado_general', `RECORD_ID()='${patientLink}'`).catch(() => undefined);
|
|
58
|
+
if (!Array.isArray(patients)) return fail('patient_read_failed', 'patient record read failed');
|
|
59
|
+
if (!patients[0]) return fail('patient_not_found', 'patient record not found');
|
|
60
|
+
if (patients[0].whatsapp_id !== code) return fail('code_mismatch', 'code does not match the triage row patient');
|
|
61
|
+
|
|
62
|
+
const linkedItems = await resolveLinkedItems({
|
|
63
|
+
additional_symptoms_select: row.additional_symptoms_select,
|
|
64
|
+
pain_multiselect: row.pain_multiselect,
|
|
65
|
+
}, safeId);
|
|
66
|
+
if (!linkedItems) return fail('item_read_failed', 'triage item read failed');
|
|
67
|
+
|
|
68
|
+
const cadence = row['type_quest (from questionnaire_id)'];
|
|
69
|
+
const {
|
|
70
|
+
additional_symptoms_select: additionalSymptoms,
|
|
71
|
+
pain_multiselect: painOptions,
|
|
72
|
+
} = linkedItems;
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
ok: true,
|
|
76
|
+
payload: buildPayloadFromTriageRow(
|
|
77
|
+
{ ...row, type_quest: Array.isArray(cadence) ? cadence[0] : cadence ?? row.type_quest },
|
|
78
|
+
{ patientCode: code, triageRecordId: safeId, additionalSymptoms, painOptions },
|
|
79
|
+
),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = {
|
|
84
|
+
buildRetriggerPayload,
|
|
85
|
+
};
|
|
@@ -60,7 +60,7 @@ class GatewayProvider extends BaseLLMProvider {
|
|
|
60
60
|
sessionManager: this.sessionManager,
|
|
61
61
|
});
|
|
62
62
|
} catch (err) {
|
|
63
|
-
throw new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`);
|
|
63
|
+
throw Object.assign(new Error(`Gateway routed a model to '${vendor}' but its provider could not be created: ${err.message}`), { permanent: true });
|
|
64
64
|
}
|
|
65
65
|
return this._subs[vendor];
|
|
66
66
|
}
|
|
@@ -80,7 +80,7 @@ class GatewayProvider extends BaseLLMProvider {
|
|
|
80
80
|
}
|
|
81
81
|
const { vendor, model: routedModel } = this._route(model);
|
|
82
82
|
if (vendor !== 'openai' && vendor !== 'anthropic') {
|
|
83
|
-
throw new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`);
|
|
83
|
+
throw Object.assign(new Error(`runStructured is only supported for OpenAI and Anthropic models; routed model '${model}' resolved to '${vendor}'`), { permanent: true });
|
|
84
84
|
}
|
|
85
85
|
return this._sub(vendor).runStructured({ ...params, model: routedModel });
|
|
86
86
|
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
const { buildRetriggerPayload } = require('../helpers/triageRetriggerHelper');
|
|
2
|
+
const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
3
|
+
const { logger } = require('../../utils/logger');
|
|
4
|
+
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
|
+
const { recommendationRetryLive } = require('../flags/recommendationRecoveryFlags');
|
|
6
|
+
const { Thread } = require('../../models/threadModel');
|
|
7
|
+
const { recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
8
|
+
const { handleTriageCompleted } = require('./triageRecommendationService');
|
|
9
|
+
const { WriteClaimStore } = require('./writeClaimStore');
|
|
10
|
+
|
|
11
|
+
const TRIAGE_TABLE = 'triaje_symptoms';
|
|
12
|
+
const SCAN_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
13
|
+
const MIN_AGE_MS = 15 * 60 * 1000;
|
|
14
|
+
const RETRY_MAX_AGE_MS = 60 * 60 * 1000;
|
|
15
|
+
const MAX_CANDIDATES = 20;
|
|
16
|
+
const MAX_RETRIES_PER_PASS = 3;
|
|
17
|
+
const CLAIM_TTL_MS = 60 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
const retryClaims = new WriteClaimStore({ namespace: 'recom-orphan-retry', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
20
|
+
const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttlMs: SCAN_WINDOW_MS, maxSize: 500 });
|
|
21
|
+
|
|
22
|
+
const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
|
|
23
|
+
|
|
24
|
+
function orphanFormula(now) {
|
|
25
|
+
const newest = new Date(now.getTime() - MIN_AGE_MS).toISOString();
|
|
26
|
+
const oldest = new Date(now.getTime() - SCAN_WINDOW_MS).toISOString();
|
|
27
|
+
return [
|
|
28
|
+
'AND(',
|
|
29
|
+
'ARRAYJOIN({source})=\'auna\',',
|
|
30
|
+
'COUNTA({symptom_name_positive})>0,',
|
|
31
|
+
'COUNTA({cluster_recommendations})=0,',
|
|
32
|
+
`IS_AFTER({Created}, '${oldest}'),`,
|
|
33
|
+
`IS_BEFORE({Created}, '${newest}')`,
|
|
34
|
+
')',
|
|
35
|
+
].join('');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function firstValue(value) {
|
|
39
|
+
return Array.isArray(value) ? value[0] : value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function describe(row) {
|
|
43
|
+
return {
|
|
44
|
+
triageRecordId: row._recordId,
|
|
45
|
+
triageId: firstValue(row.triaje_symptoms_id) ?? null,
|
|
46
|
+
code: firstValue(row.whatsapp_id) ?? null,
|
|
47
|
+
createdAt: row.Created ?? null,
|
|
48
|
+
positiveSymptoms: (Array.isArray(row.symptom_name_positive) ? row.symptom_name_positive : []).length,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function botIsPaused(code) {
|
|
53
|
+
if (!code) return false;
|
|
54
|
+
try {
|
|
55
|
+
const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
|
|
56
|
+
return Boolean(paused);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
logger.warn('[recommendationRecovery] thread state unreadable; treating the bot as paused', { code, error: error.message });
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function fileOpsTicket(orphan) {
|
|
64
|
+
if (!orphan.code) return false;
|
|
65
|
+
return recordUnresolvedRequest({
|
|
66
|
+
code: orphan.code,
|
|
67
|
+
trace: null,
|
|
68
|
+
question: 'El triaje de la paciente no generó recomendaciones.',
|
|
69
|
+
details: `Triaje ${orphan.triageId ?? orphan.triageRecordId} (${orphan.createdAt}) con ${orphan.positiveSymptoms} síntomas positivos no tiene recomendaciones. Revisar si procede reenviarlas.`,
|
|
70
|
+
category: 'contact_team_member',
|
|
71
|
+
urgency: 'soon',
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function retriggerTriage(orphan) {
|
|
76
|
+
const built = await buildRetriggerPayload({ triageRecordId: orphan.triageRecordId, code: orphan.code });
|
|
77
|
+
if (!built.ok) throw new Error(built.reason);
|
|
78
|
+
handleTriageCompleted(built.payload, { trigger: 'retry' });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function sweepUnrecoveredTriages({
|
|
82
|
+
now = new Date(),
|
|
83
|
+
retrigger = retriggerTriage,
|
|
84
|
+
alert = fileOpsTicket,
|
|
85
|
+
retryLive = recommendationRetryLive,
|
|
86
|
+
claims = retryClaims,
|
|
87
|
+
ticketGate = ticketClaims,
|
|
88
|
+
isPaused = botIsPaused,
|
|
89
|
+
} = {}) {
|
|
90
|
+
let rows;
|
|
91
|
+
try {
|
|
92
|
+
rows = await getRecordByFilter(Symptoms_ID, TRIAGE_TABLE, orphanFormula(now), null, FIELDS, true);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
logger.error('[recommendationRecovery] orphan scan failed', { error: error.message });
|
|
95
|
+
return { scanned: 0, retried: 0, alerted: 0, skipped: 0 };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const orphans = (Array.isArray(rows) ? rows : []).map(describe).filter((orphan) => orphan.triageRecordId);
|
|
99
|
+
if (!orphans.length) return { scanned: 0, retried: 0, alerted: 0, skipped: 0 };
|
|
100
|
+
|
|
101
|
+
if (orphans.length > MAX_CANDIDATES) {
|
|
102
|
+
logger.error('[recommendationRecovery] too many triages without recommendations to act on', {
|
|
103
|
+
found: orphans.length, ceiling: MAX_CANDIDATES,
|
|
104
|
+
});
|
|
105
|
+
return { scanned: orphans.length, retried: 0, alerted: 0, skipped: orphans.length };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const canRetry = retryLive() && typeof retrigger === 'function';
|
|
109
|
+
let retried = 0;
|
|
110
|
+
let alerted = 0;
|
|
111
|
+
let skipped = 0;
|
|
112
|
+
|
|
113
|
+
for (const orphan of orphans) {
|
|
114
|
+
const ageMs = now.getTime() - new Date(orphan.createdAt).getTime();
|
|
115
|
+
const fresh = Number.isFinite(ageMs) && ageMs <= RETRY_MAX_AGE_MS;
|
|
116
|
+
|
|
117
|
+
const paused = (fresh && canRetry) ? await isPaused(orphan.code) : false;
|
|
118
|
+
|
|
119
|
+
if (fresh && canRetry && !paused && retried < MAX_RETRIES_PER_PASS) {
|
|
120
|
+
const claim = await claims.acquire(orphan.triageRecordId, 'retried');
|
|
121
|
+
if (claim === 'taken') { skipped += 1; continue; }
|
|
122
|
+
if (claim === 'unavailable') {
|
|
123
|
+
skipped += 1;
|
|
124
|
+
logger.error('[recommendationRecovery] triage produced no recommendations and could not be claimed', { ...orphan, ageMs });
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
logger.error('[recommendationRecovery] triage produced no recommendations, retrying', { ...orphan, ageMs });
|
|
128
|
+
try {
|
|
129
|
+
await retrigger(orphan);
|
|
130
|
+
retried += 1;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
await claims.release(orphan.triageRecordId);
|
|
133
|
+
logger.error('[recommendationRecovery] retry could not be dispatched', { ...orphan, error: error.message });
|
|
134
|
+
}
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const ticket = await ticketGate.acquire(orphan.triageRecordId, 'alerted');
|
|
139
|
+
if (ticket === 'taken') { skipped += 1; continue; }
|
|
140
|
+
if (ticket === 'unavailable') {
|
|
141
|
+
skipped += 1;
|
|
142
|
+
logger.error('[recommendationRecovery] triage produced no recommendations and could not be claimed', { ...orphan, ageMs });
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
logger.error('[recommendationRecovery] triage produced no recommendations', {
|
|
147
|
+
...orphan, ageMs, retryable: fresh, retryLive: canRetry, botPaused: paused,
|
|
148
|
+
});
|
|
149
|
+
try {
|
|
150
|
+
if (await alert(orphan)) {
|
|
151
|
+
alerted += 1;
|
|
152
|
+
} else {
|
|
153
|
+
await ticketGate.release(orphan.triageRecordId);
|
|
154
|
+
}
|
|
155
|
+
} catch (error) {
|
|
156
|
+
await ticketGate.release(orphan.triageRecordId);
|
|
157
|
+
logger.error('[recommendationRecovery] could not file the ops ticket', { ...orphan, error: error.message });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return { scanned: orphans.length, retried, alerted, skipped };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
module.exports = {
|
|
165
|
+
botIsPaused,
|
|
166
|
+
sweepUnrecoveredTriages,
|
|
167
|
+
orphanFormula,
|
|
168
|
+
_handledClaims: retryClaims,
|
|
169
|
+
_ticketClaims: ticketClaims,
|
|
170
|
+
CLAIM_TTL_MS,
|
|
171
|
+
MIN_AGE_MS,
|
|
172
|
+
RETRY_MAX_AGE_MS,
|
|
173
|
+
MAX_CANDIDATES,
|
|
174
|
+
MAX_RETRIES_PER_PASS,
|
|
175
|
+
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { Types } = require('mongoose');
|
|
1
2
|
const { getTriageGate, getTriagePlan } = require('../config/subAgentsConfig');
|
|
2
3
|
const { getSafetyFlagPatterns, getRedFlagMinRoutes } = require('../config/divergenceConfig');
|
|
3
4
|
const { requireGatewayProvider } = require('../config/llmConfig');
|
|
@@ -19,6 +20,8 @@ const {
|
|
|
19
20
|
hasActionableFindings,
|
|
20
21
|
} = require('../helpers/triageCaseBaseHelper');
|
|
21
22
|
const { buildLegacyStep1, buildLegacyStep2, buildLegacyStep3 } = require('../helpers/legacyRecommendationFormatHelper');
|
|
23
|
+
|
|
24
|
+
const runtimeConfig = require('../../config/runtimeConfig');
|
|
22
25
|
const { triageRecommendationLive } = require('../flags/triageRecommendationFlags');
|
|
23
26
|
const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
24
27
|
const { TRIAGE_RUN_PREFIX } = require('../../fhir/helpers/recommendationIds');
|
|
@@ -67,6 +70,8 @@ const { prepareSupportAction } = require('./supportActionService');
|
|
|
67
70
|
const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
|
|
68
71
|
const GATE_MAX_ATTEMPTS = 2;
|
|
69
72
|
const PLAN_MAX_ATTEMPTS = 2;
|
|
73
|
+
const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
|
|
74
|
+
const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
|
|
70
75
|
const RAW_EXCERPT_MAX = 2000;
|
|
71
76
|
const PRIOR_TRIAGE_RX = /^rec[A-Za-z0-9]{14,}$/;
|
|
72
77
|
const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_recommendations)';
|
|
@@ -147,23 +152,94 @@ function defaultRunId(payload) {
|
|
|
147
152
|
return `${TRIAGE_RUN_PREFIX}${payload.triageRecordId}`;
|
|
148
153
|
}
|
|
149
154
|
|
|
155
|
+
function sleep(ms, { keepAlive = false } = {}) {
|
|
156
|
+
return new Promise((resolve) => {
|
|
157
|
+
const t = setTimeout(resolve, ms);
|
|
158
|
+
if (!keepAlive) t.unref?.();
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isPermanentProviderError(error) {
|
|
163
|
+
if (error?.permanent === true) return true;
|
|
164
|
+
const status = Number(error?.status ?? error?.statusCode);
|
|
165
|
+
return Number.isFinite(status) && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function alreadyRetriedByProvider(error) {
|
|
169
|
+
return error?.originalError !== undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function jittered(ms) {
|
|
173
|
+
return Math.round(ms * (0.75 + (Math.random() * 0.5)));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function backoffSchedule(key, fallback) {
|
|
177
|
+
const raw = runtimeConfig.get(key);
|
|
178
|
+
if (raw == null) return fallback;
|
|
179
|
+
if (String(raw).trim() === '') return [];
|
|
180
|
+
const pieces = String(raw).split(',').map((piece) => piece.trim());
|
|
181
|
+
if (pieces.some((piece) => piece === '')) return fallback;
|
|
182
|
+
const parsed = pieces.map(Number);
|
|
183
|
+
if (!parsed.length || parsed.some((ms) => !Number.isFinite(ms) || ms < 0)) return fallback;
|
|
184
|
+
return parsed;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function newIdempotentEventId() {
|
|
188
|
+
return new Types.ObjectId();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function settleLossIsCritical(status) {
|
|
192
|
+
return status !== 'success' && status !== 'skipped' && status !== 'skipped_duplicate';
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function newTransientBudget() {
|
|
196
|
+
return { schedule: backoffSchedule('TRIAGE_PROVIDER_RETRY_BACKOFF_MS', DEFAULT_PROVIDER_RETRY_BACKOFF_MS), used: 0 };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function callProviderWithBackoff(run, { code, rid, stage, attempt, budget }) {
|
|
200
|
+
for (;;) {
|
|
201
|
+
try {
|
|
202
|
+
return await run();
|
|
203
|
+
} catch (err) {
|
|
204
|
+
const permanent = isPermanentProviderError(err) || alreadyRetriedByProvider(err);
|
|
205
|
+
const waitMs = permanent ? null : budget.schedule[budget.used];
|
|
206
|
+
logger.warn(`[triageRecommendation] ${stage} provider call failed`, {
|
|
207
|
+
code, runId: rid, attempt, transientRetriesUsed: budget.used, retryInMs: waitMs ?? null, permanent, error: err?.message,
|
|
208
|
+
});
|
|
209
|
+
if (waitMs == null) throw err;
|
|
210
|
+
budget.used += 1;
|
|
211
|
+
await sleep(jittered(waitMs));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
150
216
|
async function recordSettleEvent({ payload, trigger, totalLatencyMs, ...settle }) {
|
|
151
217
|
const event = { patientCode: payload.patientCode, triageRecordId: payload.triageRecordId, trigger };
|
|
152
218
|
if (totalLatencyMs != null) event.totalLatencyMs = totalLatencyMs;
|
|
153
219
|
for (const [key, value] of Object.entries(settle)) {
|
|
154
220
|
if (value != null) event[key] = value;
|
|
155
221
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
222
|
+
event._id = newIdempotentEventId();
|
|
223
|
+
let lastError;
|
|
224
|
+
const settleSchedule = backoffSchedule('TRIAGE_SETTLE_WRITE_BACKOFF_MS', DEFAULT_SETTLE_WRITE_BACKOFF_MS);
|
|
225
|
+
for (let tries = 0; tries <= settleSchedule.length; tries += 1) {
|
|
226
|
+
try {
|
|
227
|
+
await getTriageRecommendationEventModel().create(event);
|
|
228
|
+
return;
|
|
229
|
+
} catch (err) {
|
|
230
|
+
if (err?.code === 11000) return;
|
|
231
|
+
lastError = err;
|
|
232
|
+
const waitMs = settleSchedule[tries];
|
|
233
|
+
if (waitMs == null) break;
|
|
234
|
+
await sleep(jittered(waitMs), { keepAlive: true });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const lost = { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: event.status, reason: event.reason, error: lastError?.message };
|
|
238
|
+
if (!settleLossIsCritical(event.status)) {
|
|
239
|
+
logger.warn('[triageRecommendation] settle event write failed', lost);
|
|
240
|
+
return;
|
|
166
241
|
}
|
|
242
|
+
logger.error('[triageRecommendation] failure lost before it was recorded', lost);
|
|
167
243
|
}
|
|
168
244
|
|
|
169
245
|
async function generateTriageRecommendations({ payload, provider, runId = null, supportRouting = {} }) {
|
|
@@ -655,6 +731,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
655
731
|
let gateRepairs = [];
|
|
656
732
|
let accepted = null;
|
|
657
733
|
let priorIssues = null;
|
|
734
|
+
const budget = newTransientBudget();
|
|
658
735
|
for (let attempt = 1; attempt <= GATE_MAX_ATTEMPTS; attempt += 1) {
|
|
659
736
|
attempts = attempt;
|
|
660
737
|
const last = attempt === GATE_MAX_ATTEMPTS;
|
|
@@ -662,13 +739,12 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
662
739
|
if (priorIssues) input.push({ role: 'user', content: gateCorrectionNote(priorIssues) });
|
|
663
740
|
let result;
|
|
664
741
|
try {
|
|
665
|
-
result = await provider.runStructured({
|
|
742
|
+
result = await callProviderWithBackoff(() => provider.runStructured({
|
|
666
743
|
presetId,
|
|
667
744
|
input,
|
|
668
745
|
metadata: { subAgent: 'triage-gate', runId: rid },
|
|
669
|
-
});
|
|
670
|
-
} catch
|
|
671
|
-
logger.warn('[triageRecommendation] gate provider call failed', { code, runId: rid, attempt, error: err?.message });
|
|
746
|
+
}), { code, rid, stage: 'gate', attempt, budget });
|
|
747
|
+
} catch {
|
|
672
748
|
if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_provider_failed' } };
|
|
673
749
|
continue;
|
|
674
750
|
}
|
|
@@ -772,6 +848,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
772
848
|
let rankReordered = 0;
|
|
773
849
|
let deniedCardsDropped = 0;
|
|
774
850
|
let deniedTargetsStripped = 0;
|
|
851
|
+
const budget = newTransientBudget();
|
|
775
852
|
for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
|
|
776
853
|
const content = attempt === 1 || !lastIssues.length
|
|
777
854
|
? planInput
|
|
@@ -779,13 +856,12 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
779
856
|
const last = attempt === PLAN_MAX_ATTEMPTS;
|
|
780
857
|
let result;
|
|
781
858
|
try {
|
|
782
|
-
result = await provider.runStructured({
|
|
859
|
+
result = await callProviderWithBackoff(() => provider.runStructured({
|
|
783
860
|
presetId,
|
|
784
861
|
input: [{ role: 'user', content }],
|
|
785
862
|
metadata: { subAgent: 'triage-plan', runId: rid },
|
|
786
|
-
});
|
|
787
|
-
} catch
|
|
788
|
-
logger.warn('[triageRecommendation] plan provider call failed', { code, runId: rid, attempt, error: err?.message });
|
|
863
|
+
}), { code, rid, stage: 'plan', attempt, budget });
|
|
864
|
+
} catch {
|
|
789
865
|
lastIssues = [];
|
|
790
866
|
if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } });
|
|
791
867
|
continue;
|
|
@@ -987,6 +1063,9 @@ async function recordTriageAdherence({ code, entries, patientRecordId, priorReso
|
|
|
987
1063
|
}
|
|
988
1064
|
|
|
989
1065
|
module.exports = {
|
|
1066
|
+
recordSettleEvent,
|
|
1067
|
+
backoffSchedule,
|
|
1068
|
+
settleLossIsCritical,
|
|
990
1069
|
handleTriageCompleted,
|
|
991
1070
|
generateTriageRecommendations,
|
|
992
1071
|
};
|
|
@@ -55,6 +55,34 @@ class WriteClaimStore {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
async acquire(key, value = true) {
|
|
59
|
+
if (this.memory.get(key) !== undefined) return 'taken';
|
|
60
|
+
if (!this._durable()) return 'unavailable';
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
await WriteClaim.create({ key: this._key(key), value, expiresAt: new Date(Date.now() + this.ttlMs) });
|
|
64
|
+
this.memory.set(key, value);
|
|
65
|
+
return 'acquired';
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error?.code === 11000) {
|
|
68
|
+
this.memory.set(key, value);
|
|
69
|
+
return 'taken';
|
|
70
|
+
}
|
|
71
|
+
logger.warn('[writeClaimStore] Claim could not be acquired', { namespace: this.namespace, error: error.message });
|
|
72
|
+
return 'unavailable';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async release(key) {
|
|
77
|
+
this.memory.delete(key);
|
|
78
|
+
if (!this._durable()) return;
|
|
79
|
+
try {
|
|
80
|
+
await WriteClaim.deleteOne({ key: this._key(key) });
|
|
81
|
+
} catch (error) {
|
|
82
|
+
logger.warn('[writeClaimStore] Claim could not be released', { namespace: this.namespace, error: error.message });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
58
86
|
clear() {
|
|
59
87
|
this.memory.clear();
|
|
60
88
|
}
|
|
@@ -1,100 +1,35 @@
|
|
|
1
|
-
const { Symptoms_ID } = require('../config/airtableConfig');
|
|
2
1
|
const { logger } = require('../utils/logger');
|
|
3
|
-
const { getRecordByFilter } = require('../services/airtableService');
|
|
4
2
|
const { handleTriageCompleted } = require('../clinical/services/triageRecommendationService');
|
|
5
|
-
const {
|
|
3
|
+
const { buildRetriggerPayload } = require('../clinical/helpers/triageRetriggerHelper');
|
|
6
4
|
const { TRIAGE_RUN_PREFIX } = require('../fhir/helpers/recommendationIds');
|
|
7
5
|
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const filter = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
|
|
20
|
-
let rows;
|
|
21
|
-
try {
|
|
22
|
-
rows = await getRecordByFilter(Symptoms_ID, ITEM_TABLE, filter, null, [ITEM_FIELD], true);
|
|
23
|
-
} catch {
|
|
24
|
-
return null;
|
|
25
|
-
}
|
|
26
|
-
for (const row of (Array.isArray(rows) ? rows : [])) byId.set(row._recordId, row[ITEM_FIELD]);
|
|
27
|
-
}
|
|
28
|
-
for (const [field, value] of Object.entries(links)) {
|
|
29
|
-
const linked = (Array.isArray(value) ? value : []).length;
|
|
30
|
-
const wanted = linkIdsOf(value);
|
|
31
|
-
const items = wanted.map((id) => byId.get(id)).filter((item) => item != null && String(item).trim() !== '');
|
|
32
|
-
if (items.length !== linked) {
|
|
33
|
-
logger.warn('[TriageRecommendationController] unresolved triage item links', {
|
|
34
|
-
triageRecordId, field, linked, matchedIdShape: wanted.length, resolved: items.length,
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
resolved[field] = items;
|
|
38
|
-
}
|
|
39
|
-
return resolved;
|
|
40
|
-
}
|
|
6
|
+
const STATUS_BY_REASON = {
|
|
7
|
+
invalid_triage_id: 400,
|
|
8
|
+
missing_code: 400,
|
|
9
|
+
no_patient_link: 400,
|
|
10
|
+
code_mismatch: 400,
|
|
11
|
+
triage_not_found: 404,
|
|
12
|
+
patient_not_found: 404,
|
|
13
|
+
triage_read_failed: 503,
|
|
14
|
+
patient_read_failed: 503,
|
|
15
|
+
item_read_failed: 503,
|
|
16
|
+
};
|
|
41
17
|
|
|
42
18
|
const triageRecommendationController = async (req, res) => {
|
|
43
19
|
const { triage_record_id: triageRecordId, code } = req.body || {};
|
|
44
|
-
if (typeof triageRecordId !== 'string' || !RECORD_ID_RX.test(triageRecordId.trim())) {
|
|
45
|
-
return res.status(400).json({ success: false, error: 'triage_record_id must be an Airtable record id' });
|
|
46
|
-
}
|
|
47
|
-
if (!code || typeof code !== 'string') {
|
|
48
|
-
return res.status(400).json({ success: false, error: 'code is required' });
|
|
49
|
-
}
|
|
50
20
|
|
|
51
21
|
try {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
22
|
+
const built = await buildRetriggerPayload({ triageRecordId, code });
|
|
23
|
+
if (!built.ok) {
|
|
24
|
+
const status = STATUS_BY_REASON[built.reason] ?? 500;
|
|
25
|
+
if (status === 503) {
|
|
26
|
+
logger.error('[TriageRecommendationController] retrigger read failed', { triageRecordId, code, reason: built.reason });
|
|
27
|
+
}
|
|
28
|
+
return res.status(status).json({ success: false, error: built.message });
|
|
58
29
|
}
|
|
59
|
-
const row = rows[0];
|
|
60
|
-
if (!row) return res.status(404).json({ success: false, error: 'triage record not found' });
|
|
61
30
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return res.status(400).json({ success: false, error: 'triage row has no patient link' });
|
|
65
|
-
}
|
|
66
|
-
const patients = await getRecordByFilter(Symptoms_ID, 'estado_general', `RECORD_ID()='${patientLink}'`)
|
|
67
|
-
.catch(() => undefined);
|
|
68
|
-
if (!Array.isArray(patients)) {
|
|
69
|
-
logger.error('[TriageRecommendationController] patient record read failed', { triageRecordId: safeId, code });
|
|
70
|
-
return res.status(503).json({ success: false, error: 'patient record read failed' });
|
|
71
|
-
}
|
|
72
|
-
if (!patients[0]) {
|
|
73
|
-
return res.status(404).json({ success: false, error: 'patient record not found' });
|
|
74
|
-
}
|
|
75
|
-
if (patients[0].whatsapp_id !== code) {
|
|
76
|
-
return res.status(400).json({ success: false, error: 'code does not match the triage row patient' });
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const cadence = row['type_quest (from questionnaire_id)'];
|
|
80
|
-
const linkedItems = await resolveLinkedItems({
|
|
81
|
-
additional_symptoms_select: row.additional_symptoms_select,
|
|
82
|
-
pain_multiselect: row.pain_multiselect,
|
|
83
|
-
}, safeId);
|
|
84
|
-
if (!linkedItems) {
|
|
85
|
-
logger.error('[TriageRecommendationController] triage item read failed', { triageRecordId: safeId, code });
|
|
86
|
-
return res.status(503).json({ success: false, error: 'triage item read failed' });
|
|
87
|
-
}
|
|
88
|
-
const {
|
|
89
|
-
additional_symptoms_select: additionalSymptoms,
|
|
90
|
-
pain_multiselect: painOptions,
|
|
91
|
-
} = linkedItems;
|
|
92
|
-
const payload = buildPayloadFromTriageRow(
|
|
93
|
-
{ ...row, type_quest: Array.isArray(cadence) ? cadence[0] : cadence ?? row.type_quest },
|
|
94
|
-
{ patientCode: code, triageRecordId: safeId, additionalSymptoms, painOptions },
|
|
95
|
-
);
|
|
96
|
-
handleTriageCompleted(payload, { trigger: 'retry' });
|
|
97
|
-
return res.status(202).json({ success: true, accepted: true, run_id: `${TRIAGE_RUN_PREFIX}${safeId}` });
|
|
31
|
+
handleTriageCompleted(built.payload, { trigger: 'retry' });
|
|
32
|
+
return res.status(202).json({ success: true, accepted: true, run_id: `${TRIAGE_RUN_PREFIX}${String(triageRecordId).trim()}` });
|
|
98
33
|
} catch (error) {
|
|
99
34
|
logger.error('[TriageRecommendationController] retrigger error', { error: error.message, triageRecordId, code });
|
|
100
35
|
return res.status(500).json({ success: false, error: 'Failed to retrigger triage recommendation' });
|
|
@@ -30,6 +30,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
|
|
|
30
30
|
|
|
31
31
|
const { BatchingManager } = require('../core/BatchingManager');
|
|
32
32
|
const { ProcessingPipeline } = require('../core/ProcessingPipeline');
|
|
33
|
+
const { sweepUnrecoveredTriages } = require('../clinical/services/recommendationRecoveryService');
|
|
33
34
|
const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
|
|
34
35
|
const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
|
|
35
36
|
const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
|
|
@@ -169,6 +170,7 @@ class NexusMessaging {
|
|
|
169
170
|
...(config.queueReconciliation || {}),
|
|
170
171
|
scheduleMessage: (options) => this.scheduledMessageJob.schedule(options),
|
|
171
172
|
scheduleTemplateApproval: (options) => this.scheduleTemplateApproval(options),
|
|
173
|
+
sweepUnrecoveredTriages: () => sweepUnrecoveredTriages(),
|
|
172
174
|
sweepHeldMessages: () => sweepHeldMessages()
|
|
173
175
|
});
|
|
174
176
|
|
|
@@ -7,20 +7,24 @@ const DEFAULT_INTERVAL_MS = 10 * 60 * 1000;
|
|
|
7
7
|
const DEFAULT_LOOKBACK_MS = 24 * 60 * 60 * 1000;
|
|
8
8
|
const DEFAULT_STALE_AFTER_MS = 30 * 60 * 1000;
|
|
9
9
|
const DEFAULT_BATCH_LIMIT = 200;
|
|
10
|
+
const DEFAULT_PASS_TIMEOUT_MS = 5 * 60 * 1000;
|
|
10
11
|
|
|
11
12
|
class QueueReconciliationService {
|
|
12
13
|
constructor({
|
|
13
14
|
scheduleMessage,
|
|
14
15
|
scheduleTemplateApproval,
|
|
15
16
|
sweepHeldMessages,
|
|
17
|
+
sweepUnrecoveredTriages,
|
|
16
18
|
intervalMs = DEFAULT_INTERVAL_MS,
|
|
17
19
|
lookbackMs = DEFAULT_LOOKBACK_MS,
|
|
18
20
|
staleAfterMs = DEFAULT_STALE_AFTER_MS,
|
|
19
|
-
batchLimit = DEFAULT_BATCH_LIMIT
|
|
21
|
+
batchLimit = DEFAULT_BATCH_LIMIT,
|
|
22
|
+
passTimeoutMs = DEFAULT_PASS_TIMEOUT_MS
|
|
20
23
|
} = {}) {
|
|
21
24
|
this.scheduleMessage = scheduleMessage;
|
|
22
25
|
this.scheduleTemplateApproval = scheduleTemplateApproval;
|
|
23
26
|
this.sweepHeldMessages = sweepHeldMessages;
|
|
27
|
+
this.sweepUnrecoveredTriages = sweepUnrecoveredTriages;
|
|
24
28
|
this.intervalMs = intervalMs;
|
|
25
29
|
this.lookbackMs = lookbackMs;
|
|
26
30
|
this.staleAfterMs = staleAfterMs;
|
|
@@ -28,6 +32,7 @@ class QueueReconciliationService {
|
|
|
28
32
|
this.timer = null;
|
|
29
33
|
this.stopped = false;
|
|
30
34
|
this.inFlight = new Set();
|
|
35
|
+
this.passTimeoutMs = passTimeoutMs;
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
start() {
|
|
@@ -35,10 +40,15 @@ class QueueReconciliationService {
|
|
|
35
40
|
this.stopped = false;
|
|
36
41
|
|
|
37
42
|
const launch = (label) => {
|
|
38
|
-
const
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
for (const entry of this.inFlight) {
|
|
45
|
+
if (now - entry.startedAt < this.passTimeoutMs) return;
|
|
46
|
+
}
|
|
47
|
+
const entry = { startedAt: now };
|
|
48
|
+
entry.promise = this.runOnce()
|
|
39
49
|
.catch((error) => logger.warn(`[QueueReconciliation] ${label} failed`, { error: error.message }))
|
|
40
|
-
.finally(() => this.inFlight.delete(
|
|
41
|
-
this.inFlight.add(
|
|
50
|
+
.finally(() => this.inFlight.delete(entry));
|
|
51
|
+
this.inFlight.add(entry);
|
|
42
52
|
};
|
|
43
53
|
|
|
44
54
|
launch('Startup pass');
|
|
@@ -56,23 +66,35 @@ class QueueReconciliationService {
|
|
|
56
66
|
clearInterval(this.timer);
|
|
57
67
|
this.timer = null;
|
|
58
68
|
}
|
|
59
|
-
return Promise.allSettled([...this.inFlight]).then(() => undefined);
|
|
69
|
+
return Promise.allSettled([...this.inFlight].map((entry) => entry.promise)).then(() => undefined);
|
|
60
70
|
}
|
|
61
71
|
|
|
62
72
|
async runOnce() {
|
|
63
|
-
if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0 };
|
|
73
|
+
if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0, unrecoveredTriages: 0 };
|
|
64
74
|
const since = new Date(Date.now() - this.lookbackMs);
|
|
65
|
-
const [scheduledMessages, recoveries, heldMessages] = await Promise.all([
|
|
75
|
+
const [scheduledMessages, recoveries, heldMessages, unrecoveredTriages] = await Promise.all([
|
|
66
76
|
this._reEnqueueScheduledMessages(since),
|
|
67
77
|
this._reArmTemplateApprovals(since),
|
|
68
|
-
this._releaseHeldMessages()
|
|
78
|
+
this._releaseHeldMessages(),
|
|
79
|
+
this._recoverUnrecoveredTriages()
|
|
69
80
|
]);
|
|
70
81
|
|
|
71
82
|
if (scheduledMessages || recoveries || heldMessages) {
|
|
72
83
|
logger.warn('[QueueReconciliation] Re-armed dropped jobs', { scheduledMessages, recoveries, heldMessages });
|
|
73
84
|
}
|
|
74
85
|
|
|
75
|
-
return { scheduledMessages, recoveries, heldMessages };
|
|
86
|
+
return { scheduledMessages, recoveries, heldMessages, unrecoveredTriages };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async _recoverUnrecoveredTriages() {
|
|
90
|
+
if (typeof this.sweepUnrecoveredTriages !== 'function') return 0;
|
|
91
|
+
try {
|
|
92
|
+
const result = await this.sweepUnrecoveredTriages();
|
|
93
|
+
return (result?.retried || 0) + (result?.alerted || 0);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
logger.error('[QueueReconciliation] Recommendation recovery sweep failed', { error: error.message });
|
|
96
|
+
return 0;
|
|
97
|
+
}
|
|
76
98
|
}
|
|
77
99
|
|
|
78
100
|
async _releaseHeldMessages() {
|