@peopl-health/nexus 5.51.0-dev.7631 → 5.51.0-dev.7633
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/README.md +0 -21
- package/lib/clinical/AssistantProcessor.js +12 -156
- package/lib/clinical/context/ToolRuntimeContext.js +1 -39
- package/lib/clinical/context/turnContext.js +0 -10
- package/lib/clinical/models/triageRecommendationEventModel.js +0 -28
- package/lib/clinical/providers/BaseLLMProvider.js +5 -45
- package/lib/clinical/services/clinicalAirtableService.js +5 -8
- package/lib/clinical/services/divergenceService.js +2 -9
- package/lib/clinical/services/triageRecommendationService.js +251 -453
- package/lib/clinical/tools/deliverPatientMessageTool.js +23 -82
- package/lib/clinical/tools/registerClinicalTools.js +0 -2
- package/lib/controllers/dashboardController.js +2 -5
- package/lib/controllers/escalationReviewController.js +12 -0
- package/lib/core/BatchingManager.js +9 -20
- package/lib/core/NexusMessaging.js +6 -25
- package/lib/core/ProcessingPipeline.js +3 -32
- package/lib/index.d.ts +6 -334
- package/lib/index.js +0 -22
- package/lib/models/escalationReviewModel.js +4 -0
- package/lib/routes/index.js +2 -0
- package/lib/services/airtableService.js +1 -8
- package/lib/services/dashboardService.js +3 -30
- package/lib/services/escalationReviewService.js +43 -11
- package/package.json +1 -1
- package/lib/clinical/models/supportCandidateModel.js +0 -90
- package/lib/clinical/services/deliverySettlementService.js +0 -39
- package/lib/clinical/services/supportActionService.js +0 -129
- package/lib/clinical/services/supportCandidateService.js +0 -532
- package/lib/clinical/services/supportRoutingAgentService.js +0 -118
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +0 -200
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +0 -141
- package/lib/core/runtimeToolPolicy.js +0 -3
- package/lib/services/dashboard-provider-registry.js +0 -38
- package/lib/shared/dtos/NutritionSafetyDecision.js +0 -128
- package/lib/shared/dtos/SupportAction.js +0 -28
- package/lib/shared/dtos/SupportRoutingRecommendation.js +0 -124
|
@@ -1,200 +0,0 @@
|
|
|
1
|
-
const { ZodError } = require('zod');
|
|
2
|
-
|
|
3
|
-
const {
|
|
4
|
-
NutritionSafetyDecision,
|
|
5
|
-
FINDING_CODES,
|
|
6
|
-
FINDING_VALUES,
|
|
7
|
-
QUESTION_CODES,
|
|
8
|
-
EVIDENCE_SOURCE_TYPES,
|
|
9
|
-
DISPOSITIONS,
|
|
10
|
-
} = require('../../shared/dtos/NutritionSafetyDecision');
|
|
11
|
-
|
|
12
|
-
const definition = {
|
|
13
|
-
name: 'submitNutritionSafetyDecision',
|
|
14
|
-
description: '**Does:** Commits the typed warning-sign decision for the current nutrition-intake clarification turn. The active patient, trace, inbound message identity, submission revision, and screen revision are validated by Nexus and revalidated by the consumer repository. Call exactly once when this runtime tool is offered and forced.\n\n**Required inputs:** the reviewed submission and screen revisions; all four findings as yes/no/unknown; every unresolved question code; and a clear, clarify, escalate, or review_required disposition.\n\n**Side effects:** synchronously invokes the configured canonical nutrition-safety repository. It never writes consumer state directly.',
|
|
15
|
-
strict: true,
|
|
16
|
-
replayScope: 'turn',
|
|
17
|
-
parameters: {
|
|
18
|
-
type: 'object',
|
|
19
|
-
additionalProperties: false,
|
|
20
|
-
properties: {
|
|
21
|
-
submission_revision: { type: 'integer', minimum: 1 },
|
|
22
|
-
screen_revision: { type: 'integer', minimum: 0 },
|
|
23
|
-
findings: {
|
|
24
|
-
type: 'object',
|
|
25
|
-
additionalProperties: false,
|
|
26
|
-
properties: Object.fromEntries(FINDING_CODES.map(code => [code, { type: 'string', enum: FINDING_VALUES }])),
|
|
27
|
-
required: FINDING_CODES,
|
|
28
|
-
},
|
|
29
|
-
evidence_refs: {
|
|
30
|
-
type: 'array',
|
|
31
|
-
minItems: FINDING_CODES.length,
|
|
32
|
-
items: {
|
|
33
|
-
type: 'object',
|
|
34
|
-
additionalProperties: false,
|
|
35
|
-
properties: {
|
|
36
|
-
finding: { type: 'string', enum: FINDING_CODES },
|
|
37
|
-
source_type: { type: 'string', enum: EVIDENCE_SOURCE_TYPES },
|
|
38
|
-
source_id: { type: 'string', minLength: 1 },
|
|
39
|
-
observed_at: { type: 'string', format: 'date-time' },
|
|
40
|
-
},
|
|
41
|
-
required: ['finding', 'source_type', 'source_id', 'observed_at'],
|
|
42
|
-
},
|
|
43
|
-
},
|
|
44
|
-
questions_needed: {
|
|
45
|
-
type: 'array',
|
|
46
|
-
maxItems: QUESTION_CODES.length,
|
|
47
|
-
uniqueItems: true,
|
|
48
|
-
items: { type: 'string', enum: QUESTION_CODES },
|
|
49
|
-
},
|
|
50
|
-
disposition: { type: 'string', enum: DISPOSITIONS },
|
|
51
|
-
},
|
|
52
|
-
required: ['submission_revision', 'screen_revision', 'findings', 'evidence_refs', 'questions_needed', 'disposition'],
|
|
53
|
-
},
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
function fail(error, data = {}) {
|
|
57
|
-
return JSON.stringify({ success: false, error, data });
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function activeIdentity(runtime) {
|
|
61
|
-
const trace = runtime?.trace;
|
|
62
|
-
const traceId = trace?._id ? String(trace._id) : null;
|
|
63
|
-
const sourceId = runtime?.patientInput?.sourceId;
|
|
64
|
-
const observedAt = runtime?.patientInput?.observedAt;
|
|
65
|
-
if (!runtime?.turnId || !runtime?.patientCode || runtime?.turnKind !== 'patient' || !traceId
|
|
66
|
-
|| String(trace.turnId) !== String(runtime.turnId)
|
|
67
|
-
|| String(trace.patientCode) !== String(runtime.patientCode)
|
|
68
|
-
|| typeof sourceId !== 'string' || !sourceId
|
|
69
|
-
|| typeof observedAt !== 'string' || Number.isNaN(new Date(observedAt).getTime())) {
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
72
|
-
return {
|
|
73
|
-
patientCode: runtime.patientCode,
|
|
74
|
-
turnId: runtime.turnId,
|
|
75
|
-
traceId,
|
|
76
|
-
sourceId,
|
|
77
|
-
observedAt,
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function safeCommitResult(result) {
|
|
82
|
-
const outcome = typeof result?.outcome === 'string' ? result.outcome : null;
|
|
83
|
-
const status = typeof result?.screen?.status === 'string'
|
|
84
|
-
? result.screen.status
|
|
85
|
-
: (typeof result?.status === 'string' ? result.status : null);
|
|
86
|
-
const requested = result?.questionsNeeded ?? result?.questions_needed ?? [];
|
|
87
|
-
const questionsNeeded = Array.isArray(requested)
|
|
88
|
-
? [...new Set(requested.filter(code => QUESTION_CODES.includes(code)))]
|
|
89
|
-
: [];
|
|
90
|
-
if (!outcome || !status) return null;
|
|
91
|
-
return { outcome, status, questions_needed: questionsNeeded };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function sameInstant(first, second) {
|
|
95
|
-
return new Date(first).getTime() === new Date(second).getTime();
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function validateEvidence(decision, runtime, identity) {
|
|
99
|
-
const trustedContext = runtime?.consumerMetadata?.nutritionSafety?.evidenceRefs;
|
|
100
|
-
const trustedReferences = Array.isArray(trustedContext) ? trustedContext : [];
|
|
101
|
-
|
|
102
|
-
const validated = decision.evidenceRefs.map((reference) => {
|
|
103
|
-
if (reference.sourceType === 'chat') {
|
|
104
|
-
if (reference.sourceId !== identity.sourceId
|
|
105
|
-
|| !sameInstant(reference.observedAt, identity.observedAt)) {
|
|
106
|
-
return null;
|
|
107
|
-
}
|
|
108
|
-
return { ...reference, observedAt: identity.observedAt, traceId: identity.traceId };
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const trusted = trustedReferences.find(candidate => (
|
|
112
|
-
candidate?.finding === reference.finding
|
|
113
|
-
&& candidate?.sourceType === reference.sourceType
|
|
114
|
-
&& candidate?.sourceId === reference.sourceId
|
|
115
|
-
&& typeof candidate?.observedAt === 'string'
|
|
116
|
-
&& (reference.sourceType === 'flow'
|
|
117
|
-
? candidate.observedAt === reference.observedAt
|
|
118
|
-
: sameInstant(candidate.observedAt, reference.observedAt))
|
|
119
|
-
));
|
|
120
|
-
if (!trusted) return null;
|
|
121
|
-
return {
|
|
122
|
-
...reference,
|
|
123
|
-
observedAt: trusted.observedAt,
|
|
124
|
-
...(typeof trusted.traceId === 'string' && trusted.traceId ? { traceId: trusted.traceId } : {}),
|
|
125
|
-
};
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
if (validated.some(reference => reference === null)) return null;
|
|
129
|
-
return validated;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function isRuntimeLive(runtime) {
|
|
133
|
-
if (typeof runtime?.isLive !== 'function') return false;
|
|
134
|
-
try {
|
|
135
|
-
return runtime.isLive() === true;
|
|
136
|
-
} catch {
|
|
137
|
-
return false;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
async function handler(args = {}, context = {}) {
|
|
142
|
-
const runtime = context?.toolRuntimeContext;
|
|
143
|
-
const identity = activeIdentity(runtime);
|
|
144
|
-
const commitDecision = runtime?.repos?.nutritionSafety?.commitDecision;
|
|
145
|
-
if (!identity || typeof commitDecision !== 'function') {
|
|
146
|
-
return fail('nutrition_safety_active_context_required');
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
let decision;
|
|
150
|
-
try {
|
|
151
|
-
decision = new NutritionSafetyDecision(args);
|
|
152
|
-
} catch (error) {
|
|
153
|
-
if (error instanceof ZodError) {
|
|
154
|
-
return fail('nutrition_safety_decision_invalid', {
|
|
155
|
-
issues: error.issues.slice(0, 20).map(issue => ({
|
|
156
|
-
path: issue.path.join('.'),
|
|
157
|
-
problem: issue.message,
|
|
158
|
-
})),
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
return fail('nutrition_safety_decision_invalid');
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const evidenceRefs = validateEvidence(decision, runtime, identity);
|
|
165
|
-
if (!evidenceRefs) return fail('nutrition_safety_evidence_invalid');
|
|
166
|
-
decision.evidenceRefs = evidenceRefs;
|
|
167
|
-
|
|
168
|
-
if (!isRuntimeLive(runtime)) {
|
|
169
|
-
return fail('nutrition_safety_turn_inactive');
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
try {
|
|
173
|
-
const result = await commitDecision({ decision, ...identity });
|
|
174
|
-
const safeResult = safeCommitResult(result);
|
|
175
|
-
if (!safeResult) return fail('nutrition_safety_commit_result_invalid');
|
|
176
|
-
if (result?.deliveryDirective) {
|
|
177
|
-
if (typeof runtime?.setDeliveryDirective !== 'function') {
|
|
178
|
-
return fail('nutrition_safety_delivery_directive_unavailable');
|
|
179
|
-
}
|
|
180
|
-
try {
|
|
181
|
-
runtime.setDeliveryDirective(result.deliveryDirective);
|
|
182
|
-
} catch {
|
|
183
|
-
return fail('nutrition_safety_delivery_directive_invalid');
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
runtime.trace?.setSignals?.({
|
|
187
|
-
nutritionSafety: {
|
|
188
|
-
submissionRevision: decision.submissionRevision,
|
|
189
|
-
screenRevision: decision.screenRevision,
|
|
190
|
-
disposition: decision.disposition,
|
|
191
|
-
status: safeResult.status,
|
|
192
|
-
},
|
|
193
|
-
});
|
|
194
|
-
return JSON.stringify({ success: true, data: safeResult });
|
|
195
|
-
} catch {
|
|
196
|
-
return fail('nutrition_safety_commit_failed');
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
module.exports = { definition, handler };
|
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
const { ZodError } = require('zod');
|
|
2
|
-
|
|
3
|
-
const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
|
|
4
|
-
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
5
|
-
|
|
6
|
-
const decisionProperties = {
|
|
7
|
-
service: { type: 'string', enum: ['nutrition', 'psychology'] },
|
|
8
|
-
nutritionRisk: { type: ['string', 'null'], enum: ['green', 'yellow', 'red', 'unknown', null] },
|
|
9
|
-
psychologyRisk: { type: ['string', 'null'], enum: ['green', 'orange', 'red', 'unknown', null] },
|
|
10
|
-
disposition: { type: 'string', enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'] },
|
|
11
|
-
groupEligible: { type: 'boolean' },
|
|
12
|
-
urgentIntakeEligible: { type: 'boolean' },
|
|
13
|
-
priority: { type: 'string', enum: ['routine', 'soon', 'urgent'] },
|
|
14
|
-
confidence: { type: 'number', minimum: 0, maximum: 1 },
|
|
15
|
-
reasonCodes: { type: 'array', items: { type: 'string' }, maxItems: 20 },
|
|
16
|
-
evidence: {
|
|
17
|
-
type: 'array',
|
|
18
|
-
minItems: 1,
|
|
19
|
-
maxItems: 20,
|
|
20
|
-
items: {
|
|
21
|
-
type: 'object',
|
|
22
|
-
properties: {
|
|
23
|
-
source: { type: 'string', enum: ['chat', 'triage', 'fhir', 'airtable'] },
|
|
24
|
-
sourceId: { type: 'string' },
|
|
25
|
-
code: { type: 'string' },
|
|
26
|
-
summary: { type: ['string', 'null'] },
|
|
27
|
-
confidence: { type: ['number', 'null'], minimum: 0, maximum: 1 },
|
|
28
|
-
},
|
|
29
|
-
required: ['source', 'sourceId', 'code'],
|
|
30
|
-
},
|
|
31
|
-
},
|
|
32
|
-
safety: {
|
|
33
|
-
type: 'object',
|
|
34
|
-
properties: {
|
|
35
|
-
suicidalIdeation: { type: 'boolean' },
|
|
36
|
-
immediateRisk: { type: 'boolean' },
|
|
37
|
-
urgentMedicalRisk: { type: 'boolean' },
|
|
38
|
-
needsHumanConfirmation: { type: 'boolean' },
|
|
39
|
-
},
|
|
40
|
-
required: ['suicidalIdeation', 'immediateRisk', 'urgentMedicalRisk', 'needsHumanConfirmation'],
|
|
41
|
-
},
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
const definition = {
|
|
45
|
-
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
|
-
strict: false,
|
|
48
|
-
parameters: {
|
|
49
|
-
type: 'object',
|
|
50
|
-
properties: {
|
|
51
|
-
decisions: {
|
|
52
|
-
type: 'array',
|
|
53
|
-
minItems: 1,
|
|
54
|
-
maxItems: 2,
|
|
55
|
-
items: { type: 'object', properties: decisionProperties, required: ['service', 'disposition', 'groupEligible', 'confidence', 'evidence', 'safety'] },
|
|
56
|
-
},
|
|
57
|
-
},
|
|
58
|
-
required: ['decisions'],
|
|
59
|
-
},
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
function normalizedDecision(raw, turnId) {
|
|
63
|
-
const common = {
|
|
64
|
-
service: raw.service,
|
|
65
|
-
disposition: raw.disposition,
|
|
66
|
-
groupEligible: raw.groupEligible,
|
|
67
|
-
priority: raw.priority || 'routine',
|
|
68
|
-
confidence: raw.confidence,
|
|
69
|
-
reasonCodes: raw.reasonCodes || [],
|
|
70
|
-
evidence: (raw.evidence || []).map((item) => ({
|
|
71
|
-
source: 'chat',
|
|
72
|
-
sourceId: turnId,
|
|
73
|
-
code: item.code,
|
|
74
|
-
summary: item.summary ?? null,
|
|
75
|
-
confidence: item.confidence ?? null,
|
|
76
|
-
})),
|
|
77
|
-
safety: raw.safety,
|
|
78
|
-
};
|
|
79
|
-
return raw.service === 'nutrition'
|
|
80
|
-
? { ...common, nutritionRisk: raw.nutritionRisk || 'unknown', urgentIntakeEligible: raw.urgentIntakeEligible ?? false }
|
|
81
|
-
: { ...common, psychologyRisk: raw.psychologyRisk || 'unknown' };
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function inactiveTurn() {
|
|
85
|
-
return JSON.stringify({ success: false, error: 'support_routing_turn_inactive', data: {} });
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function isRuntimeLive(runtime) {
|
|
89
|
-
if (typeof runtime?.isLive !== 'function') return false;
|
|
90
|
-
try {
|
|
91
|
-
return runtime.isLive() === true;
|
|
92
|
-
} catch {
|
|
93
|
-
return false;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
async function handler(args = {}, context = {}) {
|
|
98
|
-
const runtime = context?.toolRuntimeContext;
|
|
99
|
-
if (!runtime?.turnId || !runtime?.patientCode || runtime.turnKind !== 'patient') {
|
|
100
|
-
return inactiveTurn();
|
|
101
|
-
}
|
|
102
|
-
if (!isRuntimeLive(runtime)) {
|
|
103
|
-
return inactiveTurn();
|
|
104
|
-
}
|
|
105
|
-
try {
|
|
106
|
-
const observedAt = runtime.patientInput?.observedAt;
|
|
107
|
-
const recommendation = new SupportRoutingRecommendation({
|
|
108
|
-
patientId: runtime.patientCode,
|
|
109
|
-
origin: 'chat',
|
|
110
|
-
sourceId: runtime.turnId,
|
|
111
|
-
createdAt: typeof observedAt === 'string' && !Number.isNaN(new Date(observedAt).getTime())
|
|
112
|
-
? new Date(observedAt).toISOString()
|
|
113
|
-
: new Date().toISOString(),
|
|
114
|
-
decisions: (args.decisions || []).map((decision) => normalizedDecision(decision, runtime.turnId)),
|
|
115
|
-
});
|
|
116
|
-
if (!isRuntimeLive(runtime)) return inactiveTurn();
|
|
117
|
-
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
118
|
-
runtime.trace?.setSignals?.({
|
|
119
|
-
supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
|
|
120
|
-
});
|
|
121
|
-
return JSON.stringify({
|
|
122
|
-
success: true,
|
|
123
|
-
data: {
|
|
124
|
-
accepted: true,
|
|
125
|
-
candidates: candidates.map((candidate) => ({
|
|
126
|
-
candidate_id: candidate.candidateId,
|
|
127
|
-
service: candidate.service,
|
|
128
|
-
disposition: candidate.disposition,
|
|
129
|
-
})),
|
|
130
|
-
invitation_sent: false,
|
|
131
|
-
},
|
|
132
|
-
});
|
|
133
|
-
} catch (error) {
|
|
134
|
-
if (error instanceof ZodError) {
|
|
135
|
-
return JSON.stringify({ success: false, error: 'support_routing_schema_invalid', data: { issues: error.issues.map((issue) => ({ path: issue.path.join('.'), problem: issue.message })) } });
|
|
136
|
-
}
|
|
137
|
-
return JSON.stringify({ success: false, error: error?.message || 'support routing failed', data: {} });
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
module.exports = { definition, handler };
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
const { withTimeout } = require('../utils/timeoutUtils');
|
|
2
|
-
|
|
3
|
-
const providers = new Map();
|
|
4
|
-
const SOURCE = 'auna.support.v1';
|
|
5
|
-
|
|
6
|
-
function registerDashboardProvider(source, provider) {
|
|
7
|
-
if (source !== SOURCE || typeof provider !== 'function' || providers.has(source)) {
|
|
8
|
-
throw new Error('Invalid or duplicate dashboard provider');
|
|
9
|
-
}
|
|
10
|
-
providers.set(source, provider);
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
function validateDashboardSource(config) {
|
|
14
|
-
if (config?.source !== SOURCE || config.metric !== 'exceptions' || !providers.has(config.source)) {
|
|
15
|
-
throw new Error('Dashboard provider unavailable');
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
async function readDashboardProvider(config, now) {
|
|
20
|
-
validateDashboardSource(config);
|
|
21
|
-
try {
|
|
22
|
-
const snapshot = await withTimeout(Promise.resolve().then(() => providers.get(config.source)({ now })), 15000, 'Dashboard provider');
|
|
23
|
-
const metric = snapshot?.metrics?.exceptions;
|
|
24
|
-
if (snapshot?.generatedAt !== now.toISOString() || Object.keys(snapshot.metrics).length !== 1
|
|
25
|
-
|| !Array.isArray(metric?.records) || metric.records.length > 2000 || !Array.isArray(metric.struct)
|
|
26
|
-
|| metric.records.some(row => !row || typeof row !== 'object' || Array.isArray(row))
|
|
27
|
-
|| metric.struct.some(column => typeof column !== 'string')
|
|
28
|
-
|| !['indicator', 'sample', 'total'].every(key => metric[key] === metric.records.length)) {
|
|
29
|
-
throw new Error('Invalid dashboard snapshot');
|
|
30
|
-
}
|
|
31
|
-
const { indicator, sample, total, struct, records } = metric;
|
|
32
|
-
return { generatedAt: snapshot.generatedAt, indicator, sample, total, struct, records };
|
|
33
|
-
} catch {
|
|
34
|
-
throw new Error('Dashboard provider unavailable');
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
module.exports = { registerDashboardProvider, validateDashboardSource, readDashboardProvider };
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
const { z } = require('zod');
|
|
2
|
-
|
|
3
|
-
const { BaseDto } = require('./BaseDto');
|
|
4
|
-
|
|
5
|
-
const FINDING_CODES = [
|
|
6
|
-
'cannot_eat',
|
|
7
|
-
'cannot_keep_fluids',
|
|
8
|
-
'bleeding',
|
|
9
|
-
'severe_abdominal_pain',
|
|
10
|
-
];
|
|
11
|
-
const FINDING_VALUES = ['yes', 'no', 'unknown'];
|
|
12
|
-
const FINDING_TO_QUESTION = Object.freeze({
|
|
13
|
-
cannot_eat: 'can_eat',
|
|
14
|
-
cannot_keep_fluids: 'can_keep_fluids',
|
|
15
|
-
bleeding: 'bleeding',
|
|
16
|
-
severe_abdominal_pain: 'severe_abdominal_pain',
|
|
17
|
-
});
|
|
18
|
-
const QUESTION_CODES = Object.freeze(FINDING_CODES.map(code => FINDING_TO_QUESTION[code]));
|
|
19
|
-
const EVIDENCE_SOURCE_TYPES = ['chat', 'flow', 'historical', 'forecast'];
|
|
20
|
-
const CURRENT_EVIDENCE_SOURCE_TYPES = new Set(['chat', 'flow']);
|
|
21
|
-
const DISPOSITIONS = ['clear', 'clarify', 'escalate', 'review_required'];
|
|
22
|
-
|
|
23
|
-
const findingsSchema = z.strictObject(Object.fromEntries(
|
|
24
|
-
FINDING_CODES.map(code => [code, z.enum(FINDING_VALUES)]),
|
|
25
|
-
));
|
|
26
|
-
|
|
27
|
-
const evidenceRefSchema = z.strictObject({
|
|
28
|
-
finding: z.enum(FINDING_CODES),
|
|
29
|
-
source_type: z.enum(EVIDENCE_SOURCE_TYPES),
|
|
30
|
-
source_id: z.string().min(1),
|
|
31
|
-
observed_at: z.string().datetime({ offset: true }),
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
const schema = z.strictObject({
|
|
35
|
-
submission_revision: z.number().int().positive(),
|
|
36
|
-
screen_revision: z.number().int().nonnegative(),
|
|
37
|
-
findings: findingsSchema,
|
|
38
|
-
evidence_refs: z.array(evidenceRefSchema).min(FINDING_CODES.length),
|
|
39
|
-
questions_needed: z.array(z.enum(QUESTION_CODES)).max(QUESTION_CODES.length)
|
|
40
|
-
.refine(values => new Set(values).size === values.length, 'question codes must be unique'),
|
|
41
|
-
disposition: z.enum(DISPOSITIONS),
|
|
42
|
-
}).superRefine((value, ctx) => {
|
|
43
|
-
const unknown = FINDING_CODES.filter(code => value.findings[code] === 'unknown');
|
|
44
|
-
const yes = FINDING_CODES.filter(code => value.findings[code] === 'yes');
|
|
45
|
-
const questions = new Set(value.questions_needed);
|
|
46
|
-
for (const finding of FINDING_CODES) {
|
|
47
|
-
const references = value.evidence_refs.filter(reference => reference.finding === finding);
|
|
48
|
-
if (references.length === 0) {
|
|
49
|
-
ctx.addIssue({
|
|
50
|
-
code: 'custom',
|
|
51
|
-
path: ['evidence_refs'],
|
|
52
|
-
message: `evidence is required for ${finding}`,
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
if (value.findings[finding] !== 'unknown'
|
|
56
|
-
&& !references.some(reference => CURRENT_EVIDENCE_SOURCE_TYPES.has(reference.source_type))) {
|
|
57
|
-
ctx.addIssue({
|
|
58
|
-
code: 'custom',
|
|
59
|
-
path: ['evidence_refs'],
|
|
60
|
-
message: `${finding} requires current Flow or active chat evidence`,
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
if (value.findings[finding] !== 'unknown'
|
|
64
|
-
&& references.some(reference => !CURRENT_EVIDENCE_SOURCE_TYPES.has(reference.source_type))) {
|
|
65
|
-
ctx.addIssue({
|
|
66
|
-
code: 'custom',
|
|
67
|
-
path: ['evidence_refs'],
|
|
68
|
-
message: 'historical and forecast evidence may only support unknown findings',
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
if (value.disposition === 'clear') {
|
|
73
|
-
if (FINDING_CODES.some(code => value.findings[code] !== 'no')) {
|
|
74
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'clear requires every finding to be no' });
|
|
75
|
-
}
|
|
76
|
-
if (value.questions_needed.length > 0) {
|
|
77
|
-
ctx.addIssue({ code: 'custom', path: ['questions_needed'], message: 'clear cannot request questions' });
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
if (value.disposition === 'clarify') {
|
|
81
|
-
const expectedQuestions = unknown.map(code => FINDING_TO_QUESTION[code]);
|
|
82
|
-
if (unknown.length === 0
|
|
83
|
-
|| expectedQuestions.some(code => !questions.has(code))
|
|
84
|
-
|| questions.size !== expectedQuestions.length) {
|
|
85
|
-
ctx.addIssue({ code: 'custom', path: ['questions_needed'], message: 'clarify must request every and only unknown finding' });
|
|
86
|
-
}
|
|
87
|
-
if (yes.length > 0) {
|
|
88
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'a confirmed warning requires escalation' });
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
if (value.disposition === 'review_required' && yes.length > 0) {
|
|
92
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'a confirmed warning requires escalation' });
|
|
93
|
-
}
|
|
94
|
-
if (value.disposition === 'escalate') {
|
|
95
|
-
if (yes.length === 0) {
|
|
96
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'escalate requires a confirmed warning finding' });
|
|
97
|
-
}
|
|
98
|
-
if (value.questions_needed.length > 0) {
|
|
99
|
-
ctx.addIssue({ code: 'custom', path: ['questions_needed'], message: 'escalate cannot request questions' });
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}).transform(value => ({
|
|
103
|
-
submissionRevision: value.submission_revision,
|
|
104
|
-
screenRevision: value.screen_revision,
|
|
105
|
-
findings: value.findings,
|
|
106
|
-
evidenceRefs: value.evidence_refs.map(reference => ({
|
|
107
|
-
finding: reference.finding,
|
|
108
|
-
sourceType: reference.source_type,
|
|
109
|
-
sourceId: reference.source_id,
|
|
110
|
-
observedAt: reference.observed_at,
|
|
111
|
-
})),
|
|
112
|
-
questionsNeeded: value.questions_needed,
|
|
113
|
-
disposition: value.disposition,
|
|
114
|
-
}));
|
|
115
|
-
|
|
116
|
-
class NutritionSafetyDecision extends BaseDto {}
|
|
117
|
-
|
|
118
|
-
NutritionSafetyDecision.schema = schema;
|
|
119
|
-
|
|
120
|
-
module.exports = {
|
|
121
|
-
NutritionSafetyDecision,
|
|
122
|
-
FINDING_CODES,
|
|
123
|
-
FINDING_VALUES,
|
|
124
|
-
FINDING_TO_QUESTION,
|
|
125
|
-
QUESTION_CODES,
|
|
126
|
-
EVIDENCE_SOURCE_TYPES,
|
|
127
|
-
DISPOSITIONS,
|
|
128
|
-
};
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
const { z } = require('zod');
|
|
2
|
-
|
|
3
|
-
const { BaseDto } = require('./BaseDto');
|
|
4
|
-
|
|
5
|
-
const actionSchema = z.strictObject({
|
|
6
|
-
candidateId: z.string().min(1),
|
|
7
|
-
service: z.enum(['nutrition', 'psychology']),
|
|
8
|
-
type: z.enum(['group_registration', 'urgent_nutrition_intake']),
|
|
9
|
-
invitationClass: z.enum(['first', 'followup']).nullable().default(null),
|
|
10
|
-
idempotencyKey: z.string().min(1).nullable().optional(),
|
|
11
|
-
targetKey: z.string().min(1),
|
|
12
|
-
priority: z.enum(['routine', 'soon', 'urgent']),
|
|
13
|
-
}).refine((action) => action.type !== 'group_registration' || Boolean(action.idempotencyKey), {
|
|
14
|
-
path: ['idempotencyKey'], message: 'group registration requires idempotencyKey',
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
const supportActionSchema = z.strictObject({
|
|
18
|
-
schemaVersion: z.literal('1'),
|
|
19
|
-
patientId: z.string().min(1),
|
|
20
|
-
sourceId: z.string().min(1),
|
|
21
|
-
actions: z.array(actionSchema).min(1).max(3),
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
class SupportAction extends BaseDto {}
|
|
25
|
-
|
|
26
|
-
SupportAction.schema = supportActionSchema;
|
|
27
|
-
|
|
28
|
-
module.exports = { SupportAction };
|
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
const { z } = require('zod');
|
|
2
|
-
|
|
3
|
-
const { BaseDto } = require('./BaseDto');
|
|
4
|
-
|
|
5
|
-
const dateTime = z.iso.datetime({ offset: true });
|
|
6
|
-
const PRIORITIES = ['routine', 'soon', 'urgent'];
|
|
7
|
-
const DISPOSITIONS = ['group', 'individual', 'escalated', 'reviewRequired', 'none'];
|
|
8
|
-
|
|
9
|
-
const evidenceSchema = z.strictObject({
|
|
10
|
-
source: z.enum(['triage', 'chat', 'fhir', 'airtable']),
|
|
11
|
-
sourceId: z.string().min(1),
|
|
12
|
-
code: z.string().min(1),
|
|
13
|
-
summary: z.string().max(300).nullable().default(null),
|
|
14
|
-
confidence: z.number().min(0).max(1).nullable().default(null),
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
const safetySchema = z.strictObject({
|
|
18
|
-
suicidalIdeation: z.boolean().default(false),
|
|
19
|
-
immediateRisk: z.boolean().default(false),
|
|
20
|
-
urgentMedicalRisk: z.boolean().default(false),
|
|
21
|
-
needsHumanConfirmation: z.boolean().default(false),
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
const decisionBase = {
|
|
25
|
-
disposition: z.enum(DISPOSITIONS),
|
|
26
|
-
groupEligible: z.boolean(),
|
|
27
|
-
priority: z.enum(PRIORITIES).default('routine'),
|
|
28
|
-
confidence: z.number().min(0).max(1),
|
|
29
|
-
reasonCodes: z.array(z.string().min(1)).max(20).default([]),
|
|
30
|
-
evidence: z.array(evidenceSchema).min(1).max(20),
|
|
31
|
-
safety: safetySchema,
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
const nutritionDecisionSchema = z.strictObject({
|
|
35
|
-
service: z.literal('nutrition'),
|
|
36
|
-
nutritionRisk: z.enum(['green', 'yellow', 'red', 'unknown']),
|
|
37
|
-
urgentIntakeEligible: z.boolean(),
|
|
38
|
-
...decisionBase,
|
|
39
|
-
}).superRefine((decision, ctx) => {
|
|
40
|
-
const expected = {
|
|
41
|
-
green: { eligible: true, urgentIntakeEligible: false, dispositions: ['group'] },
|
|
42
|
-
yellow: { eligible: null, urgentIntakeEligible: true, dispositions: ['individual'] },
|
|
43
|
-
red: { eligible: false, urgentIntakeEligible: false, dispositions: ['escalated'] },
|
|
44
|
-
unknown: { eligible: false, urgentIntakeEligible: false, dispositions: ['reviewRequired'] },
|
|
45
|
-
}[decision.nutritionRisk];
|
|
46
|
-
if (expected.eligible !== null && decision.groupEligible !== expected.eligible) {
|
|
47
|
-
ctx.addIssue({ code: 'custom', path: ['groupEligible'], message: `nutrition ${decision.nutritionRisk} has invalid group eligibility` });
|
|
48
|
-
}
|
|
49
|
-
if (decision.urgentIntakeEligible !== expected.urgentIntakeEligible) {
|
|
50
|
-
ctx.addIssue({ code: 'custom', path: ['urgentIntakeEligible'], message: `nutrition ${decision.nutritionRisk} has invalid urgent intake eligibility` });
|
|
51
|
-
}
|
|
52
|
-
if (!expected.dispositions.includes(decision.disposition)) {
|
|
53
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: `nutrition ${decision.nutritionRisk} has invalid disposition` });
|
|
54
|
-
}
|
|
55
|
-
if (!decision.safety.urgentMedicalRisk) {
|
|
56
|
-
if (decision.disposition === 'escalated') {
|
|
57
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'nutrition escalation requires urgent medical risk' });
|
|
58
|
-
}
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
if (decision.disposition !== 'escalated') {
|
|
62
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'urgent medical risk permits escalation only' });
|
|
63
|
-
}
|
|
64
|
-
if (decision.groupEligible) {
|
|
65
|
-
ctx.addIssue({ code: 'custom', path: ['groupEligible'], message: 'urgent medical risk cannot be group eligible' });
|
|
66
|
-
}
|
|
67
|
-
if (decision.urgentIntakeEligible) {
|
|
68
|
-
ctx.addIssue({ code: 'custom', path: ['urgentIntakeEligible'], message: 'urgent medical risk cannot be urgent intake eligible' });
|
|
69
|
-
}
|
|
70
|
-
if (decision.priority !== 'urgent') {
|
|
71
|
-
ctx.addIssue({ code: 'custom', path: ['priority'], message: 'urgent medical risk requires urgent priority' });
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
const psychologyDecisionSchema = z.strictObject({
|
|
76
|
-
service: z.literal('psychology'),
|
|
77
|
-
psychologyRisk: z.enum(['green', 'orange', 'red', 'unknown']),
|
|
78
|
-
...decisionBase,
|
|
79
|
-
}).superRefine((decision, ctx) => {
|
|
80
|
-
const expected = {
|
|
81
|
-
green: { eligible: true, dispositions: ['group'] },
|
|
82
|
-
orange: { eligible: false, dispositions: ['individual'] },
|
|
83
|
-
red: { eligible: false, dispositions: ['escalated'] },
|
|
84
|
-
unknown: { eligible: false, dispositions: ['reviewRequired'] },
|
|
85
|
-
}[decision.psychologyRisk];
|
|
86
|
-
if (decision.groupEligible !== expected.eligible) {
|
|
87
|
-
ctx.addIssue({ code: 'custom', path: ['groupEligible'], message: `psychology ${decision.psychologyRisk} has invalid group eligibility` });
|
|
88
|
-
}
|
|
89
|
-
if (!expected.dispositions.includes(decision.disposition)) {
|
|
90
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: `psychology ${decision.psychologyRisk} has invalid disposition` });
|
|
91
|
-
}
|
|
92
|
-
if ((decision.safety.suicidalIdeation || decision.safety.immediateRisk) && decision.psychologyRisk !== 'red') {
|
|
93
|
-
ctx.addIssue({ code: 'custom', path: ['psychologyRisk'], message: 'immediate or suicidal risk must be red' });
|
|
94
|
-
}
|
|
95
|
-
if ((decision.safety.suicidalIdeation || decision.safety.immediateRisk) && decision.priority !== 'urgent') {
|
|
96
|
-
ctx.addIssue({ code: 'custom', path: ['priority'], message: 'immediate or suicidal risk requires urgent priority' });
|
|
97
|
-
}
|
|
98
|
-
if ((decision.safety.suicidalIdeation || decision.safety.immediateRisk) && decision.disposition !== 'escalated') {
|
|
99
|
-
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'immediate or suicidal risk requires escalation' });
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
const schema = z.strictObject({
|
|
104
|
-
schemaVersion: z.string().default('1'),
|
|
105
|
-
decisionVersion: z.string().default('support-routing-v1'),
|
|
106
|
-
patientId: z.string().trim().min(1),
|
|
107
|
-
origin: z.enum(['triage', 'chat', 'fhir']),
|
|
108
|
-
sourceId: z.string().min(1),
|
|
109
|
-
createdAt: dateTime,
|
|
110
|
-
decisions: z.array(z.union([nutritionDecisionSchema, psychologyDecisionSchema])).max(2),
|
|
111
|
-
}).superRefine((recommendation, ctx) => {
|
|
112
|
-
const services = recommendation.decisions.map((decision) => decision.service);
|
|
113
|
-
if (new Set(services).size !== services.length) {
|
|
114
|
-
ctx.addIssue({ code: 'custom', path: ['decisions'], message: 'only one decision per service is allowed' });
|
|
115
|
-
}
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
class SupportRoutingRecommendation extends BaseDto {}
|
|
119
|
-
|
|
120
|
-
SupportRoutingRecommendation.schema = schema;
|
|
121
|
-
|
|
122
|
-
module.exports = {
|
|
123
|
-
SupportRoutingRecommendation,
|
|
124
|
-
};
|