@erosolaraijs/cure 2.3.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +7 -0
  2. package/dist/bin/cure.js +114 -1
  3. package/dist/bin/cure.js.map +1 -1
  4. package/dist/capabilities/clinicalTrialMatchingModule.d.ts +150 -0
  5. package/dist/capabilities/clinicalTrialMatchingModule.d.ts.map +1 -0
  6. package/dist/capabilities/clinicalTrialMatchingModule.js +436 -0
  7. package/dist/capabilities/clinicalTrialMatchingModule.js.map +1 -0
  8. package/dist/capabilities/emergencyOncology.d.ts +97 -0
  9. package/dist/capabilities/emergencyOncology.d.ts.map +1 -0
  10. package/dist/capabilities/emergencyOncology.js +1824 -0
  11. package/dist/capabilities/emergencyOncology.js.map +1 -0
  12. package/dist/capabilities/index.d.ts +10 -0
  13. package/dist/capabilities/index.d.ts.map +1 -1
  14. package/dist/capabilities/index.js +20 -0
  15. package/dist/capabilities/index.js.map +1 -1
  16. package/dist/capabilities/multimodalOncologyModule.d.ts +149 -0
  17. package/dist/capabilities/multimodalOncologyModule.d.ts.map +1 -0
  18. package/dist/capabilities/multimodalOncologyModule.js +701 -0
  19. package/dist/capabilities/multimodalOncologyModule.js.map +1 -0
  20. package/dist/capabilities/palliativeCareModule.d.ts +216 -0
  21. package/dist/capabilities/palliativeCareModule.d.ts.map +1 -0
  22. package/dist/capabilities/palliativeCareModule.js +1160 -0
  23. package/dist/capabilities/palliativeCareModule.js.map +1 -0
  24. package/dist/capabilities/precisionMedicineModule.d.ts +151 -0
  25. package/dist/capabilities/precisionMedicineModule.d.ts.map +1 -0
  26. package/dist/capabilities/precisionMedicineModule.js +758 -0
  27. package/dist/capabilities/precisionMedicineModule.js.map +1 -0
  28. package/dist/capabilities/specialPopulationsModule.d.ts +126 -0
  29. package/dist/capabilities/specialPopulationsModule.d.ts.map +1 -0
  30. package/dist/capabilities/specialPopulationsModule.js +574 -0
  31. package/dist/capabilities/specialPopulationsModule.js.map +1 -0
  32. package/dist/capabilities/survivorshipManagement.d.ts +178 -0
  33. package/dist/capabilities/survivorshipManagement.d.ts.map +1 -0
  34. package/dist/capabilities/survivorshipManagement.js +983 -0
  35. package/dist/capabilities/survivorshipManagement.js.map +1 -0
  36. package/dist/capabilities/treatmentSequencing.d.ts +140 -0
  37. package/dist/capabilities/treatmentSequencing.d.ts.map +1 -0
  38. package/dist/capabilities/treatmentSequencing.js +1689 -0
  39. package/dist/capabilities/treatmentSequencing.js.map +1 -0
  40. package/dist/capabilities/universalHealthFramework.d.ts +108 -0
  41. package/dist/capabilities/universalHealthFramework.d.ts.map +1 -0
  42. package/dist/capabilities/universalHealthFramework.js +615 -0
  43. package/dist/capabilities/universalHealthFramework.js.map +1 -0
  44. package/dist/compliance/hipaa.d.ts.map +1 -1
  45. package/dist/compliance/hipaa.js +7 -16
  46. package/dist/compliance/hipaa.js.map +1 -1
  47. package/dist/tools/index.d.ts +31 -0
  48. package/dist/tools/index.d.ts.map +1 -0
  49. package/dist/tools/index.js +3075 -0
  50. package/dist/tools/index.js.map +1 -0
  51. package/package.json +3 -2
  52. package/src/bin/cure.ts +130 -1
  53. package/src/capabilities/clinicalTrialMatchingModule.ts +600 -0
  54. package/src/capabilities/emergencyOncology.ts +1945 -0
  55. package/src/capabilities/index.ts +181 -0
  56. package/src/capabilities/multimodalOncologyModule.ts +873 -0
  57. package/src/capabilities/palliativeCareModule.ts +1438 -0
  58. package/src/capabilities/precisionMedicineModule.ts +952 -0
  59. package/src/capabilities/specialPopulationsModule.ts +711 -0
  60. package/src/capabilities/survivorshipManagement.ts +1213 -0
  61. package/src/capabilities/treatmentSequencing.ts +1878 -0
  62. package/src/capabilities/universalHealthFramework.ts +739 -0
  63. package/src/compliance/hipaa.ts +7 -15
  64. package/src/tools/index.ts +3501 -0
@@ -0,0 +1,3075 @@
1
+ import { UniversalCancerCureEngine } from '../capabilities/universalCancerCureEngine.js';
2
+ import { TreatmentSequencingEngine } from '../capabilities/treatmentSequencing.js';
3
+ import { SpecialPopulationsEngine } from '../capabilities/specialPopulationsModule.js';
4
+ import { GlobalCancerCoverageModule } from '../capabilities/globalCancerCoverage.js';
5
+ import { UniversalHealthEngine } from '../capabilities/universalHealthFramework.js';
6
+ import { PrecisionMedicineEngine } from '../capabilities/precisionMedicineModule.js';
7
+ import { CureValidationFramework } from '../capabilities/cureValidationFramework.js';
8
+ import { PalliativeCareEngine } from '../capabilities/palliativeCareModule.js';
9
+ import { EmergencyOncologyEngine } from '../capabilities/emergencyOncology.js';
10
+ import { SurvivorshipCareEngine } from '../capabilities/survivorshipManagement.js';
11
+ import { MultimodalOncologyEngine } from '../capabilities/multimodalOncologyModule.js';
12
+ import { ResistanceManagementEngine, CureVerificationEngine } from '../capabilities/resistanceManagement.js';
13
+ import { ClinicalTrialMatchingEngine } from '../capabilities/clinicalTrialMatchingModule.js';
14
+ import { EmergingTherapeuticsModule } from '../capabilities/emergingTherapeutics.js';
15
+ import { RetrospectiveValidationService } from '../validation/index.js';
16
+ import { createRealWorldOncologyService } from '../orchestrator/realWorldOncology.js';
17
+ import { OutcomePredictorService } from '../ml/outcomePredictor.js';
18
+ import { DrugSafetyService } from '../safety/drugInteractions.js';
19
+ import { HIPAAComplianceService } from '../compliance/hipaa.js';
20
+ import { ClinicalDecisionSupportService } from '../clinician/decisionSupport.js';
21
+ import { PatientPortalService } from '../patient/patientPortal.js';
22
+ import { UnifiedGenomicsService, GenomicPlatformClient } from '../integrations/genomics/genomicPlatforms.js';
23
+ const SAMPLE_PATIENT_ID = 'TOOL-001';
24
+ const SAMPLE_CANCER_TYPE = 'NSCLC';
25
+ const SAMPLE_STAGE = 'IV';
26
+ function formatPercent(value) {
27
+ return `${(value * 100).toFixed(1)}%`;
28
+ }
29
+ function formatNumber(value) {
30
+ return Math.round(value * 10) / 10;
31
+ }
32
+ function runToolAction(toolId, action) {
33
+ const start = Date.now();
34
+ return action()
35
+ .then(payload => {
36
+ const checks = payload.checks;
37
+ const ok = payload.ok ?? (checks ? checks.every(check => check.ok) : true);
38
+ return {
39
+ toolId,
40
+ ok,
41
+ summary: payload.summary,
42
+ durationMs: Date.now() - start,
43
+ checks,
44
+ metrics: payload.metrics
45
+ };
46
+ })
47
+ .catch(error => {
48
+ const message = error instanceof Error ? error.message : String(error);
49
+ return {
50
+ toolId,
51
+ ok: false,
52
+ summary: message,
53
+ durationMs: Date.now() - start
54
+ };
55
+ });
56
+ }
57
+ function createSampleGenomicProfile() {
58
+ return {
59
+ mutations: ['EGFR', 'TP53'],
60
+ biomarkers: ['EGFR+', 'PD-L1 60%'],
61
+ msiStatus: 'MSS',
62
+ tmbLevel: 'High',
63
+ pdl1Expression: 60,
64
+ hrdStatus: false
65
+ };
66
+ }
67
+ function createSampleRealWorldPatient() {
68
+ return {
69
+ id: SAMPLE_PATIENT_ID,
70
+ demographics: {
71
+ firstName: 'Alex',
72
+ lastName: 'Taylor',
73
+ dateOfBirth: new Date('1962-05-10'),
74
+ gender: 'male',
75
+ ethnicity: 'other',
76
+ address: {
77
+ city: 'Boston',
78
+ state: 'MA',
79
+ zipCode: '02115',
80
+ country: 'USA'
81
+ }
82
+ },
83
+ diagnosis: {
84
+ cancerType: SAMPLE_CANCER_TYPE,
85
+ stage: SAMPLE_STAGE,
86
+ diagnosisDate: new Date('2022-01-15'),
87
+ histology: 'Adenocarcinoma',
88
+ primarySite: 'Lung',
89
+ metastaticSites: ['Brain']
90
+ },
91
+ genomics: {
92
+ testDate: new Date('2022-02-01'),
93
+ platform: 'Foundation',
94
+ mutations: ['EGFR L858R', 'TP53'],
95
+ biomarkers: {
96
+ EGFR: 'positive',
97
+ 'PD-L1': '60%'
98
+ },
99
+ msiStatus: 'MSS',
100
+ tmbLevel: 'High',
101
+ tmbValue: 12,
102
+ pdl1Expression: 60,
103
+ hrdStatus: false,
104
+ hrdScore: 22
105
+ },
106
+ performanceStatus: 1,
107
+ comorbidities: ['Hypertension']
108
+ };
109
+ }
110
+ function createSamplePatientFeatures() {
111
+ return {
112
+ age: 62,
113
+ gender: 'male',
114
+ cancerType: SAMPLE_CANCER_TYPE,
115
+ stage: 'IV',
116
+ ecogStatus: 1,
117
+ genomicAlterations: [
118
+ {
119
+ gene: 'EGFR',
120
+ alteration: 'L858R',
121
+ type: 'mutation',
122
+ vaf: 0.32
123
+ }
124
+ ],
125
+ pdl1Score: 60,
126
+ pdl1ScoreType: 'TPS',
127
+ msiStatus: 'MSS',
128
+ tmbValue: 12,
129
+ tmbStatus: 'high'
130
+ };
131
+ }
132
+ function createSampleTreatmentFeatures() {
133
+ return {
134
+ regimen: 'Osimertinib',
135
+ drugs: ['Osimertinib'],
136
+ treatmentType: 'targeted',
137
+ setting: 'first-line'
138
+ };
139
+ }
140
+ function createSampleSafetyProfile(patientId) {
141
+ return {
142
+ patientId,
143
+ allergies: [
144
+ {
145
+ allergen: 'Penicillin',
146
+ reactionType: 'rash',
147
+ severity: 'moderate'
148
+ }
149
+ ],
150
+ renalFunction: {
151
+ gfr: 85,
152
+ creatinine: 1.0,
153
+ dialysis: false
154
+ },
155
+ hepaticFunction: {
156
+ childPughClass: 'A',
157
+ bilirubin: 1.1,
158
+ albumin: 4.0,
159
+ inr: 1.0,
160
+ ascites: 'none',
161
+ encephalopathy: 'none'
162
+ },
163
+ cardiacStatus: {
164
+ qtcInterval: 440,
165
+ lvef: 60,
166
+ arrhythmiaHistory: false
167
+ },
168
+ currentMedications: [
169
+ {
170
+ drug: 'Lisinopril',
171
+ dose: '10mg',
172
+ frequency: 'daily',
173
+ startDate: new Date('2020-01-01')
174
+ }
175
+ ],
176
+ demographics: {
177
+ age: 62,
178
+ weight: 78,
179
+ gender: 'male'
180
+ }
181
+ };
182
+ }
183
+ function createSampleTrialProfile() {
184
+ return {
185
+ cancerType: SAMPLE_CANCER_TYPE,
186
+ histology: 'Adenocarcinoma',
187
+ stage: SAMPLE_STAGE,
188
+ biomarkers: [
189
+ {
190
+ name: 'EGFR exon 19 del or L858R',
191
+ status: 'Positive'
192
+ }
193
+ ],
194
+ priorTherapies: ['Osimertinib'],
195
+ currentLine: 2,
196
+ age: 62,
197
+ performanceStatus: 1,
198
+ organFunction: {
199
+ renalFunction: 'Normal',
200
+ hepaticFunction: 'Normal',
201
+ cardiacFunction: 'Normal',
202
+ bonemarrowFunction: 'Normal'
203
+ },
204
+ location: {
205
+ country: 'United States',
206
+ state: 'MA',
207
+ city: 'Boston'
208
+ },
209
+ willingToTravel: true,
210
+ maxTravelDistance: 100,
211
+ preferences: {
212
+ preferredPhases: ['Phase 2', 'Phase 3'],
213
+ acceptPlaceboArm: false,
214
+ preferLocalTrials: true,
215
+ interestedMechanisms: ['EGFR inhibitors', 'Immunotherapy']
216
+ }
217
+ };
218
+ }
219
+ function createSamplePainAssessment() {
220
+ return {
221
+ location: ['Lower back'],
222
+ intensity: 7,
223
+ quality: ['Burning', 'Shooting'],
224
+ temporalPattern: 'Constant',
225
+ aggravatingFactors: ['Movement'],
226
+ relievingFactors: ['Rest', 'Heat'],
227
+ functionalImpact: {
228
+ sleepDisturbance: 2,
229
+ mobilityImpairment: 1,
230
+ selfCareImpairment: 0,
231
+ socialImpairment: 1,
232
+ overallQoL: 6
233
+ },
234
+ psychologicalImpact: ['Anxiety'],
235
+ painType: ['Neuropathic-Peripheral']
236
+ };
237
+ }
238
+ function createSampleTreatmentSummary() {
239
+ return {
240
+ cancerType: 'breast',
241
+ stage: 'early stage',
242
+ summary: {
243
+ surgery: [
244
+ {
245
+ procedure: 'Lumpectomy',
246
+ date: '2022-06-01',
247
+ findings: 'Clear margins',
248
+ complications: [],
249
+ longTermConsiderations: ['Lymphedema monitoring']
250
+ }
251
+ ],
252
+ radiation: [
253
+ {
254
+ site: 'Breast',
255
+ modality: 'IMRT',
256
+ totalDose: '50 Gy',
257
+ fractions: 25,
258
+ completionDate: '2022-09-01',
259
+ acuteToxicities: ['Fatigue'],
260
+ expectedLateEffects: ['Fibrosis']
261
+ }
262
+ ],
263
+ systemicTherapy: [
264
+ {
265
+ agentClass: 'Chemotherapy',
266
+ specificAgents: ['Doxorubicin', 'Cyclophosphamide'],
267
+ duration: '12 weeks',
268
+ completionDate: '2022-05-01',
269
+ significantToxicities: ['Nausea'],
270
+ expectedLateEffects: ['Cardiac monitoring']
271
+ }
272
+ ],
273
+ otherTreatments: []
274
+ }
275
+ };
276
+ }
277
+ function createSamplePortalSummary(patientId) {
278
+ return {
279
+ patientId,
280
+ diagnosis: {
281
+ condition: 'Non-small cell lung cancer',
282
+ diagnosisDate: new Date('2022-01-15'),
283
+ stage: 'IV',
284
+ simpleExplanation: 'Lung cancer that has spread, treated with targeted therapy.'
285
+ },
286
+ currentTreatment: {
287
+ regimen: 'Osimertinib',
288
+ medications: [
289
+ {
290
+ name: 'Osimertinib',
291
+ purpose: 'Target EGFR mutation',
292
+ dose: '80mg',
293
+ frequency: 'Daily',
294
+ instructions: 'Take with or without food',
295
+ sideEffectsToWatch: ['Rash', 'Diarrhea']
296
+ }
297
+ ],
298
+ startDate: new Date('2022-02-01'),
299
+ cycleInfo: {
300
+ currentCycle: 3,
301
+ totalPlannedCycles: 12,
302
+ nextCycleDate: new Date('2022-05-01')
303
+ },
304
+ whatToExpect: ['Monthly labs', 'Imaging every 8-12 weeks'],
305
+ whenToCallDoctor: ['Fever over 100.4F', 'Shortness of breath']
306
+ },
307
+ upcomingAppointments: [
308
+ {
309
+ date: new Date('2022-05-15'),
310
+ type: 'CT Scan',
311
+ provider: 'Radiology',
312
+ location: 'Main Hospital'
313
+ }
314
+ ],
315
+ careTeam: [
316
+ {
317
+ role: 'Medical Oncologist',
318
+ name: 'Dr. Chen',
319
+ phone: '555-0101',
320
+ messageable: true
321
+ }
322
+ ],
323
+ goals: [
324
+ {
325
+ goal: 'Maintain energy levels',
326
+ progress: 70,
327
+ lastUpdated: new Date('2022-04-01')
328
+ }
329
+ ]
330
+ };
331
+ }
332
+ function buildSampleGenomicResults(patientId) {
333
+ return [
334
+ {
335
+ reportId: 'REP-001',
336
+ orderId: 'ORD-001',
337
+ patientId,
338
+ testType: 'comprehensive-genomic-profiling',
339
+ panelName: 'MockPanel',
340
+ specimenInfo: {
341
+ type: 'tissue',
342
+ collectionDate: new Date('2023-01-10'),
343
+ tumorPurity: 0.4
344
+ },
345
+ reportDate: new Date('2023-01-20'),
346
+ variants: [
347
+ {
348
+ gene: 'EGFR',
349
+ hgvsP: 'p.L858R',
350
+ variantType: 'SNV',
351
+ variantAlleleFrequency: 0.32,
352
+ clinicalSignificance: 'pathogenic'
353
+ }
354
+ ],
355
+ copyNumberAlterations: [],
356
+ fusions: [],
357
+ biomarkers: [
358
+ {
359
+ name: 'PD-L1',
360
+ value: 60,
361
+ unit: '%',
362
+ status: 'positive',
363
+ method: 'IHC'
364
+ }
365
+ ],
366
+ therapyMatches: [],
367
+ clinicalTrialMatches: [],
368
+ signatures: {
369
+ microsatelliteInstability: {
370
+ status: 'MSS',
371
+ method: 'NGS'
372
+ },
373
+ tumorMutationalBurden: {
374
+ value: 12,
375
+ unit: 'mutations/Mb',
376
+ status: 'high',
377
+ threshold: 10
378
+ }
379
+ },
380
+ qualityMetrics: {
381
+ meanCoverage: 500,
382
+ percentBases100x: 0.95
383
+ }
384
+ }
385
+ ];
386
+ }
387
+ class MockGenomicClient extends GenomicPlatformClient {
388
+ sampleResults;
389
+ constructor(config, sampleResults) {
390
+ super(config);
391
+ this.sampleResults = sampleResults;
392
+ }
393
+ async authenticate() {
394
+ return;
395
+ }
396
+ async submitOrder(order) {
397
+ return { orderId: order.orderId, status: 'completed' };
398
+ }
399
+ async getOrderStatus(orderId) {
400
+ return {
401
+ orderId,
402
+ patientId: SAMPLE_PATIENT_ID,
403
+ testType: 'comprehensive-genomic-profiling',
404
+ panelName: 'MockPanel',
405
+ specimenType: 'tissue',
406
+ orderDate: new Date(),
407
+ clinicalIndication: 'Mock indication',
408
+ icdCodes: ['C34.9'],
409
+ orderingPhysician: {
410
+ name: 'Dr. Smith',
411
+ npi: '0000000000',
412
+ facility: 'Mock Hospital'
413
+ },
414
+ status: 'completed'
415
+ };
416
+ }
417
+ async getResults(_orderId) {
418
+ return this.sampleResults[0];
419
+ }
420
+ async listPatientResults(patientId) {
421
+ return this.sampleResults.filter(result => result.patientId === patientId);
422
+ }
423
+ }
424
+ function buildSampleValidationData() {
425
+ const cohortId = 'sample-cohort';
426
+ const patients = [
427
+ {
428
+ id: 'VAL-001',
429
+ demographics: { ageAtDiagnosis: 67, gender: 'male' },
430
+ diagnosis: {
431
+ cancerType: 'NSCLC',
432
+ stage: 'IV',
433
+ diagnosisDate: new Date('2021-11-15'),
434
+ biomarkers: [{ name: 'EGFR', value: 'L858R' }]
435
+ },
436
+ treatment: {
437
+ regimen: 'Osimertinib',
438
+ drugs: ['Osimertinib'],
439
+ setting: 'first-line',
440
+ startDate: new Date('2021-12-01'),
441
+ endDate: new Date('2023-01-15')
442
+ },
443
+ outcomes: {
444
+ bestResponse: 'PR',
445
+ responseDate: new Date('2022-02-15'),
446
+ progressionDate: new Date('2023-01-15'),
447
+ lastFollowUpDate: new Date('2023-02-01')
448
+ },
449
+ ecogAtBaseline: 1,
450
+ priorLines: 0
451
+ },
452
+ {
453
+ id: 'VAL-002',
454
+ demographics: { ageAtDiagnosis: 55, gender: 'female' },
455
+ diagnosis: {
456
+ cancerType: 'Breast Cancer',
457
+ stage: 'II',
458
+ diagnosisDate: new Date('2020-03-10'),
459
+ biomarkers: [{ name: 'ER', value: 'positive' }, { name: 'HER2', value: 'negative' }]
460
+ },
461
+ treatment: {
462
+ regimen: 'AC-T',
463
+ drugs: ['Doxorubicin', 'Cyclophosphamide', 'Paclitaxel'],
464
+ setting: 'adjuvant',
465
+ startDate: new Date('2020-04-01'),
466
+ endDate: new Date('2020-09-15'),
467
+ cycles: 8
468
+ },
469
+ outcomes: {
470
+ bestResponse: 'CR',
471
+ responseDate: new Date('2020-09-10'),
472
+ lastFollowUpDate: new Date('2023-03-10')
473
+ },
474
+ ecogAtBaseline: 0,
475
+ priorLines: 0
476
+ },
477
+ {
478
+ id: 'VAL-003',
479
+ demographics: { ageAtDiagnosis: 48, gender: 'female' },
480
+ diagnosis: {
481
+ cancerType: 'Melanoma',
482
+ stage: 'III',
483
+ diagnosisDate: new Date('2019-06-01'),
484
+ biomarkers: [{ name: 'BRAF', value: 'V600E' }]
485
+ },
486
+ treatment: {
487
+ regimen: 'Nivolumab',
488
+ drugs: ['Nivolumab'],
489
+ setting: 'adjuvant',
490
+ startDate: new Date('2019-07-01'),
491
+ endDate: new Date('2020-02-01')
492
+ },
493
+ outcomes: {
494
+ bestResponse: 'SD',
495
+ responseDate: new Date('2019-10-01'),
496
+ progressionDate: new Date('2020-02-01'),
497
+ deathDate: new Date('2021-01-15'),
498
+ lastFollowUpDate: new Date('2021-01-15')
499
+ },
500
+ ecogAtBaseline: 1,
501
+ priorLines: 1
502
+ }
503
+ ];
504
+ const recommendations = [
505
+ {
506
+ patientId: 'VAL-001',
507
+ recommendedRegimen: 'Osimertinib',
508
+ recommendedDrugs: ['Osimertinib'],
509
+ predictions: {
510
+ responseRate: 0.68,
511
+ pfsMonths: 14,
512
+ osMonths: 28,
513
+ toxicityRisk: 0.2
514
+ },
515
+ matchingBiomarkers: ['EGFR L858R'],
516
+ confidenceScore: 0.82,
517
+ timestamp: new Date('2021-12-01')
518
+ },
519
+ {
520
+ patientId: 'VAL-002',
521
+ recommendedRegimen: 'AC-T',
522
+ recommendedDrugs: ['Doxorubicin', 'Cyclophosphamide', 'Paclitaxel'],
523
+ predictions: {
524
+ responseRate: 0.85,
525
+ pfsMonths: 30,
526
+ osMonths: 60,
527
+ toxicityRisk: 0.25
528
+ },
529
+ matchingBiomarkers: ['ER+', 'PR+', 'HER2-'],
530
+ confidenceScore: 0.88,
531
+ timestamp: new Date('2020-04-01')
532
+ },
533
+ {
534
+ patientId: 'VAL-003',
535
+ recommendedRegimen: 'Nivolumab + Ipilimumab',
536
+ recommendedDrugs: ['Nivolumab', 'Ipilimumab'],
537
+ predictions: {
538
+ responseRate: 0.55,
539
+ pfsMonths: 10,
540
+ osMonths: 24,
541
+ toxicityRisk: 0.35
542
+ },
543
+ matchingBiomarkers: ['BRAF V600E'],
544
+ confidenceScore: 0.7,
545
+ timestamp: new Date('2019-07-01')
546
+ }
547
+ ];
548
+ return { cohortId, patients, recommendations };
549
+ }
550
+ export async function runSelfTestSuite(context) {
551
+ const start = Date.now();
552
+ const checks = [];
553
+ const cancerTreatment = context.cancerTreatment;
554
+ const runCheck = async (name, task) => {
555
+ try {
556
+ const result = await task();
557
+ checks.push({ name, ok: result.ok, detail: result.detail });
558
+ }
559
+ catch (error) {
560
+ const message = error instanceof Error ? error.message : String(error);
561
+ checks.push({ name, ok: false, detail: message });
562
+ }
563
+ };
564
+ await runCheck('protocols-loaded', async () => {
565
+ const protocols = await cancerTreatment.listTreatmentProtocols();
566
+ return {
567
+ ok: protocols.length > 0,
568
+ detail: `count=${protocols.length}`
569
+ };
570
+ });
571
+ await runCheck('drug-targets-loaded', async () => {
572
+ const targets = await cancerTreatment.listDrugTargets();
573
+ return {
574
+ ok: targets.length > 10,
575
+ detail: `count=${targets.length}`
576
+ };
577
+ });
578
+ await runCheck('analyze-patient', async () => {
579
+ const analysis = await cancerTreatment.analyzePatient('SELFTEST-001', true);
580
+ const cancerType = analysis?.analysis?.cancerType;
581
+ return {
582
+ ok: Boolean(cancerType),
583
+ detail: `cancerType=${cancerType ?? 'unknown'}`
584
+ };
585
+ });
586
+ await runCheck('treatment-plan', async () => {
587
+ const plan = await cancerTreatment.designTreatmentPlan('SELFTEST-001');
588
+ const protocolId = plan?.plan?.protocol?.id;
589
+ return {
590
+ ok: Boolean(protocolId),
591
+ detail: `protocol=${protocolId ?? 'unknown'}`
592
+ };
593
+ });
594
+ await runCheck('target-discovery', async () => {
595
+ const discovery = await cancerTreatment.discoverDrugTargets('Lung', 'EGFR');
596
+ const matchCount = Array.isArray(discovery?.discoveredTargets)
597
+ ? discovery.discoveredTargets.length
598
+ : 0;
599
+ return {
600
+ ok: matchCount > 0,
601
+ detail: `matches=${matchCount}`
602
+ };
603
+ });
604
+ await runCheck('cure-protocol', async () => {
605
+ const result = await cancerTreatment.cureCancer('SELFTEST-001', 'Lung', 'IV', {
606
+ mutations: ['EGFR'],
607
+ biomarkers: ['EGFR+'],
608
+ msiStatus: 'MSS',
609
+ tmbLevel: 'High',
610
+ pdl1Expression: 60,
611
+ hrdStatus: false
612
+ });
613
+ const confidence = result?.projectedOutcome?.cureConfidence;
614
+ return {
615
+ ok: typeof confidence === 'number',
616
+ detail: confidence !== undefined ? `confidence=${formatPercent(confidence)}` : 'confidence=unknown'
617
+ };
618
+ });
619
+ const ok = checks.every(check => check.ok);
620
+ const summary = ok
621
+ ? `All ${checks.length} checks passed`
622
+ : `${checks.filter(check => !check.ok).length} checks failed`;
623
+ return {
624
+ toolId: 'selftest',
625
+ ok,
626
+ summary,
627
+ durationMs: Date.now() - start,
628
+ checks
629
+ };
630
+ }
631
+ export async function runValidationSample() {
632
+ const start = Date.now();
633
+ try {
634
+ const service = new RetrospectiveValidationService();
635
+ const { cohortId, patients, recommendations } = buildSampleValidationData();
636
+ service.loadCohort(cohortId, patients);
637
+ service.loadRecommendations(recommendations);
638
+ const analysis = await service.runValidation(cohortId);
639
+ const metrics = {
640
+ patients: analysis.patientCount,
641
+ fullConcordance: formatPercent(analysis.concordance.fullConcordance),
642
+ partialConcordance: formatPercent(analysis.concordance.partialConcordance),
643
+ responseAccuracy: formatPercent(analysis.predictionAccuracy.responseAccuracy),
644
+ medianPfsMonths: formatNumber(analysis.clinicalImpact.medianPFS),
645
+ medianOsMonths: formatNumber(analysis.clinicalImpact.medianOS)
646
+ };
647
+ return {
648
+ toolId: 'validate',
649
+ ok: analysis.patientCount === patients.length,
650
+ summary: `Validated ${analysis.patientCount} patients`,
651
+ durationMs: Date.now() - start,
652
+ metrics
653
+ };
654
+ }
655
+ catch (error) {
656
+ const message = error instanceof Error ? error.message : String(error);
657
+ return {
658
+ toolId: 'validate',
659
+ ok: false,
660
+ summary: message,
661
+ durationMs: Date.now() - start
662
+ };
663
+ }
664
+ }
665
+ async function runCancerCore(context) {
666
+ return runToolAction('cancer-core', async () => {
667
+ const protocols = await context.cancerTreatment.listTreatmentProtocols();
668
+ const targets = await context.cancerTreatment.listDrugTargets();
669
+ const immunotherapies = await context.cancerTreatment.listImmunotherapyProtocols();
670
+ const combos = await context.cancerTreatment.listCombinationTherapies();
671
+ const checks = [
672
+ { name: 'protocols', ok: protocols.length > 0, detail: `count=${protocols.length}` },
673
+ { name: 'targets', ok: targets.length > 0, detail: `count=${targets.length}` },
674
+ { name: 'immunotherapy', ok: immunotherapies.length > 0, detail: `count=${immunotherapies.length}` },
675
+ { name: 'combinations', ok: combos.length > 0, detail: `count=${combos.length}` }
676
+ ];
677
+ return {
678
+ summary: `Protocols ${protocols.length}, targets ${targets.length}`,
679
+ checks,
680
+ metrics: {
681
+ protocols: protocols.length,
682
+ drugTargets: targets.length,
683
+ immunotherapyProtocols: immunotherapies.length,
684
+ combinationTherapies: combos.length
685
+ }
686
+ };
687
+ });
688
+ }
689
+ async function runCancerAnalyze(context) {
690
+ return runToolAction('cancer-analyze', async () => {
691
+ const result = await context.cancerTreatment.analyzePatient(SAMPLE_PATIENT_ID, true);
692
+ const analysis = result.analysis;
693
+ return {
694
+ summary: `Analyzed ${analysis.cancerType} ${analysis.stage}`,
695
+ metrics: {
696
+ cancerType: analysis.cancerType,
697
+ stage: analysis.stage,
698
+ biomarkers: analysis.biomarkers.join(', '),
699
+ survivalProbability: formatPercent(analysis.riskAssessment.survivalProbability)
700
+ }
701
+ };
702
+ });
703
+ }
704
+ async function runCancerPlan(context) {
705
+ return runToolAction('cancer-plan', async () => {
706
+ const result = await context.cancerTreatment.designTreatmentPlan(SAMPLE_PATIENT_ID);
707
+ const protocolName = result.plan.protocol.name;
708
+ return {
709
+ summary: `Plan ${protocolName}`,
710
+ metrics: {
711
+ protocol: protocolName,
712
+ estimatedEfficacy: formatPercent(result.estimatedEfficacy)
713
+ }
714
+ };
715
+ });
716
+ }
717
+ async function runCancerCure(context) {
718
+ return runToolAction('cancer-cure', async () => {
719
+ const profile = createSampleGenomicProfile();
720
+ const result = await context.cancerTreatment.cureCancer(SAMPLE_PATIENT_ID, SAMPLE_CANCER_TYPE, SAMPLE_STAGE, profile);
721
+ return {
722
+ summary: `Status ${result.status}`,
723
+ metrics: {
724
+ cureConfidence: formatPercent(result.projectedOutcome.cureConfidence),
725
+ responseRate: formatPercent(result.projectedOutcome.responseRate),
726
+ fiveYearSurvival: formatPercent(result.projectedOutcome.fiveYearSurvival)
727
+ }
728
+ };
729
+ });
730
+ }
731
+ async function runCancerDiscover(context) {
732
+ return runToolAction('cancer-discover', async () => {
733
+ const discovery = await context.cancerTreatment.discoverDrugTargets('Lung', 'EGFR');
734
+ const matchCount = Array.isArray(discovery?.discoveredTargets)
735
+ ? discovery.discoveredTargets.length
736
+ : 0;
737
+ const topTarget = discovery?.discoveredTargets?.[0]?.gene || 'none';
738
+ return {
739
+ summary: `Discovered ${matchCount} targets`,
740
+ metrics: {
741
+ matches: matchCount,
742
+ topTarget
743
+ }
744
+ };
745
+ });
746
+ }
747
+ async function runUniversalCure() {
748
+ return runToolAction('universal-cure', async () => {
749
+ const engine = new UniversalCancerCureEngine();
750
+ const result = await engine.cureAnyCancer('U-001', {
751
+ cancerType: 'NSCLC',
752
+ stage: 'IV',
753
+ histology: 'Adenocarcinoma'
754
+ }, {
755
+ age: 62,
756
+ gender: 'male',
757
+ performanceStatus: 1,
758
+ comorbidities: ['Hypertension'],
759
+ priorTreatments: ['Osimertinib']
760
+ }, {
761
+ mutations: ['EGFR'],
762
+ msiStatus: 'MSS',
763
+ tmbScore: 12,
764
+ immuneScore: 'Hot',
765
+ pdl1TPS: 60
766
+ });
767
+ return {
768
+ summary: `Universal cure status ${result.status}`,
769
+ metrics: {
770
+ cureProbability: formatPercent(result.cureProbability),
771
+ primaryStrategy: result.treatmentPlan.primaryStrategy,
772
+ trialMatches: result.clinicalTrialMatches.highPriority.length +
773
+ result.clinicalTrialMatches.alternatives.length +
774
+ result.clinicalTrialMatches.emergingTrials.length
775
+ }
776
+ };
777
+ });
778
+ }
779
+ async function runGlobalCoverage() {
780
+ return runToolAction('global-coverage', async () => {
781
+ const module = new GlobalCancerCoverageModule();
782
+ const stats = module.getCoverageStatistics();
783
+ return {
784
+ summary: `Guidelines ${stats.totalGlobalGuidelines}`,
785
+ metrics: {
786
+ guidelines: stats.totalGlobalGuidelines,
787
+ regions: stats.regionsRepresented.join(', '),
788
+ rareCancers: stats.totalRareCancers,
789
+ pediatricProtocols: stats.totalPediatricProtocols,
790
+ supportiveCare: stats.totalSupportiveCareProtocols,
791
+ specialPopulations: stats.totalSpecialPopulations
792
+ }
793
+ };
794
+ });
795
+ }
796
+ async function runTreatmentSequencing() {
797
+ return runToolAction('treatment-sequencing', async () => {
798
+ const engine = new TreatmentSequencingEngine();
799
+ const recommendations = engine.getNextLineRecommendation('NSCLC', 'EGFR-mutant (exon 19 del or L858R)', '1L', ['nsclc-egfr-1l-osi'], { 'EGFR exon 19 del or L858R': 'positive' });
800
+ return {
801
+ summary: `Next-line regimens ${recommendations.length}`,
802
+ metrics: {
803
+ recommendations: recommendations.length,
804
+ topRegimen: recommendations[0]?.name || 'none'
805
+ }
806
+ };
807
+ });
808
+ }
809
+ async function runPrecisionMedicine() {
810
+ return runToolAction('precision-medicine', async () => {
811
+ const engine = new PrecisionMedicineEngine();
812
+ const report = engine.generatePrecisionReport(SAMPLE_PATIENT_ID, [
813
+ { gene: 'EGFR', alteration: 'L858R', type: 'mutation' },
814
+ { gene: 'PIK3CA', alteration: 'E545K', type: 'mutation' }
815
+ ], ['DPYD']);
816
+ return {
817
+ summary: report.summary,
818
+ metrics: {
819
+ actionableTargets: report.actionableTargets.length,
820
+ pharmacogenomics: report.pgxRecommendations.length,
821
+ clinicalTrialTargets: report.clinicalTrialTargets.length
822
+ }
823
+ };
824
+ });
825
+ }
826
+ async function runEmergingTherapeutics() {
827
+ return runToolAction('emerging-therapeutics', async () => {
828
+ const module = new EmergingTherapeuticsModule();
829
+ const stats = module.getStatistics();
830
+ return {
831
+ summary: `Emerging targets ${stats.totalNovelTargets}`,
832
+ metrics: {
833
+ cellularTherapies: stats.totalCellularTherapies,
834
+ proteinDegraders: stats.totalProteinDegraders,
835
+ radiopharmaceuticals: stats.totalRadiopharmaceuticals,
836
+ novelTargets: stats.totalNovelTargets,
837
+ aiDrugs: stats.totalAIDrugs,
838
+ stageBreakdown: JSON.stringify(stats.breakdownByStage)
839
+ }
840
+ };
841
+ });
842
+ }
843
+ async function runMultimodalOncology() {
844
+ return runToolAction('multimodal-oncology', async () => {
845
+ const engine = new MultimodalOncologyEngine();
846
+ const sequence = engine.getMultimodalSequence('HER2+ Breast Cancer', 'Stage II-III');
847
+ const bed = engine.calculateBED(60, 30, 10);
848
+ return {
849
+ summary: sequence ? `Sequence found for ${sequence.cancerType}` : 'Sequence not found',
850
+ metrics: {
851
+ sequencePhases: sequence ? sequence.sequence.length : 0,
852
+ bed: formatNumber(bed)
853
+ }
854
+ };
855
+ });
856
+ }
857
+ async function runSpecialPopulations() {
858
+ return runToolAction('special-populations', async () => {
859
+ const engine = new SpecialPopulationsEngine();
860
+ const pediatric = engine.calculatePediatricDose('Vincristine', 18, 110, 6);
861
+ const geriatric = engine.performGeriatricAssessment({
862
+ adl: 4,
863
+ iadl: 5,
864
+ comorbidity: 2
865
+ });
866
+ return {
867
+ summary: `Pediatric dose ${pediatric.dose}`,
868
+ metrics: {
869
+ pediatricDose: pediatric.dose,
870
+ geriatricRisk: geriatric.riskCategory,
871
+ monitoringItems: pediatric.monitoring.length
872
+ }
873
+ };
874
+ });
875
+ }
876
+ async function runResistanceManagement() {
877
+ return runToolAction('resistance-management', async () => {
878
+ const engine = new ResistanceManagementEngine();
879
+ const analysis = engine.analyzeResistance('Osimertinib', 'EGFR', 'T790M', { age: 63, ps: 1, priorLines: 1 });
880
+ const prevention = engine.generatePreventionPlan('NSCLC', 'EGFR TKI', ['EGFR']);
881
+ return {
882
+ summary: `Resistance urgency ${analysis.urgency}`,
883
+ metrics: {
884
+ strategies: analysis.recommendedStrategies.length,
885
+ preventionStrategies: prevention.strategies.length,
886
+ combinationOptions: prevention.combinationOptions.length
887
+ }
888
+ };
889
+ });
890
+ }
891
+ async function runCureVerification() {
892
+ return runToolAction('cure-verification', async () => {
893
+ const engine = new CureVerificationEngine();
894
+ const result = engine.verifyCureStatus('Breast Cancer', 24, 'CR', 'negative', 'undetectable', 18, 18);
895
+ return {
896
+ summary: `Verification ${result.status}`,
897
+ metrics: {
898
+ confidence: formatPercent(result.confidence),
899
+ evidenceItems: result.evidence.length
900
+ }
901
+ };
902
+ });
903
+ }
904
+ async function runCureValidation() {
905
+ return runToolAction('cure-validation', async () => {
906
+ const framework = new CureValidationFramework();
907
+ const report = await framework.validateCoverageCompleteness();
908
+ return {
909
+ summary: `Coverage ${formatNumber(report.coveragePercentage)}%`,
910
+ metrics: {
911
+ totalCancerTypes: report.totalCancerTypes,
912
+ coveredCancerTypes: report.coveredCancerTypes,
913
+ coveragePercent: `${formatNumber(report.coveragePercentage)}%`,
914
+ gapCount: report.gaps.length
915
+ }
916
+ };
917
+ });
918
+ }
919
+ async function runClinicalTrialMatching() {
920
+ return runToolAction('clinical-trial-matching', async () => {
921
+ const engine = new ClinicalTrialMatchingEngine();
922
+ const matches = engine.findMatchingTrials(createSampleTrialProfile());
923
+ const topMatch = matches[0];
924
+ return {
925
+ summary: `Matches ${matches.length}`,
926
+ metrics: {
927
+ matches: matches.length,
928
+ topTrial: topMatch?.trial?.nctId || 'none',
929
+ topScore: topMatch ? formatNumber(topMatch.matchScore) : 0
930
+ }
931
+ };
932
+ });
933
+ }
934
+ async function runPalliativeCare() {
935
+ return runToolAction('palliative-care', async () => {
936
+ const engine = new PalliativeCareEngine();
937
+ const protocol = engine.assessPain(createSamplePainAssessment());
938
+ const conversion = engine.calculateOpioidConversion('Morphine', 30, 'PO', 'Oxycodone', 'PO');
939
+ return {
940
+ summary: protocol ? `Pain protocol ${protocol.severity}` : 'No pain protocol matched',
941
+ metrics: {
942
+ severity: protocol?.severity || 'unknown',
943
+ opioidConversionDose: conversion.dose,
944
+ conversionNotes: conversion.notes.length
945
+ }
946
+ };
947
+ });
948
+ }
949
+ async function runEmergencyOncology() {
950
+ return runToolAction('emergency-oncology', async () => {
951
+ const engine = new EmergencyOncologyEngine();
952
+ const matches = engine.identifyPotentialEmergency(['Back pain', 'Weakness', 'Urinary retention'], { calcium: 13.2, potassium: 6.1 });
953
+ const top = matches[0];
954
+ return {
955
+ summary: `Potential emergencies ${matches.length}`,
956
+ metrics: {
957
+ matches: matches.length,
958
+ topEmergency: top?.name || 'none',
959
+ topUrgency: top?.urgency || 'n/a'
960
+ }
961
+ };
962
+ });
963
+ }
964
+ async function runSurvivorshipCare() {
965
+ return runToolAction('survivorship-care', async () => {
966
+ const engine = new SurvivorshipCareEngine();
967
+ const sample = createSampleTreatmentSummary();
968
+ const plan = engine.generateSurvivorshipCarePlan(sample.cancerType, sample.stage, sample.summary);
969
+ return {
970
+ summary: `Survivorship plan for ${plan.cancerType}`,
971
+ metrics: {
972
+ surveillanceDuration: plan.surveillanceProtocol.duration,
973
+ lateEffects: plan.lateEffectsScreening.length,
974
+ secondaryMalignancy: plan.secondaryMalignancyScreening.length
975
+ }
976
+ };
977
+ });
978
+ }
979
+ async function runUniversalHealth() {
980
+ return runToolAction('universal-health', async () => {
981
+ const engine = new UniversalHealthEngine();
982
+ const plan = engine.generateHealthPlan(45, 'Male', ['hypertension'], ['smoking', 'obesity']);
983
+ return {
984
+ summary: `Health plan with ${plan.conditionManagement.length} conditions`,
985
+ metrics: {
986
+ preventiveCare: plan.preventiveCare.length,
987
+ conditionManagement: plan.conditionManagement.length,
988
+ riskModifications: plan.riskModification.length,
989
+ specialistReferrals: plan.specialistReferrals.length
990
+ }
991
+ };
992
+ });
993
+ }
994
+ async function runClinicalDecisionSupport() {
995
+ return runToolAction('clinical-decision-support', async () => {
996
+ const service = new ClinicalDecisionSupportService();
997
+ const recommendation = await service.generateRecommendation({
998
+ patientId: SAMPLE_PATIENT_ID,
999
+ cancerType: SAMPLE_CANCER_TYPE,
1000
+ stage: SAMPLE_STAGE,
1001
+ biomarkers: [
1002
+ { name: 'EGFR', value: 'L858R', status: 'positive' },
1003
+ { name: 'PD-L1', value: 60, status: 'positive' }
1004
+ ],
1005
+ genomicAlterations: [
1006
+ { gene: 'EGFR', alteration: 'L858R' },
1007
+ { gene: 'TP53', alteration: 'loss' }
1008
+ ],
1009
+ priorTherapies: ['Osimertinib'],
1010
+ performanceStatus: 1,
1011
+ comorbidities: ['Hypertension']
1012
+ });
1013
+ return {
1014
+ summary: `Recommendation ${recommendation.primaryRecommendation.regimen}`,
1015
+ metrics: {
1016
+ primaryRegimen: recommendation.primaryRecommendation.regimen,
1017
+ alternatives: recommendation.alternativeOptions.length,
1018
+ responseRate: formatPercent(recommendation.predictions.responseRate.value)
1019
+ }
1020
+ };
1021
+ });
1022
+ }
1023
+ async function runPatientPortal() {
1024
+ return runToolAction('patient-portal', async () => {
1025
+ const portal = new PatientPortalService();
1026
+ const accountData = {
1027
+ mrn: 'MRN-001',
1028
+ email: 'patient@example.com',
1029
+ preferredLanguage: 'en',
1030
+ preferredContactMethod: 'portal',
1031
+ accessLevel: 'full',
1032
+ notificationPreferences: {
1033
+ appointments: true,
1034
+ labResults: true,
1035
+ messages: true,
1036
+ medications: true,
1037
+ educational: true
1038
+ }
1039
+ };
1040
+ const account = await portal.createAccount(accountData);
1041
+ const summary = createSamplePortalSummary(account.id);
1042
+ portal.setTreatmentSummary(summary);
1043
+ const simple = portal.generateSimpleSummary('NSCLC', 'IV', 'Osimertinib');
1044
+ return {
1045
+ summary: `Portal account ${account.id}`,
1046
+ metrics: {
1047
+ summaryLines: simple.whatItMeans.length,
1048
+ careTeam: summary.careTeam.length,
1049
+ upcomingAppointments: summary.upcomingAppointments.length
1050
+ }
1051
+ };
1052
+ });
1053
+ }
1054
+ async function runMLOutcome() {
1055
+ return runToolAction('ml-outcome', async () => {
1056
+ const predictor = new OutcomePredictorService();
1057
+ const patient = createSamplePatientFeatures();
1058
+ const treatment = createSampleTreatmentFeatures();
1059
+ const response = await predictor.predictResponse(patient, treatment);
1060
+ const survival = await predictor.predictSurvival(patient, treatment);
1061
+ return {
1062
+ summary: `Predicted response ${response.predictedResponse}`,
1063
+ metrics: {
1064
+ objectiveResponseRate: formatPercent(response.objectiveResponseRate),
1065
+ medianPfsMonths: formatNumber(survival.pfs.median),
1066
+ medianOsMonths: formatNumber(survival.os.median)
1067
+ }
1068
+ };
1069
+ });
1070
+ }
1071
+ async function runDrugSafety() {
1072
+ return runToolAction('drug-safety', async () => {
1073
+ const safety = new DrugSafetyService();
1074
+ const patient = createSampleSafetyProfile(SAMPLE_PATIENT_ID);
1075
+ const result = await safety.performSafetyCheck(patient, [
1076
+ { drug: 'Pembrolizumab', dose: '200mg', route: 'IV' },
1077
+ { drug: 'Ipilimumab', dose: '3mg/kg', route: 'IV' }
1078
+ ]);
1079
+ return {
1080
+ summary: `Safety risk ${result.summary.overallRisk}`,
1081
+ metrics: {
1082
+ criticalAlerts: result.summary.criticalAlerts,
1083
+ highAlerts: result.summary.highAlerts,
1084
+ overallRisk: result.summary.overallRisk
1085
+ }
1086
+ };
1087
+ });
1088
+ }
1089
+ async function runHipaaCompliance() {
1090
+ return runToolAction('hipaa-compliance', async () => {
1091
+ const hipaa = new HIPAAComplianceService();
1092
+ const phi = {
1093
+ ssn: '123-45-6789',
1094
+ dob: '1980-01-01',
1095
+ phone: '555-123-4567',
1096
+ address: {
1097
+ street: '100 Main St',
1098
+ city: 'Boston',
1099
+ state: 'MA',
1100
+ zip: '02115'
1101
+ },
1102
+ mrn: 'MRN-001',
1103
+ genomics: { EGFR: 'L858R' }
1104
+ };
1105
+ const masked = hipaa.maskPHI(phi, 'clinical');
1106
+ const encrypted = await hipaa.encryptPHI(phi);
1107
+ const decrypted = await hipaa.decryptPHI(encrypted);
1108
+ const checks = [
1109
+ { name: 'mask-ssn', ok: masked.ssn !== phi.ssn, detail: String(masked.ssn) },
1110
+ { name: 'encrypt-roundtrip', ok: decrypted.ssn === phi.ssn, detail: String(decrypted.ssn) }
1111
+ ];
1112
+ return {
1113
+ summary: 'HIPAA masking/encryption complete',
1114
+ checks,
1115
+ metrics: {
1116
+ encryptedFields: encrypted._encrypted ? Object.keys(encrypted._encrypted).length : 0,
1117
+ maskedDob: String(masked.dob)
1118
+ }
1119
+ };
1120
+ });
1121
+ }
1122
+ async function runRealWorldOrchestrator(context) {
1123
+ return runToolAction('real-world-orchestrator', async () => {
1124
+ const service = context.oncologyService ?? createRealWorldOncologyService(context.serviceConfig);
1125
+ if (!context.oncologyService) {
1126
+ await service.initialize();
1127
+ }
1128
+ const plan = await service.generateComprehensivePlan(createSampleRealWorldPatient(), 'DR-001', {
1129
+ includeTrials: true,
1130
+ includePredictions: true,
1131
+ includeSafetyCheck: true
1132
+ });
1133
+ return {
1134
+ summary: `Plan ${plan.planId}`,
1135
+ metrics: {
1136
+ status: plan.coreRecommendation.status,
1137
+ cureConfidence: formatPercent(plan.coreRecommendation.projectedOutcome.cureConfidence),
1138
+ ehrSource: plan.ehrData?.source || 'none'
1139
+ }
1140
+ };
1141
+ });
1142
+ }
1143
+ async function runGenomicsAggregation() {
1144
+ return runToolAction('genomics-aggregation', async () => {
1145
+ const service = new UnifiedGenomicsService();
1146
+ const sampleResults = buildSampleGenomicResults(SAMPLE_PATIENT_ID);
1147
+ const mockClient = new MockGenomicClient({ platform: 'generic', apiBaseUrl: 'https://example.org' }, sampleResults);
1148
+ service.registerClient('mock', mockClient);
1149
+ const aggregated = await service.getAggregatedVariants(SAMPLE_PATIENT_ID);
1150
+ const matches = await service.matchToTherapies(SAMPLE_PATIENT_ID, SAMPLE_CANCER_TYPE);
1151
+ return {
1152
+ summary: `Aggregated ${aggregated.variants.length} variants`,
1153
+ metrics: {
1154
+ variants: aggregated.variants.length,
1155
+ cnvs: aggregated.cnvs.length,
1156
+ fusions: aggregated.fusions.length,
1157
+ therapyMatches: matches.length,
1158
+ tmbStatus: aggregated.biomarkers.tmb?.status || 'unknown'
1159
+ }
1160
+ };
1161
+ });
1162
+ }
1163
+ async function runEhrReadiness(context) {
1164
+ return runToolAction('ehr-readiness', async () => {
1165
+ const ehrConfig = context.serviceConfig?.ehr;
1166
+ const enabled = ehrConfig?.enabled ?? false;
1167
+ const baseUrl = process.env.FHIR_BASE_URL || ehrConfig?.baseUrl || '';
1168
+ const clientId = process.env.FHIR_CLIENT_ID || ehrConfig?.clientId || '';
1169
+ const clientSecret = process.env.FHIR_CLIENT_SECRET || '';
1170
+ const checks = [
1171
+ { name: 'ehr-enabled', ok: true, detail: enabled ? 'enabled' : 'disabled' },
1172
+ { name: 'FHIR_BASE_URL', ok: !enabled || Boolean(baseUrl), detail: baseUrl || 'missing' },
1173
+ { name: 'FHIR_CLIENT_ID', ok: !enabled || Boolean(clientId), detail: clientId ? 'set' : 'missing' },
1174
+ { name: 'FHIR_CLIENT_SECRET', ok: !enabled || Boolean(clientSecret), detail: clientSecret ? 'set' : 'missing' }
1175
+ ];
1176
+ return {
1177
+ summary: enabled ? 'EHR integration enabled' : 'EHR integration disabled',
1178
+ checks,
1179
+ metrics: {
1180
+ vendor: ehrConfig?.vendor || 'unknown'
1181
+ }
1182
+ };
1183
+ });
1184
+ }
1185
+ const CLI_TOOLS = [
1186
+ {
1187
+ id: 'selftest',
1188
+ description: 'Run core capability smoke tests',
1189
+ usage: '/tool selftest',
1190
+ run: (context) => runSelfTestSuite(context)
1191
+ },
1192
+ {
1193
+ id: 'validate',
1194
+ description: 'Run retrospective validation on a sample cohort',
1195
+ usage: '/tool validate',
1196
+ run: () => runValidationSample()
1197
+ },
1198
+ {
1199
+ id: 'cancer-core',
1200
+ description: 'Summarize cancer treatment core datasets',
1201
+ usage: '/tool cancer-core',
1202
+ run: (context) => runCancerCore(context)
1203
+ },
1204
+ {
1205
+ id: 'cancer-analyze',
1206
+ description: 'Run sample patient analysis',
1207
+ usage: '/tool cancer-analyze',
1208
+ run: (context) => runCancerAnalyze(context)
1209
+ },
1210
+ {
1211
+ id: 'cancer-plan',
1212
+ description: 'Generate sample treatment plan',
1213
+ usage: '/tool cancer-plan',
1214
+ run: (context) => runCancerPlan(context)
1215
+ },
1216
+ {
1217
+ id: 'cancer-cure',
1218
+ description: 'Generate sample cure protocol',
1219
+ usage: '/tool cancer-cure',
1220
+ run: (context) => runCancerCure(context)
1221
+ },
1222
+ {
1223
+ id: 'cancer-discover',
1224
+ description: 'Run sample drug target discovery',
1225
+ usage: '/tool cancer-discover',
1226
+ run: (context) => runCancerDiscover(context)
1227
+ },
1228
+ {
1229
+ id: 'universal-cure',
1230
+ description: 'Run universal cancer cure engine',
1231
+ usage: '/tool universal-cure',
1232
+ run: () => runUniversalCure()
1233
+ },
1234
+ {
1235
+ id: 'global-coverage',
1236
+ description: 'Summarize global guideline coverage',
1237
+ usage: '/tool global-coverage',
1238
+ run: () => runGlobalCoverage()
1239
+ },
1240
+ {
1241
+ id: 'treatment-sequencing',
1242
+ description: 'Recommend next-line therapy sequencing',
1243
+ usage: '/tool treatment-sequencing',
1244
+ run: () => runTreatmentSequencing()
1245
+ },
1246
+ {
1247
+ id: 'precision-medicine',
1248
+ description: 'Generate precision medicine report',
1249
+ usage: '/tool precision-medicine',
1250
+ run: () => runPrecisionMedicine()
1251
+ },
1252
+ {
1253
+ id: 'emerging-therapeutics',
1254
+ description: 'Summarize emerging therapy portfolio',
1255
+ usage: '/tool emerging-therapeutics',
1256
+ run: () => runEmergingTherapeutics()
1257
+ },
1258
+ {
1259
+ id: 'multimodal-oncology',
1260
+ description: 'Generate multimodal oncology sample output',
1261
+ usage: '/tool multimodal-oncology',
1262
+ run: () => runMultimodalOncology()
1263
+ },
1264
+ {
1265
+ id: 'special-populations',
1266
+ description: 'Run pediatric/geriatric special population checks',
1267
+ usage: '/tool special-populations',
1268
+ run: () => runSpecialPopulations()
1269
+ },
1270
+ {
1271
+ id: 'resistance-management',
1272
+ description: 'Analyze resistance and prevention plan',
1273
+ usage: '/tool resistance-management',
1274
+ run: () => runResistanceManagement()
1275
+ },
1276
+ {
1277
+ id: 'cure-verification',
1278
+ description: 'Verify cure status criteria',
1279
+ usage: '/tool cure-verification',
1280
+ run: () => runCureVerification()
1281
+ },
1282
+ {
1283
+ id: 'cure-validation',
1284
+ description: 'Validate coverage completeness',
1285
+ usage: '/tool cure-validation',
1286
+ run: () => runCureValidation()
1287
+ },
1288
+ {
1289
+ id: 'clinical-trial-matching',
1290
+ description: 'Match trials against sample profile',
1291
+ usage: '/tool clinical-trial-matching',
1292
+ run: () => runClinicalTrialMatching()
1293
+ },
1294
+ {
1295
+ id: 'palliative-care',
1296
+ description: 'Assess pain and opioid conversion',
1297
+ usage: '/tool palliative-care',
1298
+ run: () => runPalliativeCare()
1299
+ },
1300
+ {
1301
+ id: 'emergency-oncology',
1302
+ description: 'Identify potential oncology emergencies',
1303
+ usage: '/tool emergency-oncology',
1304
+ run: () => runEmergencyOncology()
1305
+ },
1306
+ {
1307
+ id: 'survivorship-care',
1308
+ description: 'Generate survivorship care plan',
1309
+ usage: '/tool survivorship-care',
1310
+ run: () => runSurvivorshipCare()
1311
+ },
1312
+ {
1313
+ id: 'universal-health',
1314
+ description: 'Generate general health plan',
1315
+ usage: '/tool universal-health',
1316
+ run: () => runUniversalHealth()
1317
+ },
1318
+ {
1319
+ id: 'clinical-decision-support',
1320
+ description: 'Generate clinician decision support output',
1321
+ usage: '/tool clinical-decision-support',
1322
+ run: () => runClinicalDecisionSupport()
1323
+ },
1324
+ {
1325
+ id: 'patient-portal',
1326
+ description: 'Create patient portal artifacts',
1327
+ usage: '/tool patient-portal',
1328
+ run: () => runPatientPortal()
1329
+ },
1330
+ {
1331
+ id: 'ml-outcome',
1332
+ description: 'Run ML outcome prediction',
1333
+ usage: '/tool ml-outcome',
1334
+ run: () => runMLOutcome()
1335
+ },
1336
+ {
1337
+ id: 'drug-safety',
1338
+ description: 'Run drug safety check',
1339
+ usage: '/tool drug-safety',
1340
+ run: () => runDrugSafety()
1341
+ },
1342
+ {
1343
+ id: 'hipaa-compliance',
1344
+ description: 'Run HIPAA masking and encryption checks',
1345
+ usage: '/tool hipaa-compliance',
1346
+ run: () => runHipaaCompliance()
1347
+ },
1348
+ {
1349
+ id: 'real-world-orchestrator',
1350
+ description: 'Generate comprehensive plan via orchestrator',
1351
+ usage: '/tool real-world-orchestrator',
1352
+ run: (context) => runRealWorldOrchestrator(context)
1353
+ },
1354
+ {
1355
+ id: 'genomics-aggregation',
1356
+ description: 'Aggregate genomics (mock platform)',
1357
+ usage: '/tool genomics-aggregation',
1358
+ run: () => runGenomicsAggregation()
1359
+ },
1360
+ {
1361
+ id: 'ehr-readiness',
1362
+ description: 'Check EHR integration readiness',
1363
+ usage: '/tool ehr-readiness',
1364
+ run: (context) => runEhrReadiness(context)
1365
+ },
1366
+ // ═══════════════════════════════════════════════════════════════════════════
1367
+ // COMPREHENSIVE HEALTH & WELLNESS TOOLS
1368
+ // ═══════════════════════════════════════════════════════════════════════════
1369
+ {
1370
+ id: 'preventive-screening',
1371
+ description: 'Age/gender-specific preventive health screening recommendations',
1372
+ usage: '/tool preventive-screening --age=50 --sex=female',
1373
+ run: () => runPreventiveScreening()
1374
+ },
1375
+ {
1376
+ id: 'cardiovascular-risk',
1377
+ description: 'Cardiovascular disease risk assessment (ASCVD, Framingham)',
1378
+ usage: '/tool cardiovascular-risk',
1379
+ run: () => runCardiovascularRisk()
1380
+ },
1381
+ {
1382
+ id: 'diabetes-management',
1383
+ description: 'Diabetes screening, management and monitoring',
1384
+ usage: '/tool diabetes-management',
1385
+ run: () => runDiabetesManagement()
1386
+ },
1387
+ {
1388
+ id: 'hypertension-management',
1389
+ description: 'Blood pressure management and treatment goals',
1390
+ usage: '/tool hypertension-management',
1391
+ run: () => runHypertensionManagement()
1392
+ },
1393
+ {
1394
+ id: 'mental-health-screening',
1395
+ description: 'Depression, anxiety, and mental health assessment',
1396
+ usage: '/tool mental-health-screening',
1397
+ run: () => runMentalHealthScreening()
1398
+ },
1399
+ {
1400
+ id: 'nutrition-assessment',
1401
+ description: 'Nutritional status and dietary recommendations',
1402
+ usage: '/tool nutrition-assessment',
1403
+ run: () => runNutritionAssessment()
1404
+ },
1405
+ {
1406
+ id: 'immunization-schedule',
1407
+ description: 'Vaccine recommendations by age and risk factors',
1408
+ usage: '/tool immunization-schedule --age=65',
1409
+ run: () => runImmunizationSchedule()
1410
+ },
1411
+ {
1412
+ id: 'bone-health',
1413
+ description: 'Osteoporosis screening and bone health assessment',
1414
+ usage: '/tool bone-health',
1415
+ run: () => runBoneHealth()
1416
+ },
1417
+ {
1418
+ id: 'cognitive-screening',
1419
+ description: 'Cognitive health and dementia risk assessment',
1420
+ usage: '/tool cognitive-screening',
1421
+ run: () => runCognitiveScreening()
1422
+ },
1423
+ {
1424
+ id: 'sleep-assessment',
1425
+ description: 'Sleep disorders screening and recommendations',
1426
+ usage: '/tool sleep-assessment',
1427
+ run: () => runSleepAssessment()
1428
+ },
1429
+ {
1430
+ id: 'substance-screening',
1431
+ description: 'Alcohol, tobacco, and substance use screening',
1432
+ usage: '/tool substance-screening',
1433
+ run: () => runSubstanceScreening()
1434
+ },
1435
+ {
1436
+ id: 'kidney-health',
1437
+ description: 'Chronic kidney disease screening and staging',
1438
+ usage: '/tool kidney-health',
1439
+ run: () => runKidneyHealth()
1440
+ },
1441
+ {
1442
+ id: 'liver-health',
1443
+ description: 'Liver disease screening and hepatitis assessment',
1444
+ usage: '/tool liver-health',
1445
+ run: () => runLiverHealth()
1446
+ },
1447
+ {
1448
+ id: 'respiratory-health',
1449
+ description: 'Pulmonary function and COPD/asthma assessment',
1450
+ usage: '/tool respiratory-health',
1451
+ run: () => runRespiratoryHealth()
1452
+ },
1453
+ {
1454
+ id: 'thyroid-screening',
1455
+ description: 'Thyroid function screening and disorders',
1456
+ usage: '/tool thyroid-screening',
1457
+ run: () => runThyroidScreening()
1458
+ },
1459
+ {
1460
+ id: 'sexual-health',
1461
+ description: 'Sexual and reproductive health screening',
1462
+ usage: '/tool sexual-health',
1463
+ run: () => runSexualHealth()
1464
+ },
1465
+ {
1466
+ id: 'infectious-disease',
1467
+ description: 'Infectious disease screening (HIV, Hepatitis, STIs)',
1468
+ usage: '/tool infectious-disease',
1469
+ run: () => runInfectiousDisease()
1470
+ },
1471
+ {
1472
+ id: 'autoimmune-screening',
1473
+ description: 'Autoimmune disease markers and assessment',
1474
+ usage: '/tool autoimmune-screening',
1475
+ run: () => runAutoimmuneScreening()
1476
+ },
1477
+ {
1478
+ id: 'allergy-assessment',
1479
+ description: 'Allergy testing and management recommendations',
1480
+ usage: '/tool allergy-assessment',
1481
+ run: () => runAllergyAssessment()
1482
+ },
1483
+ {
1484
+ id: 'pain-management',
1485
+ description: 'Chronic pain assessment and treatment options',
1486
+ usage: '/tool pain-management',
1487
+ run: () => runPainManagement()
1488
+ },
1489
+ {
1490
+ id: 'exercise-prescription',
1491
+ description: 'Exercise recommendations based on health status',
1492
+ usage: '/tool exercise-prescription',
1493
+ run: () => runExercisePrescription()
1494
+ },
1495
+ {
1496
+ id: 'weight-management',
1497
+ description: 'Weight assessment and obesity management',
1498
+ usage: '/tool weight-management',
1499
+ run: () => runWeightManagement()
1500
+ },
1501
+ {
1502
+ id: 'stress-management',
1503
+ description: 'Stress assessment and coping strategies',
1504
+ usage: '/tool stress-management',
1505
+ run: () => runStressManagement()
1506
+ },
1507
+ {
1508
+ id: 'vision-screening',
1509
+ description: 'Eye health and vision screening recommendations',
1510
+ usage: '/tool vision-screening',
1511
+ run: () => runVisionScreening()
1512
+ },
1513
+ {
1514
+ id: 'hearing-screening',
1515
+ description: 'Hearing assessment and audiological care',
1516
+ usage: '/tool hearing-screening',
1517
+ run: () => runHearingScreening()
1518
+ },
1519
+ {
1520
+ id: 'dental-health',
1521
+ description: 'Oral health assessment and dental care',
1522
+ usage: '/tool dental-health',
1523
+ run: () => runDentalHealth()
1524
+ },
1525
+ {
1526
+ id: 'skin-health',
1527
+ description: 'Dermatological screening and skin cancer prevention',
1528
+ usage: '/tool skin-health',
1529
+ run: () => runSkinHealth()
1530
+ },
1531
+ {
1532
+ id: 'genetic-risk',
1533
+ description: 'Genetic risk assessment for hereditary conditions',
1534
+ usage: '/tool genetic-risk',
1535
+ run: () => runGeneticRisk()
1536
+ },
1537
+ {
1538
+ id: 'medication-review',
1539
+ description: 'Polypharmacy review and medication optimization',
1540
+ usage: '/tool medication-review',
1541
+ run: () => runMedicationReview()
1542
+ },
1543
+ {
1544
+ id: 'fall-risk',
1545
+ description: 'Fall risk assessment for elderly patients',
1546
+ usage: '/tool fall-risk',
1547
+ run: () => runFallRisk()
1548
+ },
1549
+ {
1550
+ id: 'functional-status',
1551
+ description: 'Activities of daily living and functional assessment',
1552
+ usage: '/tool functional-status',
1553
+ run: () => runFunctionalStatus()
1554
+ },
1555
+ {
1556
+ id: 'pediatric-wellness',
1557
+ description: 'Pediatric developmental milestones and wellness',
1558
+ usage: '/tool pediatric-wellness',
1559
+ run: () => runPediatricWellness()
1560
+ },
1561
+ {
1562
+ id: 'prenatal-care',
1563
+ description: 'Prenatal screening and pregnancy care',
1564
+ usage: '/tool prenatal-care',
1565
+ run: () => runPrenatalCare()
1566
+ },
1567
+ {
1568
+ id: 'menopause-management',
1569
+ description: 'Menopause symptom management and HRT assessment',
1570
+ usage: '/tool menopause-management',
1571
+ run: () => runMenopauseManagement()
1572
+ },
1573
+ {
1574
+ id: 'prostate-health',
1575
+ description: 'Prostate health screening and BPH management',
1576
+ usage: '/tool prostate-health',
1577
+ run: () => runProstateHealth()
1578
+ },
1579
+ {
1580
+ id: 'travel-health',
1581
+ description: 'Travel medicine and vaccination requirements',
1582
+ usage: '/tool travel-health --destination=Africa',
1583
+ run: () => runTravelHealth()
1584
+ },
1585
+ {
1586
+ id: 'occupational-health',
1587
+ description: 'Workplace health hazards and screening',
1588
+ usage: '/tool occupational-health',
1589
+ run: () => runOccupationalHealth()
1590
+ },
1591
+ {
1592
+ id: 'environmental-health',
1593
+ description: 'Environmental exposure risks and mitigation',
1594
+ usage: '/tool environmental-health',
1595
+ run: () => runEnvironmentalHealth()
1596
+ },
1597
+ {
1598
+ id: 'longevity-assessment',
1599
+ description: 'Longevity factors and healthy aging strategies',
1600
+ usage: '/tool longevity-assessment',
1601
+ run: () => runLongevityAssessment()
1602
+ },
1603
+ {
1604
+ id: 'health-optimization',
1605
+ description: 'Comprehensive health optimization recommendations',
1606
+ usage: '/tool health-optimization',
1607
+ run: () => runHealthOptimization()
1608
+ },
1609
+ {
1610
+ id: 'all',
1611
+ description: 'Run all diagnostic tools',
1612
+ usage: '/tool all',
1613
+ run: (context) => runAllTools(context)
1614
+ }
1615
+ ];
1616
+ // ═══════════════════════════════════════════════════════════════════════════════
1617
+ // COMPREHENSIVE HEALTH TOOL IMPLEMENTATIONS
1618
+ // ═══════════════════════════════════════════════════════════════════════════════
1619
+ async function runPreventiveScreening() {
1620
+ return runToolAction('preventive-screening', async () => {
1621
+ const screenings = [
1622
+ { test: 'Blood pressure', frequency: 'Annually', ages: '18+' },
1623
+ { test: 'Lipid panel', frequency: 'Every 5 years', ages: '20+, more frequent if elevated' },
1624
+ { test: 'Blood glucose/HbA1c', frequency: 'Every 3 years', ages: '45+ or with risk factors' },
1625
+ { test: 'Colorectal cancer screening', frequency: 'Every 10 years colonoscopy', ages: '45-75' },
1626
+ { test: 'Mammography', frequency: 'Every 1-2 years', ages: 'Women 40+' },
1627
+ { test: 'Cervical cancer (Pap/HPV)', frequency: 'Every 3-5 years', ages: 'Women 21-65' },
1628
+ { test: 'Lung cancer (LDCT)', frequency: 'Annually', ages: '50-80 with 20+ pack-year history' },
1629
+ { test: 'Prostate cancer (PSA)', frequency: 'Discuss with provider', ages: 'Men 50+' },
1630
+ { test: 'Osteoporosis (DEXA)', frequency: 'Every 2 years', ages: 'Women 65+, Men 70+' },
1631
+ { test: 'AAA ultrasound', frequency: 'Once', ages: 'Men 65-75 who ever smoked' },
1632
+ { test: 'Hepatitis C', frequency: 'Once', ages: 'All adults 18-79' },
1633
+ { test: 'HIV', frequency: 'At least once', ages: 'All adults 15-65' },
1634
+ { test: 'Depression screening', frequency: 'Annually', ages: 'All adults' },
1635
+ { test: 'Skin cancer exam', frequency: 'Annually', ages: 'All adults' },
1636
+ { test: 'Dental exam', frequency: 'Every 6-12 months', ages: 'All ages' },
1637
+ { test: 'Eye exam', frequency: 'Every 1-2 years', ages: '40+' }
1638
+ ];
1639
+ const checks = screenings.map(s => ({
1640
+ name: s.test,
1641
+ ok: true,
1642
+ detail: `${s.frequency} (Ages: ${s.ages})`
1643
+ }));
1644
+ return {
1645
+ summary: `${screenings.length} preventive screenings recommended`,
1646
+ checks,
1647
+ metrics: {
1648
+ totalScreenings: screenings.length,
1649
+ cancerScreenings: 5,
1650
+ cardioMetabolicScreenings: 3,
1651
+ infectiousScreenings: 2
1652
+ }
1653
+ };
1654
+ });
1655
+ }
1656
+ async function runCardiovascularRisk() {
1657
+ return runToolAction('cardiovascular-risk', async () => {
1658
+ // Sample patient for demo
1659
+ const riskFactors = {
1660
+ age: 55,
1661
+ sex: 'male',
1662
+ totalCholesterol: 220,
1663
+ hdl: 45,
1664
+ systolicBP: 140,
1665
+ onBPMeds: false,
1666
+ diabetic: false,
1667
+ smoker: false
1668
+ };
1669
+ // Simplified ASCVD risk calculation
1670
+ let risk = 0.05; // base risk
1671
+ if (riskFactors.age > 50)
1672
+ risk += 0.02;
1673
+ if (riskFactors.totalCholesterol > 200)
1674
+ risk += 0.03;
1675
+ if (riskFactors.hdl < 50)
1676
+ risk += 0.02;
1677
+ if (riskFactors.systolicBP > 130)
1678
+ risk += 0.03;
1679
+ if (riskFactors.smoker)
1680
+ risk += 0.05;
1681
+ if (riskFactors.diabetic)
1682
+ risk += 0.04;
1683
+ const riskCategory = risk < 0.075 ? 'Low' : risk < 0.2 ? 'Intermediate' : 'High';
1684
+ const checks = [
1685
+ { name: 'Total cholesterol', ok: riskFactors.totalCholesterol < 200, detail: `${riskFactors.totalCholesterol} mg/dL` },
1686
+ { name: 'HDL cholesterol', ok: riskFactors.hdl >= 40, detail: `${riskFactors.hdl} mg/dL` },
1687
+ { name: 'Blood pressure', ok: riskFactors.systolicBP < 130, detail: `${riskFactors.systolicBP} mmHg` },
1688
+ { name: 'Smoking status', ok: !riskFactors.smoker, detail: riskFactors.smoker ? 'Current smoker' : 'Non-smoker' },
1689
+ { name: 'Diabetes status', ok: !riskFactors.diabetic, detail: riskFactors.diabetic ? 'Diabetic' : 'Non-diabetic' }
1690
+ ];
1691
+ return {
1692
+ summary: `10-year ASCVD risk: ${formatPercent(risk)} (${riskCategory})`,
1693
+ checks,
1694
+ metrics: {
1695
+ tenYearRisk: formatPercent(risk),
1696
+ riskCategory,
1697
+ statinRecommended: risk >= 0.075 ? 'Yes' : 'Consider if borderline',
1698
+ aspirinRecommended: risk >= 0.1 && riskFactors.age >= 50 ? 'Discuss' : 'Not indicated'
1699
+ }
1700
+ };
1701
+ });
1702
+ }
1703
+ async function runDiabetesManagement() {
1704
+ return runToolAction('diabetes-management', async () => {
1705
+ const targets = [
1706
+ { metric: 'HbA1c', target: '< 7.0%', rationale: 'Reduces microvascular complications' },
1707
+ { metric: 'Fasting glucose', target: '80-130 mg/dL', rationale: 'Pre-meal target' },
1708
+ { metric: 'Post-meal glucose', target: '< 180 mg/dL', rationale: '1-2 hours after eating' },
1709
+ { metric: 'Blood pressure', target: '< 130/80 mmHg', rationale: 'CV risk reduction' },
1710
+ { metric: 'LDL cholesterol', target: '< 100 mg/dL', rationale: 'High-intensity statin for most' },
1711
+ { metric: 'Triglycerides', target: '< 150 mg/dL', rationale: 'CV risk marker' }
1712
+ ];
1713
+ const monitoring = [
1714
+ { test: 'HbA1c', frequency: 'Every 3 months if not at goal, else every 6 months' },
1715
+ { test: 'Lipid panel', frequency: 'Annually' },
1716
+ { test: 'Kidney function (eGFR, UACR)', frequency: 'Annually' },
1717
+ { test: 'Dilated eye exam', frequency: 'Annually' },
1718
+ { test: 'Foot exam', frequency: 'Every visit' },
1719
+ { test: 'Dental exam', frequency: 'Every 6 months' }
1720
+ ];
1721
+ const checks = [
1722
+ ...targets.map(t => ({ name: t.metric, ok: true, detail: `Target: ${t.target}` })),
1723
+ ...monitoring.map(m => ({ name: `${m.test} monitoring`, ok: true, detail: m.frequency }))
1724
+ ];
1725
+ return {
1726
+ summary: `${targets.length} targets, ${monitoring.length} monitoring items`,
1727
+ checks,
1728
+ metrics: {
1729
+ glycemicTargets: targets.length,
1730
+ monitoringItems: monitoring.length,
1731
+ medicationClasses: 'Metformin, SGLT2i, GLP-1 RA, DPP-4i, Insulin'
1732
+ }
1733
+ };
1734
+ });
1735
+ }
1736
+ async function runHypertensionManagement() {
1737
+ return runToolAction('hypertension-management', async () => {
1738
+ const categories = [
1739
+ { category: 'Normal', systolic: '< 120', diastolic: '< 80', action: 'Reassess in 1 year' },
1740
+ { category: 'Elevated', systolic: '120-129', diastolic: '< 80', action: 'Lifestyle modification' },
1741
+ { category: 'Stage 1 HTN', systolic: '130-139', diastolic: '80-89', action: 'Lifestyle + consider meds if high CV risk' },
1742
+ { category: 'Stage 2 HTN', systolic: '≥ 140', diastolic: '≥ 90', action: 'Lifestyle + medication' },
1743
+ { category: 'Hypertensive crisis', systolic: '> 180', diastolic: '> 120', action: 'Immediate evaluation' }
1744
+ ];
1745
+ const medications = [
1746
+ { class: 'ACE inhibitors', examples: 'Lisinopril, Enalapril', notes: 'First-line, especially for DM/CKD' },
1747
+ { class: 'ARBs', examples: 'Losartan, Valsartan', notes: 'Alternative to ACEi' },
1748
+ { class: 'Calcium channel blockers', examples: 'Amlodipine, Diltiazem', notes: 'First-line option' },
1749
+ { class: 'Thiazide diuretics', examples: 'HCTZ, Chlorthalidone', notes: 'First-line option' },
1750
+ { class: 'Beta blockers', examples: 'Metoprolol, Carvedilol', notes: 'For CAD, HF, or arrhythmia' }
1751
+ ];
1752
+ const checks = [
1753
+ ...categories.map(c => ({ name: c.category, ok: true, detail: `${c.systolic}/${c.diastolic} mmHg - ${c.action}` })),
1754
+ ...medications.map(m => ({ name: m.class, ok: true, detail: `${m.examples}` }))
1755
+ ];
1756
+ return {
1757
+ summary: `${categories.length} BP categories, ${medications.length} medication classes`,
1758
+ checks,
1759
+ metrics: {
1760
+ targetBP: '< 130/80 mmHg for most',
1761
+ elderlyTarget: '< 140/90 mmHg if > 65',
1762
+ lifestyleFactors: 'DASH diet, sodium < 2300mg, exercise, weight loss, limit alcohol'
1763
+ }
1764
+ };
1765
+ });
1766
+ }
1767
+ async function runMentalHealthScreening() {
1768
+ return runToolAction('mental-health-screening', async () => {
1769
+ const screeningTools = [
1770
+ { tool: 'PHQ-9', condition: 'Depression', cutoff: '≥ 10 moderate, ≥ 15 severe' },
1771
+ { tool: 'GAD-7', condition: 'Anxiety', cutoff: '≥ 10 moderate, ≥ 15 severe' },
1772
+ { tool: 'PHQ-2', condition: 'Depression (brief)', cutoff: '≥ 3 warrants PHQ-9' },
1773
+ { tool: 'AUDIT-C', condition: 'Alcohol use', cutoff: '≥ 4 men, ≥ 3 women' },
1774
+ { tool: 'Columbia Suicide Severity', condition: 'Suicide risk', cutoff: 'Any positive requires assessment' },
1775
+ { tool: 'MDQ', condition: 'Bipolar disorder', cutoff: '≥ 7 with impairment' },
1776
+ { tool: 'PC-PTSD-5', condition: 'PTSD', cutoff: '≥ 3 positive responses' },
1777
+ { tool: 'Edinburgh Postnatal', condition: 'Postpartum depression', cutoff: '≥ 10' }
1778
+ ];
1779
+ const resources = [
1780
+ { type: 'Crisis', resource: '988 Suicide & Crisis Lifeline', access: 'Call or text 988' },
1781
+ { type: 'Crisis', resource: 'Crisis Text Line', access: 'Text HOME to 741741' },
1782
+ { type: 'Therapy', resource: 'CBT (Cognitive Behavioral)', access: 'Evidence-based first-line' },
1783
+ { type: 'Therapy', resource: 'DBT (Dialectical Behavioral)', access: 'For BPD, self-harm' },
1784
+ { type: 'Medication', resource: 'SSRIs', access: 'First-line for depression/anxiety' },
1785
+ { type: 'Medication', resource: 'SNRIs', access: 'Alternative first-line' }
1786
+ ];
1787
+ const checks = screeningTools.map(s => ({
1788
+ name: s.tool,
1789
+ ok: true,
1790
+ detail: `${s.condition}: ${s.cutoff}`
1791
+ }));
1792
+ return {
1793
+ summary: `${screeningTools.length} screening tools, ${resources.length} resources`,
1794
+ checks,
1795
+ metrics: {
1796
+ screeningTools: screeningTools.length,
1797
+ crisisResources: 2,
1798
+ therapyTypes: 2,
1799
+ medicationClasses: 2
1800
+ }
1801
+ };
1802
+ });
1803
+ }
1804
+ async function runNutritionAssessment() {
1805
+ return runToolAction('nutrition-assessment', async () => {
1806
+ const macronutrients = [
1807
+ { nutrient: 'Protein', recommendation: '0.8-1.2 g/kg body weight', notes: 'Higher for elderly, athletes' },
1808
+ { nutrient: 'Carbohydrates', recommendation: '45-65% of calories', notes: 'Focus on complex carbs, fiber' },
1809
+ { nutrient: 'Fat', recommendation: '20-35% of calories', notes: 'Limit saturated < 10%' },
1810
+ { nutrient: 'Fiber', recommendation: '25-38 g/day', notes: 'Most adults fall short' },
1811
+ { nutrient: 'Water', recommendation: '8-10 cups/day', notes: 'More with activity, heat' }
1812
+ ];
1813
+ const micronutrients = [
1814
+ { nutrient: 'Vitamin D', recommendation: '600-800 IU/day', risk: 'Deficiency common, especially in northern latitudes' },
1815
+ { nutrient: 'Vitamin B12', recommendation: '2.4 mcg/day', risk: 'Screen elderly, vegans, on metformin' },
1816
+ { nutrient: 'Iron', recommendation: '8-18 mg/day', risk: 'Menstruating women at higher risk' },
1817
+ { nutrient: 'Calcium', recommendation: '1000-1200 mg/day', risk: 'Bone health, especially postmenopausal women' },
1818
+ { nutrient: 'Omega-3', recommendation: '250-500 mg EPA+DHA', risk: 'CV benefit' },
1819
+ { nutrient: 'Folate', recommendation: '400 mcg/day', risk: '600 mcg if pregnant' }
1820
+ ];
1821
+ const checks = [
1822
+ ...macronutrients.map(m => ({ name: m.nutrient, ok: true, detail: m.recommendation })),
1823
+ ...micronutrients.map(m => ({ name: m.nutrient, ok: true, detail: m.recommendation }))
1824
+ ];
1825
+ return {
1826
+ summary: `${macronutrients.length + micronutrients.length} nutritional targets`,
1827
+ checks,
1828
+ metrics: {
1829
+ macronutrients: macronutrients.length,
1830
+ micronutrients: micronutrients.length,
1831
+ dietPatterns: 'Mediterranean, DASH, MIND recommended'
1832
+ }
1833
+ };
1834
+ });
1835
+ }
1836
+ async function runImmunizationSchedule() {
1837
+ return runToolAction('immunization-schedule', async () => {
1838
+ const adultVaccines = [
1839
+ { vaccine: 'Influenza', schedule: 'Annually', ages: 'All adults' },
1840
+ { vaccine: 'COVID-19', schedule: 'Per current guidance', ages: 'All adults' },
1841
+ { vaccine: 'Tdap/Td', schedule: 'Tdap once, Td every 10 years', ages: 'All adults' },
1842
+ { vaccine: 'Shingles (Shingrix)', schedule: '2 doses', ages: '50+' },
1843
+ { vaccine: 'Pneumococcal (PCV20 or PCV15+PPSV23)', schedule: '1-2 doses', ages: '65+ or high-risk' },
1844
+ { vaccine: 'RSV', schedule: '1 dose', ages: '60+' },
1845
+ { vaccine: 'HPV', schedule: '2-3 doses', ages: 'Through age 26 (catch-up to 45)' },
1846
+ { vaccine: 'Hepatitis B', schedule: '2-3 doses', ages: 'All adults < 60, high-risk 60+' },
1847
+ { vaccine: 'Hepatitis A', schedule: '2 doses', ages: 'High-risk groups' },
1848
+ { vaccine: 'MMR', schedule: '1-2 doses if no immunity', ages: 'Adults born after 1957' },
1849
+ { vaccine: 'Varicella', schedule: '2 doses if no immunity', ages: 'Adults without immunity' },
1850
+ { vaccine: 'Meningococcal', schedule: 'High-risk groups', ages: 'College freshmen, asplenia, complement deficiency' }
1851
+ ];
1852
+ const travelVaccines = [
1853
+ { vaccine: 'Yellow Fever', regions: 'Africa, South America' },
1854
+ { vaccine: 'Typhoid', regions: 'South Asia, developing countries' },
1855
+ { vaccine: 'Japanese Encephalitis', regions: 'Asia' },
1856
+ { vaccine: 'Rabies', regions: 'Pre-exposure for high-risk travel' },
1857
+ { vaccine: 'Cholera', regions: 'Endemic areas' }
1858
+ ];
1859
+ const checks = adultVaccines.map(v => ({
1860
+ name: v.vaccine,
1861
+ ok: true,
1862
+ detail: `${v.schedule} - ${v.ages}`
1863
+ }));
1864
+ return {
1865
+ summary: `${adultVaccines.length} routine vaccines, ${travelVaccines.length} travel vaccines`,
1866
+ checks,
1867
+ metrics: {
1868
+ routineVaccines: adultVaccines.length,
1869
+ travelVaccines: travelVaccines.length,
1870
+ annualVaccines: 'Influenza, COVID-19 (as recommended)'
1871
+ }
1872
+ };
1873
+ });
1874
+ }
1875
+ async function runBoneHealth() {
1876
+ return runToolAction('bone-health', async () => {
1877
+ const riskFactors = [
1878
+ { factor: 'Age > 65 (women) or > 70 (men)', weight: 'Major' },
1879
+ { factor: 'Prior fragility fracture', weight: 'Major' },
1880
+ { factor: 'Parental hip fracture', weight: 'Moderate' },
1881
+ { factor: 'Low body weight (< 127 lbs)', weight: 'Moderate' },
1882
+ { factor: 'Smoking', weight: 'Moderate' },
1883
+ { factor: 'Excess alcohol (> 3 drinks/day)', weight: 'Moderate' },
1884
+ { factor: 'Glucocorticoid use', weight: 'Major' },
1885
+ { factor: 'Rheumatoid arthritis', weight: 'Moderate' },
1886
+ { factor: 'Secondary osteoporosis causes', weight: 'Variable' }
1887
+ ];
1888
+ const tscore = [
1889
+ { category: 'Normal', range: 'T-score ≥ -1.0', action: 'Reassess per guidelines' },
1890
+ { category: 'Osteopenia', range: 'T-score -1.0 to -2.5', action: 'Lifestyle, consider FRAX' },
1891
+ { category: 'Osteoporosis', range: 'T-score ≤ -2.5', action: 'Treatment indicated' },
1892
+ { category: 'Severe osteoporosis', range: 'T-score ≤ -2.5 + fracture', action: 'Aggressive treatment' }
1893
+ ];
1894
+ const treatments = [
1895
+ { class: 'Bisphosphonates', drugs: 'Alendronate, Risedronate, Zoledronic acid', notes: 'First-line' },
1896
+ { class: 'RANK-L inhibitor', drugs: 'Denosumab', notes: 'Alternative first-line' },
1897
+ { class: 'Anabolic', drugs: 'Teriparatide, Abaloparatide, Romosozumab', notes: 'For severe or refractory' },
1898
+ { class: 'SERM', drugs: 'Raloxifene', notes: 'Postmenopausal, also reduces breast cancer risk' }
1899
+ ];
1900
+ const checks = [
1901
+ ...tscore.map(t => ({ name: t.category, ok: true, detail: `${t.range}: ${t.action}` })),
1902
+ ...treatments.map(t => ({ name: t.class, ok: true, detail: t.drugs }))
1903
+ ];
1904
+ return {
1905
+ summary: `${riskFactors.length} risk factors, ${treatments.length} treatment classes`,
1906
+ checks,
1907
+ metrics: {
1908
+ screeningAge: 'Women 65+, Men 70+, earlier if risk factors',
1909
+ calciumTarget: '1000-1200 mg/day',
1910
+ vitaminDTarget: '800-1000 IU/day',
1911
+ exerciseRecommendation: 'Weight-bearing + resistance training'
1912
+ }
1913
+ };
1914
+ });
1915
+ }
1916
+ async function runCognitiveScreening() {
1917
+ return runToolAction('cognitive-screening', async () => {
1918
+ const screeningTools = [
1919
+ { tool: 'Mini-Cog', time: '3 min', components: '3-word recall + clock draw' },
1920
+ { tool: 'MMSE', time: '10 min', components: '30-point scale, < 24 abnormal' },
1921
+ { tool: 'MoCA', time: '10 min', components: '30-point scale, < 26 abnormal' },
1922
+ { tool: 'SLUMS', time: '7 min', components: '30-point scale' },
1923
+ { tool: 'AD8', time: '3 min', components: 'Informant questionnaire' }
1924
+ ];
1925
+ const dementiaTypes = [
1926
+ { type: 'Alzheimer disease', percentage: '60-80%', features: 'Memory loss, gradual onset' },
1927
+ { type: 'Vascular dementia', percentage: '10-20%', features: 'Step-wise decline, CV risk factors' },
1928
+ { type: 'Lewy body dementia', percentage: '5-10%', features: 'Visual hallucinations, parkinsonism' },
1929
+ { type: 'Frontotemporal', percentage: '5-10%', features: 'Behavior/language changes, younger onset' },
1930
+ { type: 'Mixed dementia', percentage: 'Common', features: 'AD + vascular most common' }
1931
+ ];
1932
+ const modifiableRisk = [
1933
+ 'Hypertension', 'Diabetes', 'Obesity', 'Smoking', 'Depression',
1934
+ 'Physical inactivity', 'Social isolation', 'Hearing loss', 'Excessive alcohol'
1935
+ ];
1936
+ const checks = [
1937
+ ...screeningTools.map(s => ({ name: s.tool, ok: true, detail: `${s.time}: ${s.components}` })),
1938
+ ...dementiaTypes.map(d => ({ name: d.type, ok: true, detail: `${d.percentage}: ${d.features}` }))
1939
+ ];
1940
+ return {
1941
+ summary: `${screeningTools.length} screening tools, ${dementiaTypes.length} dementia types`,
1942
+ checks,
1943
+ metrics: {
1944
+ modifiableRiskFactors: modifiableRisk.length,
1945
+ riskReduction: 'Up to 40% of dementia potentially preventable',
1946
+ medications: 'Cholinesterase inhibitors, Memantine, Lecanemab (amyloid-targeting)'
1947
+ }
1948
+ };
1949
+ });
1950
+ }
1951
+ async function runSleepAssessment() {
1952
+ return runToolAction('sleep-assessment', async () => {
1953
+ const disorders = [
1954
+ { disorder: 'Obstructive Sleep Apnea', prevalence: '10-30%', screening: 'STOP-BANG questionnaire' },
1955
+ { disorder: 'Insomnia', prevalence: '10-15%', screening: 'Insomnia Severity Index' },
1956
+ { disorder: 'Restless Legs Syndrome', prevalence: '5-15%', screening: 'Clinical criteria' },
1957
+ { disorder: 'Circadian Rhythm Disorders', prevalence: 'Variable', screening: 'Sleep diary, actigraphy' },
1958
+ { disorder: 'Narcolepsy', prevalence: '0.02-0.05%', screening: 'Epworth Sleepiness Scale' }
1959
+ ];
1960
+ const hygiene = [
1961
+ 'Consistent sleep/wake times (even weekends)',
1962
+ 'Bedroom: dark, quiet, cool (65-68°F)',
1963
+ 'Avoid screens 1 hour before bed',
1964
+ 'Limit caffeine after noon',
1965
+ 'Avoid alcohol close to bedtime',
1966
+ 'Regular exercise (but not close to bedtime)',
1967
+ 'Avoid large meals before bed'
1968
+ ];
1969
+ const checks = [
1970
+ ...disorders.map(d => ({ name: d.disorder, ok: true, detail: `${d.prevalence}: ${d.screening}` })),
1971
+ { name: 'Sleep hygiene', ok: true, detail: `${hygiene.length} recommendations` }
1972
+ ];
1973
+ return {
1974
+ summary: `${disorders.length} sleep disorders, ${hygiene.length} hygiene tips`,
1975
+ checks,
1976
+ metrics: {
1977
+ recommendedSleep: '7-9 hours for adults',
1978
+ osaTreatment: 'CPAP, oral appliances, weight loss, surgery',
1979
+ insomniaTreatment: 'CBT-I first-line, short-term medications if needed'
1980
+ }
1981
+ };
1982
+ });
1983
+ }
1984
+ async function runSubstanceScreening() {
1985
+ return runToolAction('substance-screening', async () => {
1986
+ const screeningTools = [
1987
+ { tool: 'AUDIT', substance: 'Alcohol', description: '10 questions, ≥ 8 hazardous use' },
1988
+ { tool: 'AUDIT-C', substance: 'Alcohol (brief)', description: '3 questions, ≥ 4 men / ≥ 3 women' },
1989
+ { tool: 'CAGE', substance: 'Alcohol', description: '4 questions, ≥ 2 suggests problem' },
1990
+ { tool: 'DAST-10', substance: 'Drugs', description: '10 questions, ≥ 3 moderate problem' },
1991
+ { tool: 'NIDA Quick Screen', substance: 'All substances', description: 'Single question each' },
1992
+ { tool: 'Fagerström', substance: 'Nicotine', description: 'Nicotine dependence severity' }
1993
+ ];
1994
+ const interventions = [
1995
+ { level: 'Brief intervention', description: 'FRAMES: Feedback, Responsibility, Advice, Menu, Empathy, Self-efficacy' },
1996
+ { level: 'Motivational interviewing', description: 'Patient-centered, explore ambivalence' },
1997
+ { level: 'Behavioral therapy', description: 'CBT, contingency management' },
1998
+ { level: 'Medication-assisted treatment', description: 'Naltrexone, buprenorphine, methadone for OUD' },
1999
+ { level: 'Smoking cessation', description: 'NRT, varenicline, bupropion + counseling' }
2000
+ ];
2001
+ const checks = [
2002
+ ...screeningTools.map(s => ({ name: s.tool, ok: true, detail: `${s.substance}: ${s.description}` })),
2003
+ ...interventions.map(i => ({ name: i.level, ok: true, detail: i.description }))
2004
+ ];
2005
+ return {
2006
+ summary: `${screeningTools.length} screening tools, ${interventions.length} intervention levels`,
2007
+ checks,
2008
+ metrics: {
2009
+ safeAlcoholLimits: 'Men ≤ 2 drinks/day, Women ≤ 1 drink/day',
2010
+ smokingQuitlineNumber: '1-800-QUIT-NOW',
2011
+ overdoseReversal: 'Naloxone (Narcan) - prescribe to at-risk patients'
2012
+ }
2013
+ };
2014
+ });
2015
+ }
2016
+ async function runKidneyHealth() {
2017
+ return runToolAction('kidney-health', async () => {
2018
+ const ckdStages = [
2019
+ { stage: 'G1', gfr: '≥ 90', description: 'Normal or high', action: 'Monitor if albuminuria' },
2020
+ { stage: 'G2', gfr: '60-89', description: 'Mildly decreased', action: 'Monitor, control risk factors' },
2021
+ { stage: 'G3a', gfr: '45-59', description: 'Mild-moderate decrease', action: 'Nephrology referral, adjust meds' },
2022
+ { stage: 'G3b', gfr: '30-44', description: 'Moderate-severe decrease', action: 'Nephrology, prepare for RRT' },
2023
+ { stage: 'G4', gfr: '15-29', description: 'Severely decreased', action: 'RRT planning' },
2024
+ { stage: 'G5', gfr: '< 15', description: 'Kidney failure', action: 'Dialysis or transplant' }
2025
+ ];
2026
+ const albuminuria = [
2027
+ { category: 'A1', level: '< 30 mg/g', description: 'Normal to mildly increased' },
2028
+ { category: 'A2', level: '30-300 mg/g', description: 'Moderately increased' },
2029
+ { category: 'A3', level: '> 300 mg/g', description: 'Severely increased' }
2030
+ ];
2031
+ const checks = [
2032
+ ...ckdStages.map(s => ({ name: `Stage ${s.stage}`, ok: true, detail: `GFR ${s.gfr}: ${s.description}` })),
2033
+ ...albuminuria.map(a => ({ name: `Albuminuria ${a.category}`, ok: true, detail: `${a.level}: ${a.description}` }))
2034
+ ];
2035
+ return {
2036
+ summary: `${ckdStages.length} CKD stages, ${albuminuria.length} albuminuria categories`,
2037
+ checks,
2038
+ metrics: {
2039
+ screeningIndications: 'Diabetes, HTN, CVD, family history, AKI',
2040
+ nephroprotection: 'ACEi/ARB, SGLT2i for proteinuria',
2041
+ avoidNSAIDs: 'Yes, especially in advanced CKD',
2042
+ contrastPrecautions: 'Hydration, minimize contrast in GFR < 30'
2043
+ }
2044
+ };
2045
+ });
2046
+ }
2047
+ async function runLiverHealth() {
2048
+ return runToolAction('liver-health', async () => {
2049
+ const conditions = [
2050
+ { condition: 'NAFLD/MASLD', prevalence: '25-30%', screening: 'FIB-4, transient elastography' },
2051
+ { condition: 'Hepatitis B', prevalence: '0.3-0.5% (US)', screening: 'HBsAg, anti-HBc, anti-HBs' },
2052
+ { condition: 'Hepatitis C', prevalence: '1%', screening: 'Anti-HCV, confirm with HCV RNA' },
2053
+ { condition: 'Alcoholic liver disease', prevalence: 'Variable', screening: 'AUDIT, AST:ALT > 2' },
2054
+ { condition: 'Autoimmune hepatitis', prevalence: 'Rare', screening: 'ANA, SMA, IgG levels' },
2055
+ { condition: 'Hemochromatosis', prevalence: '1/200-300', screening: 'Iron studies, HFE gene' }
2056
+ ];
2057
+ const fibrosisStaging = [
2058
+ { stage: 'F0', description: 'No fibrosis', action: 'Lifestyle modification' },
2059
+ { stage: 'F1', description: 'Portal fibrosis', action: 'Monitor, address etiology' },
2060
+ { stage: 'F2', description: 'Periportal fibrosis', action: 'Consider treatment' },
2061
+ { stage: 'F3', description: 'Bridging fibrosis', action: 'Treatment, surveillance' },
2062
+ { stage: 'F4', description: 'Cirrhosis', action: 'HCC surveillance, varices screening' }
2063
+ ];
2064
+ const checks = [
2065
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: `${c.prevalence}: ${c.screening}` })),
2066
+ ...fibrosisStaging.map(f => ({ name: `Fibrosis ${f.stage}`, ok: true, detail: f.description }))
2067
+ ];
2068
+ return {
2069
+ summary: `${conditions.length} liver conditions, ${fibrosisStaging.length} fibrosis stages`,
2070
+ checks,
2071
+ metrics: {
2072
+ hccSurveillance: 'Ultrasound ± AFP every 6 months in cirrhosis',
2073
+ varicesSurveillance: 'EGD at cirrhosis diagnosis',
2074
+ hepatitisVaccination: 'HBV vaccine for all non-immune adults'
2075
+ }
2076
+ };
2077
+ });
2078
+ }
2079
+ async function runRespiratoryHealth() {
2080
+ return runToolAction('respiratory-health', async () => {
2081
+ const conditions = [
2082
+ { condition: 'COPD', prevalence: '6%', diagnosis: 'Spirometry: FEV1/FVC < 0.70' },
2083
+ { condition: 'Asthma', prevalence: '8%', diagnosis: 'Spirometry with reversibility' },
2084
+ { condition: 'Interstitial lung disease', prevalence: '0.03%', diagnosis: 'HRCT, PFTs' },
2085
+ { condition: 'Pulmonary hypertension', prevalence: 'Rare', diagnosis: 'Echo, RHC' },
2086
+ { condition: 'Sleep apnea', prevalence: '10-30%', diagnosis: 'Polysomnography' }
2087
+ ];
2088
+ const copdGold = [
2089
+ { stage: 'GOLD 1 (Mild)', fev1: '≥ 80%', symptoms: 'May have chronic cough' },
2090
+ { stage: 'GOLD 2 (Moderate)', fev1: '50-79%', symptoms: 'Dyspnea on exertion' },
2091
+ { stage: 'GOLD 3 (Severe)', fev1: '30-49%', symptoms: 'Increased dyspnea, exacerbations' },
2092
+ { stage: 'GOLD 4 (Very severe)', fev1: '< 30%', symptoms: 'Severe limitation, respiratory failure' }
2093
+ ];
2094
+ const checks = [
2095
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: `${c.prevalence}: ${c.diagnosis}` })),
2096
+ ...copdGold.map(g => ({ name: g.stage, ok: true, detail: `FEV1 ${g.fev1}` }))
2097
+ ];
2098
+ return {
2099
+ summary: `${conditions.length} respiratory conditions, COPD GOLD staging`,
2100
+ checks,
2101
+ metrics: {
2102
+ spirometryIndications: 'Smokers, dyspnea, chronic cough, wheezing',
2103
+ copdTreatment: 'Bronchodilators (LAMA, LABA), ICS for exacerbations',
2104
+ asthmaControl: 'ICS cornerstone, step-up/down approach',
2105
+ smokingCessation: 'Most important intervention for COPD'
2106
+ }
2107
+ };
2108
+ });
2109
+ }
2110
+ async function runThyroidScreening() {
2111
+ return runToolAction('thyroid-screening', async () => {
2112
+ const disorders = [
2113
+ { disorder: 'Hypothyroidism', tsh: 'Elevated', t4: 'Low', symptoms: 'Fatigue, weight gain, cold intolerance' },
2114
+ { disorder: 'Subclinical hypothyroidism', tsh: 'Mildly elevated', t4: 'Normal', symptoms: 'Often asymptomatic' },
2115
+ { disorder: 'Hyperthyroidism', tsh: 'Low', t4: 'High', symptoms: 'Weight loss, palpitations, heat intolerance' },
2116
+ { disorder: 'Thyroid nodules', tsh: 'Variable', t4: 'Variable', symptoms: 'Often incidental' },
2117
+ { disorder: 'Thyroid cancer', tsh: 'Variable', t4: 'Variable', symptoms: 'Nodule, lymphadenopathy' }
2118
+ ];
2119
+ const management = [
2120
+ { condition: 'Hypothyroidism', treatment: 'Levothyroxine', monitoring: 'TSH in 6-8 weeks, then annually' },
2121
+ { condition: 'Hyperthyroidism', treatment: 'Methimazole, RAI, surgery', monitoring: 'TFTs every 4-6 weeks initially' },
2122
+ { condition: 'Thyroid nodules', treatment: 'FNA if indicated by size/features', monitoring: 'Ultrasound surveillance' },
2123
+ { condition: 'Thyroid cancer', treatment: 'Surgery ± RAI', monitoring: 'Thyroglobulin, neck ultrasound' }
2124
+ ];
2125
+ const checks = [
2126
+ ...disorders.map(d => ({ name: d.disorder, ok: true, detail: `TSH ${d.tsh}, T4 ${d.t4}` })),
2127
+ ...management.map(m => ({ name: m.condition, ok: true, detail: m.treatment }))
2128
+ ];
2129
+ return {
2130
+ summary: `${disorders.length} thyroid disorders, ${management.length} management approaches`,
2131
+ checks,
2132
+ metrics: {
2133
+ screeningIndications: 'Symptoms, family history, pregnancy, radiation exposure',
2134
+ tshGoal: '0.5-4.0 mIU/L (varies by lab and age)',
2135
+ noduleWorkup: 'TSH, ultrasound, FNA if > 1cm or suspicious features'
2136
+ }
2137
+ };
2138
+ });
2139
+ }
2140
+ async function runSexualHealth() {
2141
+ return runToolAction('sexual-health', async () => {
2142
+ const screenings = [
2143
+ { test: 'HIV', who: 'All adults 15-65, high-risk annually', method: 'HIV Ag/Ab' },
2144
+ { test: 'Chlamydia', who: 'Sexually active women < 25, high-risk', method: 'NAAT' },
2145
+ { test: 'Gonorrhea', who: 'Sexually active women < 25, high-risk', method: 'NAAT' },
2146
+ { test: 'Syphilis', who: 'MSM, HIV+, high-risk pregnancy', method: 'Treponemal/non-treponemal' },
2147
+ { test: 'Hepatitis B', who: 'Unvaccinated with risk factors', method: 'HBsAg, anti-HBs' },
2148
+ { test: 'HPV/Cervical', who: 'Women 21-65', method: 'Pap ± HPV co-testing' }
2149
+ ];
2150
+ const contraception = [
2151
+ { method: 'IUD (hormonal)', efficacy: '99.8%', duration: '3-7 years' },
2152
+ { method: 'IUD (copper)', efficacy: '99.2%', duration: '10-12 years' },
2153
+ { method: 'Implant', efficacy: '99.9%', duration: '3-5 years' },
2154
+ { method: 'Injection', efficacy: '94%', duration: 'Every 3 months' },
2155
+ { method: 'Pill/Patch/Ring', efficacy: '91%', duration: 'Daily/weekly/monthly' },
2156
+ { method: 'Condoms', efficacy: '82%', duration: 'Per use' }
2157
+ ];
2158
+ const checks = [
2159
+ ...screenings.map(s => ({ name: s.test, ok: true, detail: `${s.who}` })),
2160
+ ...contraception.map(c => ({ name: c.method, ok: true, detail: `${c.efficacy} effective, ${c.duration}` }))
2161
+ ];
2162
+ return {
2163
+ summary: `${screenings.length} STI screenings, ${contraception.length} contraception options`,
2164
+ checks,
2165
+ metrics: {
2166
+ prep: 'PrEP (Truvada/Descovy) for HIV prevention in high-risk',
2167
+ pep: 'PEP within 72 hours of exposure',
2168
+ hpvVaccine: 'Recommended through age 26, available to 45'
2169
+ }
2170
+ };
2171
+ });
2172
+ }
2173
+ async function runInfectiousDisease() {
2174
+ return runToolAction('infectious-disease', async () => {
2175
+ const screenings = [
2176
+ { disease: 'HIV', recommendation: 'All adults 15-65 at least once, high-risk annually' },
2177
+ { disease: 'Hepatitis C', recommendation: 'All adults 18-79 once' },
2178
+ { disease: 'Hepatitis B', recommendation: 'High-risk populations' },
2179
+ { disease: 'Tuberculosis (latent)', recommendation: 'High-risk: immigrants, healthcare workers, immunocompromised' },
2180
+ { disease: 'Syphilis', recommendation: 'Pregnant women, MSM, HIV+' },
2181
+ { disease: 'Chlamydia/Gonorrhea', recommendation: 'Sexually active women < 25' }
2182
+ ];
2183
+ const vaccines = [
2184
+ { vaccine: 'Influenza', schedule: 'Annually' },
2185
+ { vaccine: 'COVID-19', schedule: 'Per current CDC guidance' },
2186
+ { vaccine: 'Pneumococcal', schedule: 'Age 65+ or high-risk' },
2187
+ { vaccine: 'Shingles', schedule: 'Age 50+' },
2188
+ { vaccine: 'Hepatitis B', schedule: 'All adults' }
2189
+ ];
2190
+ const checks = [
2191
+ ...screenings.map(s => ({ name: s.disease, ok: true, detail: s.recommendation })),
2192
+ ...vaccines.map(v => ({ name: `${v.vaccine} vaccine`, ok: true, detail: v.schedule }))
2193
+ ];
2194
+ return {
2195
+ summary: `${screenings.length} ID screenings, ${vaccines.length} vaccines`,
2196
+ checks,
2197
+ metrics: {
2198
+ hivTreatment: 'Start ART immediately upon diagnosis',
2199
+ hcvCure: '> 95% cure rate with DAAs (8-12 weeks)',
2200
+ ltbiTreatment: '3HP, 4R, or 9H regimens'
2201
+ }
2202
+ };
2203
+ });
2204
+ }
2205
+ async function runAutoimmuneScreening() {
2206
+ return runToolAction('autoimmune-screening', async () => {
2207
+ const conditions = [
2208
+ { condition: 'Rheumatoid arthritis', markers: 'RF, anti-CCP', prevalence: '0.5-1%' },
2209
+ { condition: 'SLE (Lupus)', markers: 'ANA, anti-dsDNA, anti-Smith', prevalence: '0.02-0.05%' },
2210
+ { condition: 'Sjögren syndrome', markers: 'ANA, anti-SSA/SSB', prevalence: '0.5-1%' },
2211
+ { condition: 'Systemic sclerosis', markers: 'ANA, anti-Scl70, anti-centromere', prevalence: '0.02%' },
2212
+ { condition: 'Autoimmune thyroiditis', markers: 'Anti-TPO, anti-thyroglobulin', prevalence: '5-15%' },
2213
+ { condition: 'Type 1 diabetes', markers: 'Anti-GAD, anti-IA2, anti-insulin', prevalence: '0.4%' },
2214
+ { condition: 'Celiac disease', markers: 'Anti-tTG IgA, EMA', prevalence: '1%' },
2215
+ { condition: 'Inflammatory myopathy', markers: 'ANA, anti-Jo1, anti-Mi2', prevalence: 'Rare' }
2216
+ ];
2217
+ const checks = conditions.map(c => ({
2218
+ name: c.condition,
2219
+ ok: true,
2220
+ detail: `${c.markers} (${c.prevalence})`
2221
+ }));
2222
+ return {
2223
+ summary: `${conditions.length} autoimmune conditions with markers`,
2224
+ checks,
2225
+ metrics: {
2226
+ anaInterpretation: 'Positive ANA common (15% healthy), pattern and titer matter',
2227
+ rheumatologyReferral: 'Positive specific antibodies + symptoms',
2228
+ treatmentApproach: 'DMARDs, biologics, immunosuppressants'
2229
+ }
2230
+ };
2231
+ });
2232
+ }
2233
+ async function runAllergyAssessment() {
2234
+ return runToolAction('allergy-assessment', async () => {
2235
+ const allergyTypes = [
2236
+ { type: 'Allergic rhinitis', prevalence: '10-30%', testing: 'Skin prick, serum IgE' },
2237
+ { type: 'Asthma (allergic)', prevalence: '8%', testing: 'Spirometry, allergen testing' },
2238
+ { type: 'Food allergy', prevalence: '2-5% adults', testing: 'Skin prick, serum IgE, oral challenge' },
2239
+ { type: 'Drug allergy', prevalence: '10% report, <2% confirmed', testing: 'Skin testing, challenge' },
2240
+ { type: 'Atopic dermatitis', prevalence: '2-5% adults', testing: 'Clinical, patch testing' },
2241
+ { type: 'Anaphylaxis', prevalence: '0.05-2%', testing: 'Tryptase, specific IgE' }
2242
+ ];
2243
+ const treatments = [
2244
+ { approach: 'Avoidance', description: 'Identify and avoid triggers' },
2245
+ { approach: 'Antihistamines', description: 'H1 blockers (cetirizine, loratadine)' },
2246
+ { approach: 'Intranasal corticosteroids', description: 'First-line for allergic rhinitis' },
2247
+ { approach: 'Immunotherapy', description: 'Subcutaneous or sublingual for selected allergens' },
2248
+ { approach: 'Epinephrine', description: 'Auto-injector for anaphylaxis risk' },
2249
+ { approach: 'Biologics', description: 'Omalizumab for severe asthma/urticaria' }
2250
+ ];
2251
+ const checks = [
2252
+ ...allergyTypes.map(a => ({ name: a.type, ok: true, detail: `${a.prevalence}: ${a.testing}` })),
2253
+ ...treatments.map(t => ({ name: t.approach, ok: true, detail: t.description }))
2254
+ ];
2255
+ return {
2256
+ summary: `${allergyTypes.length} allergy types, ${treatments.length} treatments`,
2257
+ checks,
2258
+ metrics: {
2259
+ epinephrineIndications: 'History of anaphylaxis, high-risk food allergy',
2260
+ immunotherapyDuration: '3-5 years for disease modification',
2261
+ referralIndications: 'Moderate-severe symptoms, anaphylaxis, immunotherapy candidate'
2262
+ }
2263
+ };
2264
+ });
2265
+ }
2266
+ async function runPainManagement() {
2267
+ return runToolAction('pain-management', async () => {
2268
+ const painTypes = [
2269
+ { type: 'Nociceptive (somatic)', example: 'Musculoskeletal', treatment: 'NSAIDs, acetaminophen, PT' },
2270
+ { type: 'Nociceptive (visceral)', example: 'Abdominal', treatment: 'Antispasmodics, address cause' },
2271
+ { type: 'Neuropathic', example: 'Diabetic neuropathy', treatment: 'Gabapentinoids, TCAs, SNRIs' },
2272
+ { type: 'Inflammatory', example: 'Arthritis', treatment: 'NSAIDs, DMARDs, biologics' },
2273
+ { type: 'Central sensitization', example: 'Fibromyalgia', treatment: 'Duloxetine, pregabalin, exercise' },
2274
+ { type: 'Cancer pain', example: 'Tumor invasion', treatment: 'WHO ladder, adjuvants, interventions' }
2275
+ ];
2276
+ const nonPharmacologic = [
2277
+ 'Physical therapy', 'Occupational therapy', 'Cognitive behavioral therapy',
2278
+ 'Acupuncture', 'Massage', 'TENS', 'Heat/cold therapy', 'Exercise', 'Mindfulness'
2279
+ ];
2280
+ const opioidPrinciples = [
2281
+ 'Exhausted non-opioid options first',
2282
+ 'Start low, go slow',
2283
+ 'Use lowest effective dose',
2284
+ 'Regular reassessment',
2285
+ 'Naloxone co-prescription',
2286
+ 'Avoid concurrent benzodiazepines',
2287
+ 'Screen for OUD risk (ORT, SOAPP)'
2288
+ ];
2289
+ const checks = [
2290
+ ...painTypes.map(p => ({ name: p.type, ok: true, detail: `${p.example}: ${p.treatment}` })),
2291
+ { name: 'Non-pharmacologic options', ok: true, detail: `${nonPharmacologic.length} modalities` },
2292
+ { name: 'Opioid stewardship', ok: true, detail: `${opioidPrinciples.length} principles` }
2293
+ ];
2294
+ return {
2295
+ summary: `${painTypes.length} pain types, multimodal approach`,
2296
+ checks,
2297
+ metrics: {
2298
+ whoLadder: 'Step 1 (non-opioids) → Step 2 (weak opioids) → Step 3 (strong opioids)',
2299
+ mmeDailyLimit: '≤ 50 MME/day preferred, > 90 requires justification',
2300
+ pdmp: 'Check prescription drug monitoring program'
2301
+ }
2302
+ };
2303
+ });
2304
+ }
2305
+ async function runExercisePrescription() {
2306
+ return runToolAction('exercise-prescription', async () => {
2307
+ const guidelines = [
2308
+ { type: 'Aerobic', recommendation: '150-300 min moderate OR 75-150 min vigorous/week' },
2309
+ { type: 'Resistance', recommendation: '2+ days/week, all major muscle groups' },
2310
+ { type: 'Flexibility', recommendation: '2-3 days/week' },
2311
+ { type: 'Balance (older adults)', recommendation: '3+ days/week' },
2312
+ { type: 'Bone-loading', recommendation: 'Weight-bearing activities' }
2313
+ ];
2314
+ const conditions = [
2315
+ { condition: 'Cardiovascular disease', modification: 'Supervised initially, gradually increase' },
2316
+ { condition: 'Diabetes', modification: 'Monitor glucose, timing with meals/insulin' },
2317
+ { condition: 'Obesity', modification: 'Low-impact, gradual progression' },
2318
+ { condition: 'Osteoporosis', modification: 'Weight-bearing, avoid high-impact or flexion' },
2319
+ { condition: 'Arthritis', modification: 'Low-impact, aquatic exercise' },
2320
+ { condition: 'COPD', modification: 'Pulmonary rehab, pacing' },
2321
+ { condition: 'Pregnancy', modification: 'Moderate intensity, avoid supine after 1st trimester' }
2322
+ ];
2323
+ const checks = [
2324
+ ...guidelines.map(g => ({ name: g.type, ok: true, detail: g.recommendation })),
2325
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: c.modification }))
2326
+ ];
2327
+ return {
2328
+ summary: `${guidelines.length} exercise types, ${conditions.length} condition modifications`,
2329
+ checks,
2330
+ metrics: {
2331
+ fittPrinciple: 'Frequency, Intensity, Time, Type',
2332
+ rpe: 'Rate of Perceived Exertion 12-14 for moderate',
2333
+ contraindications: 'Unstable angina, severe AS, acute illness, uncontrolled arrhythmia'
2334
+ }
2335
+ };
2336
+ });
2337
+ }
2338
+ async function runWeightManagement() {
2339
+ return runToolAction('weight-management', async () => {
2340
+ const bmiCategories = [
2341
+ { category: 'Underweight', bmi: '< 18.5', action: 'Evaluate for underlying cause' },
2342
+ { category: 'Normal', bmi: '18.5-24.9', action: 'Maintain healthy lifestyle' },
2343
+ { category: 'Overweight', bmi: '25-29.9', action: 'Lifestyle modification' },
2344
+ { category: 'Obesity Class I', bmi: '30-34.9', action: 'Intensive lifestyle ± medication' },
2345
+ { category: 'Obesity Class II', bmi: '35-39.9', action: 'Consider bariatric surgery if comorbidities' },
2346
+ { category: 'Obesity Class III', bmi: '≥ 40', action: 'Bariatric surgery consideration' }
2347
+ ];
2348
+ const medications = [
2349
+ { drug: 'Semaglutide (Wegovy)', mechanism: 'GLP-1 agonist', weightLoss: '15-17%' },
2350
+ { drug: 'Tirzepatide (Zepbound)', mechanism: 'GIP/GLP-1', weightLoss: '20-22%' },
2351
+ { drug: 'Phentermine-topiramate', mechanism: 'Appetite suppressant + anticonvulsant', weightLoss: '10%' },
2352
+ { drug: 'Naltrexone-bupropion', mechanism: 'Opioid antagonist + antidepressant', weightLoss: '5-6%' },
2353
+ { drug: 'Orlistat', mechanism: 'Lipase inhibitor', weightLoss: '3%' }
2354
+ ];
2355
+ const surgeryOptions = [
2356
+ { procedure: 'Sleeve gastrectomy', excess: '60-70%', mechanism: 'Restrictive' },
2357
+ { procedure: 'Roux-en-Y gastric bypass', excess: '70-80%', mechanism: 'Restrictive + malabsorptive' },
2358
+ { procedure: 'Duodenal switch', excess: '80%+', mechanism: 'Malabsorptive' }
2359
+ ];
2360
+ const checks = [
2361
+ ...bmiCategories.map(b => ({ name: b.category, ok: true, detail: `BMI ${b.bmi}` })),
2362
+ ...medications.map(m => ({ name: m.drug, ok: true, detail: `${m.weightLoss} weight loss` })),
2363
+ ...surgeryOptions.map(s => ({ name: s.procedure, ok: true, detail: `${s.excess} excess weight loss` }))
2364
+ ];
2365
+ return {
2366
+ summary: `BMI categories, ${medications.length} medications, ${surgeryOptions.length} surgical options`,
2367
+ checks,
2368
+ metrics: {
2369
+ targetWeightLoss: '5-10% for metabolic benefit',
2370
+ calorieDeficit: '500-1000 kcal/day for 1-2 lb/week',
2371
+ proteinIntake: '1.2-1.5 g/kg ideal body weight'
2372
+ }
2373
+ };
2374
+ });
2375
+ }
2376
+ async function runStressManagement() {
2377
+ return runToolAction('stress-management', async () => {
2378
+ const stressIndicators = [
2379
+ { domain: 'Physical', signs: 'Headaches, muscle tension, fatigue, sleep issues' },
2380
+ { domain: 'Emotional', signs: 'Anxiety, irritability, depression, feeling overwhelmed' },
2381
+ { domain: 'Cognitive', signs: 'Difficulty concentrating, racing thoughts, forgetfulness' },
2382
+ { domain: 'Behavioral', signs: 'Appetite changes, social withdrawal, substance use' }
2383
+ ];
2384
+ const strategies = [
2385
+ { category: 'Relaxation', techniques: 'Deep breathing, progressive muscle relaxation, meditation' },
2386
+ { category: 'Cognitive', techniques: 'Cognitive restructuring, mindfulness, journaling' },
2387
+ { category: 'Behavioral', techniques: 'Time management, assertiveness, problem-solving' },
2388
+ { category: 'Lifestyle', techniques: 'Exercise, sleep hygiene, nutrition, social support' },
2389
+ { category: 'Professional', techniques: 'Therapy (CBT, MBSR), counseling, medication if needed' }
2390
+ ];
2391
+ const checks = [
2392
+ ...stressIndicators.map(s => ({ name: s.domain, ok: true, detail: s.signs })),
2393
+ ...strategies.map(s => ({ name: s.category, ok: true, detail: s.techniques }))
2394
+ ];
2395
+ return {
2396
+ summary: `${stressIndicators.length} stress domains, ${strategies.length} strategy categories`,
2397
+ checks,
2398
+ metrics: {
2399
+ screeningTool: 'Perceived Stress Scale (PSS)',
2400
+ referralIndications: 'Persistent symptoms, functional impairment, suicidal ideation',
2401
+ apps: 'Headspace, Calm, Insight Timer for guided practice'
2402
+ }
2403
+ };
2404
+ });
2405
+ }
2406
+ async function runVisionScreening() {
2407
+ return runToolAction('vision-screening', async () => {
2408
+ const conditions = [
2409
+ { condition: 'Refractive errors', prevalence: '50%+', screening: 'Visual acuity, refraction' },
2410
+ { condition: 'Cataracts', prevalence: '50% by age 75', screening: 'Slit lamp exam' },
2411
+ { condition: 'Glaucoma', prevalence: '2-3%', screening: 'IOP, optic nerve exam, visual fields' },
2412
+ { condition: 'Age-related macular degeneration', prevalence: '10% > 65', screening: 'Dilated fundoscopy, OCT' },
2413
+ { condition: 'Diabetic retinopathy', prevalence: '30% of diabetics', screening: 'Annual dilated exam' },
2414
+ { condition: 'Dry eye', prevalence: '10-30%', screening: 'Symptom assessment, tear film eval' }
2415
+ ];
2416
+ const schedule = [
2417
+ { age: '< 40', frequency: 'Every 2-4 years if asymptomatic' },
2418
+ { age: '40-54', frequency: 'Every 2-4 years' },
2419
+ { age: '55-64', frequency: 'Every 1-3 years' },
2420
+ { age: '65+', frequency: 'Every 1-2 years' },
2421
+ { age: 'Diabetics', frequency: 'Annually starting at diagnosis' }
2422
+ ];
2423
+ const checks = [
2424
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: `${c.prevalence}: ${c.screening}` })),
2425
+ ...schedule.map(s => ({ name: `Age ${s.age}`, ok: true, detail: s.frequency }))
2426
+ ];
2427
+ return {
2428
+ summary: `${conditions.length} eye conditions, ${schedule.length} screening intervals`,
2429
+ checks,
2430
+ metrics: {
2431
+ glaucomaRisk: 'Age > 60, African descent, family history, high myopia',
2432
+ amdRisk: 'Age, smoking, family history, obesity',
2433
+ urgentReferral: 'Sudden vision loss, flashes/floaters, eye pain/redness'
2434
+ }
2435
+ };
2436
+ });
2437
+ }
2438
+ async function runHearingScreening() {
2439
+ return runToolAction('hearing-screening', async () => {
2440
+ const hearingLoss = [
2441
+ { degree: 'Normal', threshold: '< 20 dB' },
2442
+ { degree: 'Mild', threshold: '20-40 dB' },
2443
+ { degree: 'Moderate', threshold: '41-55 dB' },
2444
+ { degree: 'Moderately severe', threshold: '56-70 dB' },
2445
+ { degree: 'Severe', threshold: '71-90 dB' },
2446
+ { degree: 'Profound', threshold: '> 90 dB' }
2447
+ ];
2448
+ const riskFactors = [
2449
+ 'Age > 50', 'Occupational noise exposure', 'Recreational noise (concerts, headphones)',
2450
+ 'Ototoxic medications (aminoglycosides, cisplatin)', 'Family history', 'Diabetes', 'Cardiovascular disease'
2451
+ ];
2452
+ const interventions = [
2453
+ { intervention: 'Hearing aids', indication: 'Mild to profound hearing loss' },
2454
+ { intervention: 'Cochlear implants', indication: 'Severe-profound when aids insufficient' },
2455
+ { intervention: 'Assistive devices', indication: 'TV amplifiers, alerting systems' },
2456
+ { intervention: 'Aural rehabilitation', indication: 'Communication strategies, lip reading' }
2457
+ ];
2458
+ const checks = [
2459
+ ...hearingLoss.map(h => ({ name: h.degree, ok: true, detail: h.threshold })),
2460
+ ...interventions.map(i => ({ name: i.intervention, ok: true, detail: i.indication }))
2461
+ ];
2462
+ return {
2463
+ summary: `${hearingLoss.length} hearing levels, ${interventions.length} interventions`,
2464
+ checks,
2465
+ metrics: {
2466
+ screeningAge: 'Adults 50+ every 3 years, earlier if risk factors',
2467
+ otcHearingAids: 'Available for mild-moderate loss without prescription',
2468
+ cognitiveLink: 'Untreated hearing loss associated with cognitive decline'
2469
+ }
2470
+ };
2471
+ });
2472
+ }
2473
+ async function runDentalHealth() {
2474
+ return runToolAction('dental-health', async () => {
2475
+ const conditions = [
2476
+ { condition: 'Dental caries', prevalence: '90%+ lifetime', prevention: 'Fluoride, brushing, flossing' },
2477
+ { condition: 'Periodontal disease', prevalence: '47% adults', prevention: 'Oral hygiene, regular cleanings' },
2478
+ { condition: 'Oral cancer', prevalence: '3% of cancers', screening: 'Visual exam, high-risk screening' },
2479
+ { condition: 'Tooth loss', prevalence: '26% of 65+', prevention: 'Preventive care, caries/perio treatment' }
2480
+ ];
2481
+ const oralSystemic = [
2482
+ { condition: 'Diabetes', connection: 'Bidirectional relationship with periodontal disease' },
2483
+ { condition: 'Cardiovascular disease', connection: 'Inflammation, endocarditis risk' },
2484
+ { condition: 'Pregnancy', connection: 'Periodontal disease linked to preterm birth' },
2485
+ { condition: 'Osteoporosis', connection: 'Bone loss affects jaw, tooth loss' }
2486
+ ];
2487
+ const schedule = [
2488
+ { visit: 'Exam and cleaning', frequency: 'Every 6 months (or per risk)' },
2489
+ { visit: 'Bitewing X-rays', frequency: 'Every 6-12 months' },
2490
+ { visit: 'Full mouth X-rays', frequency: 'Every 3-5 years' }
2491
+ ];
2492
+ const checks = [
2493
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: `${c.prevalence}: ${c.prevention}` })),
2494
+ ...oralSystemic.map(o => ({ name: o.condition, ok: true, detail: o.connection }))
2495
+ ];
2496
+ return {
2497
+ summary: `${conditions.length} oral conditions, ${oralSystemic.length} systemic connections`,
2498
+ checks,
2499
+ metrics: {
2500
+ brushing: '2 minutes twice daily with fluoride toothpaste',
2501
+ flossing: 'Daily',
2502
+ oralCancerRisk: 'Tobacco, alcohol, HPV (oropharyngeal)'
2503
+ }
2504
+ };
2505
+ });
2506
+ }
2507
+ async function runSkinHealth() {
2508
+ return runToolAction('skin-health', async () => {
2509
+ const conditions = [
2510
+ { condition: 'Actinic keratosis', risk: 'Precancerous', action: 'Cryotherapy, topical treatment, surveillance' },
2511
+ { condition: 'Basal cell carcinoma', risk: 'Most common skin cancer', action: 'Surgical excision, Mohs' },
2512
+ { condition: 'Squamous cell carcinoma', risk: 'Can metastasize', action: 'Surgical excision' },
2513
+ { condition: 'Melanoma', risk: 'Highest mortality', action: 'Wide excision, staging, systemic therapy if advanced' },
2514
+ { condition: 'Psoriasis', risk: 'Chronic, CV association', action: 'Topicals, phototherapy, biologics' },
2515
+ { condition: 'Eczema', risk: 'Chronic, infection risk', action: 'Moisturizers, topical steroids, immunomodulators' }
2516
+ ];
2517
+ const abcde = [
2518
+ { letter: 'A', criterion: 'Asymmetry' },
2519
+ { letter: 'B', criterion: 'Border irregularity' },
2520
+ { letter: 'C', criterion: 'Color variation' },
2521
+ { letter: 'D', criterion: 'Diameter > 6mm' },
2522
+ { letter: 'E', criterion: 'Evolution/change' }
2523
+ ];
2524
+ const sunProtection = [
2525
+ 'Broad-spectrum SPF 30+ sunscreen',
2526
+ 'Reapply every 2 hours',
2527
+ 'Seek shade 10am-4pm',
2528
+ 'Protective clothing, hats',
2529
+ 'Avoid tanning beds'
2530
+ ];
2531
+ const checks = [
2532
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: `${c.risk}` })),
2533
+ ...abcde.map(a => ({ name: `ABCDE: ${a.letter}`, ok: true, detail: a.criterion }))
2534
+ ];
2535
+ return {
2536
+ summary: `${conditions.length} skin conditions, ABCDE criteria for melanoma`,
2537
+ checks,
2538
+ metrics: {
2539
+ selfExam: 'Monthly full-body skin self-exam',
2540
+ dermatologyVisit: 'Annual for high-risk, as needed otherwise',
2541
+ melanomaSurvival: '> 99% if localized, 35% if distant'
2542
+ }
2543
+ };
2544
+ });
2545
+ }
2546
+ async function runGeneticRisk() {
2547
+ return runToolAction('genetic-risk', async () => {
2548
+ const hereditaryCancers = [
2549
+ { syndrome: 'BRCA1/2', cancers: 'Breast, ovarian, prostate, pancreatic', prevalence: '1/400' },
2550
+ { syndrome: 'Lynch syndrome', cancers: 'Colorectal, endometrial, ovarian', prevalence: '1/300' },
2551
+ { syndrome: 'Li-Fraumeni', cancers: 'Sarcoma, breast, brain, leukemia', prevalence: 'Rare' },
2552
+ { syndrome: 'Cowden syndrome', cancers: 'Breast, thyroid, endometrial', prevalence: '1/200,000' },
2553
+ { syndrome: 'MEN syndromes', cancers: 'Thyroid, parathyroid, pheochromocytoma', prevalence: '1/30,000' }
2554
+ ];
2555
+ const cardiacGenetics = [
2556
+ { condition: 'Familial hypercholesterolemia', prevalence: '1/250', testing: 'Lipid panel, cascade testing' },
2557
+ { condition: 'Hypertrophic cardiomyopathy', prevalence: '1/500', testing: 'Echo, genetic panel' },
2558
+ { condition: 'Long QT syndrome', prevalence: '1/2,500', testing: 'ECG, genetic panel' },
2559
+ { condition: 'ARVC', prevalence: '1/5,000', testing: 'Echo, MRI, genetic panel' }
2560
+ ];
2561
+ const referralCriteria = [
2562
+ 'Personal history of cancer < 50',
2563
+ 'Multiple primary cancers',
2564
+ 'Multiple family members with cancer',
2565
+ 'Rare cancers (male breast, ovarian)',
2566
+ 'Ethnic backgrounds with founder mutations (Ashkenazi Jewish)'
2567
+ ];
2568
+ const checks = [
2569
+ ...hereditaryCancers.map(h => ({ name: h.syndrome, ok: true, detail: h.cancers })),
2570
+ ...cardiacGenetics.map(c => ({ name: c.condition, ok: true, detail: c.prevalence }))
2571
+ ];
2572
+ return {
2573
+ summary: `${hereditaryCancers.length} hereditary cancer syndromes, ${cardiacGenetics.length} cardiac conditions`,
2574
+ checks,
2575
+ metrics: {
2576
+ geneticCounseling: 'Pre- and post-test counseling essential',
2577
+ cascadeTesting: 'Test at-risk family members if positive',
2578
+ directToConsumer: 'Not sufficient for clinical decision-making'
2579
+ }
2580
+ };
2581
+ });
2582
+ }
2583
+ async function runMedicationReview() {
2584
+ return runToolAction('medication-review', async () => {
2585
+ const polypharmacyConcerns = [
2586
+ { concern: 'Drug-drug interactions', assessment: 'Review all medications including OTC' },
2587
+ { concern: 'Anticholinergic burden', assessment: 'ACB scale, cognitive effects' },
2588
+ { concern: 'Falls risk medications', assessment: 'Sedatives, antihypertensives, psychotropics' },
2589
+ { concern: 'Renal dosing', assessment: 'Adjust for CrCl/eGFR' },
2590
+ { concern: 'Hepatic dosing', assessment: 'Adjust for hepatic impairment' },
2591
+ { concern: 'Inappropriate prescribing (elderly)', assessment: 'Beers criteria, STOPP/START' }
2592
+ ];
2593
+ const deprescribingPriorities = [
2594
+ { class: 'PPIs', reason: 'Often used longer than needed, infection/fracture risk' },
2595
+ { class: 'Benzodiazepines', reason: 'Falls, cognitive impairment, dependence' },
2596
+ { class: 'Anticholinergics', reason: 'Cognitive impairment, constipation, urinary retention' },
2597
+ { class: 'Antipsychotics (dementia)', reason: 'Increased mortality, limited benefit' },
2598
+ { class: 'Sulfonylureas (elderly)', reason: 'Hypoglycemia risk' }
2599
+ ];
2600
+ const checks = [
2601
+ ...polypharmacyConcerns.map(p => ({ name: p.concern, ok: true, detail: p.assessment })),
2602
+ ...deprescribingPriorities.map(d => ({ name: d.class, ok: true, detail: d.reason }))
2603
+ ];
2604
+ return {
2605
+ summary: `${polypharmacyConcerns.length} concerns, ${deprescribingPriorities.length} deprescribing priorities`,
2606
+ checks,
2607
+ metrics: {
2608
+ polypharmacyThreshold: '≥ 5 medications (some use ≥ 10)',
2609
+ medicationReconciliation: 'At every transition of care',
2610
+ brownBagReview: 'Patient brings all medications to visit'
2611
+ }
2612
+ };
2613
+ });
2614
+ }
2615
+ async function runFallRisk() {
2616
+ return runToolAction('fall-risk', async () => {
2617
+ const riskFactors = [
2618
+ { factor: 'Age > 65', category: 'Non-modifiable' },
2619
+ { factor: 'History of falls', category: 'Major predictor' },
2620
+ { factor: 'Gait/balance impairment', category: 'Modifiable' },
2621
+ { factor: 'Polypharmacy (≥ 4 meds)', category: 'Modifiable' },
2622
+ { factor: 'Psychotropic medications', category: 'Modifiable' },
2623
+ { factor: 'Visual impairment', category: 'Modifiable' },
2624
+ { factor: 'Cognitive impairment', category: 'Partially modifiable' },
2625
+ { factor: 'Environmental hazards', category: 'Modifiable' },
2626
+ { factor: 'Orthostatic hypotension', category: 'Modifiable' },
2627
+ { factor: 'Foot/footwear problems', category: 'Modifiable' }
2628
+ ];
2629
+ const assessments = [
2630
+ { test: 'Timed Up and Go (TUG)', cutoff: '> 12 seconds = increased risk' },
2631
+ { test: '4-Stage Balance Test', cutoff: 'Unable to hold tandem 10 sec = increased risk' },
2632
+ { test: 'Orthostatic vitals', cutoff: 'SBP drop ≥ 20 or DBP ≥ 10' },
2633
+ { test: 'Vision screening', cutoff: 'Worse than 20/40' },
2634
+ { test: 'Medication review', cutoff: 'Any fall-risk-increasing drugs' }
2635
+ ];
2636
+ const interventions = [
2637
+ 'Exercise (balance, strength, gait training)',
2638
+ 'Medication review/reduction',
2639
+ 'Vision correction',
2640
+ 'Home safety assessment',
2641
+ 'Vitamin D supplementation',
2642
+ 'Assistive devices as needed',
2643
+ 'Hip protectors for high-risk'
2644
+ ];
2645
+ const checks = [
2646
+ ...riskFactors.map(r => ({ name: r.factor, ok: true, detail: r.category })),
2647
+ ...assessments.map(a => ({ name: a.test, ok: true, detail: a.cutoff }))
2648
+ ];
2649
+ return {
2650
+ summary: `${riskFactors.length} risk factors, ${interventions.length} interventions`,
2651
+ checks,
2652
+ metrics: {
2653
+ screeningQuestion: 'Have you fallen in the past year?',
2654
+ fracturePrevention: 'Treat osteoporosis, vitamin D, calcium',
2655
+ emergencyResponse: 'Medical alert system for high-risk'
2656
+ }
2657
+ };
2658
+ });
2659
+ }
2660
+ async function runFunctionalStatus() {
2661
+ return runToolAction('functional-status', async () => {
2662
+ const adls = [
2663
+ { activity: 'Bathing', description: 'Ability to wash oneself' },
2664
+ { activity: 'Dressing', description: 'Ability to dress/undress' },
2665
+ { activity: 'Toileting', description: 'Using toilet, managing hygiene' },
2666
+ { activity: 'Transferring', description: 'Moving in/out of bed or chair' },
2667
+ { activity: 'Continence', description: 'Control of bladder and bowel' },
2668
+ { activity: 'Feeding', description: 'Ability to feed oneself' }
2669
+ ];
2670
+ const iadls = [
2671
+ { activity: 'Phone use', description: 'Using telephone' },
2672
+ { activity: 'Shopping', description: 'Obtaining groceries/necessities' },
2673
+ { activity: 'Food preparation', description: 'Planning and cooking meals' },
2674
+ { activity: 'Housekeeping', description: 'Maintaining home' },
2675
+ { activity: 'Laundry', description: 'Washing clothes' },
2676
+ { activity: 'Transportation', description: 'Driving or using transport' },
2677
+ { activity: 'Medications', description: 'Managing medications' },
2678
+ { activity: 'Finances', description: 'Managing money' }
2679
+ ];
2680
+ const checks = [
2681
+ ...adls.map(a => ({ name: `ADL: ${a.activity}`, ok: true, detail: a.description })),
2682
+ ...iadls.map(i => ({ name: `IADL: ${i.activity}`, ok: true, detail: i.description }))
2683
+ ];
2684
+ return {
2685
+ summary: `${adls.length} ADLs, ${iadls.length} IADLs assessed`,
2686
+ checks,
2687
+ metrics: {
2688
+ katzIndex: 'ADL assessment tool',
2689
+ lawtonScale: 'IADL assessment tool',
2690
+ careNeeds: 'ADL dependence indicates need for personal care assistance'
2691
+ }
2692
+ };
2693
+ });
2694
+ }
2695
+ async function runPediatricWellness() {
2696
+ return runToolAction('pediatric-wellness', async () => {
2697
+ const wellChildVisits = [
2698
+ { age: 'Newborn', focus: 'Birth weight, feeding, jaundice, hearing screen' },
2699
+ { age: '2-4 days', focus: 'Weight, feeding, jaundice follow-up' },
2700
+ { age: '1 month', focus: 'Growth, feeding, development' },
2701
+ { age: '2 months', focus: 'Vaccines, growth, development' },
2702
+ { age: '4 months', focus: 'Vaccines, milestones, nutrition' },
2703
+ { age: '6 months', focus: 'Vaccines, solid food introduction' },
2704
+ { age: '9 months', focus: 'Development, dental, safety' },
2705
+ { age: '12 months', focus: 'Vaccines, walking, language' },
2706
+ { age: '15 months', focus: 'Vaccines, autism screening' },
2707
+ { age: '18 months', focus: 'Autism screening, language' },
2708
+ { age: '2 years', focus: 'Growth, behavior, dental' },
2709
+ { age: '3-21 years', focus: 'Annual visits, vaccines per schedule' }
2710
+ ];
2711
+ const screenings = [
2712
+ { screening: 'Newborn metabolic', timing: '24-48 hours' },
2713
+ { screening: 'Hearing', timing: 'Before discharge, follow-up if abnormal' },
2714
+ { screening: 'Vision', timing: '3-5 years formal screening' },
2715
+ { screening: 'Lead', timing: '12 and 24 months (high-risk areas)' },
2716
+ { screening: 'Autism (M-CHAT)', timing: '18 and 24 months' },
2717
+ { screening: 'Depression (PHQ-A)', timing: '12+ years annually' },
2718
+ { screening: 'Lipids', timing: '9-11 years, 17-21 years' }
2719
+ ];
2720
+ const checks = [
2721
+ ...wellChildVisits.slice(0, 8).map(w => ({ name: w.age, ok: true, detail: w.focus })),
2722
+ ...screenings.map(s => ({ name: s.screening, ok: true, detail: s.timing }))
2723
+ ];
2724
+ return {
2725
+ summary: `${wellChildVisits.length} well-child visits, ${screenings.length} screenings`,
2726
+ checks,
2727
+ metrics: {
2728
+ vaccineSchedule: 'Per CDC immunization schedule',
2729
+ growthCharts: 'WHO (< 2 years) and CDC (≥ 2 years)',
2730
+ developmentalMilestones: 'CDC milestone checklist'
2731
+ }
2732
+ };
2733
+ });
2734
+ }
2735
+ async function runPrenatalCare() {
2736
+ return runToolAction('prenatal-care', async () => {
2737
+ const visits = [
2738
+ { timing: 'First visit (< 12 weeks)', tests: 'Dating US, CBC, blood type, rubella, HIV, HBV, syphilis, urine culture' },
2739
+ { timing: '10-13 weeks', tests: 'First trimester screen (NT, PAPP-A, hCG) or cfDNA' },
2740
+ { timing: '15-20 weeks', tests: 'Quad screen if not done earlier, AFP' },
2741
+ { timing: '18-22 weeks', tests: 'Anatomy ultrasound' },
2742
+ { timing: '24-28 weeks', tests: 'Glucose tolerance test, repeat CBC, Rh antibody' },
2743
+ { timing: '35-37 weeks', tests: 'Group B strep culture' },
2744
+ { timing: '36+ weeks', tests: 'Weekly visits, fetal position, cervical exam if indicated' }
2745
+ ];
2746
+ const supplements = [
2747
+ { supplement: 'Folic acid', dose: '400-800 mcg daily (start before conception)' },
2748
+ { supplement: 'Prenatal vitamin', dose: 'Daily' },
2749
+ { supplement: 'Iron', dose: '27 mg daily (in prenatal)' },
2750
+ { supplement: 'DHA/Omega-3', dose: '200-300 mg daily' },
2751
+ { supplement: 'Vitamin D', dose: '600 IU daily' }
2752
+ ];
2753
+ const warningsSigns = [
2754
+ 'Vaginal bleeding', 'Severe headache', 'Visual changes', 'Severe abdominal pain',
2755
+ 'Decreased fetal movement', 'Leaking fluid', 'Contractions < 37 weeks'
2756
+ ];
2757
+ const checks = [
2758
+ ...visits.map(v => ({ name: v.timing, ok: true, detail: v.tests })),
2759
+ ...supplements.map(s => ({ name: s.supplement, ok: true, detail: s.dose }))
2760
+ ];
2761
+ return {
2762
+ summary: `${visits.length} prenatal visits, ${supplements.length} recommended supplements`,
2763
+ checks,
2764
+ metrics: {
2765
+ visitFrequency: 'Monthly until 28 wks, q2wks 28-36, weekly 36+',
2766
+ weightGain: 'Varies by pre-pregnancy BMI (25-35 lbs normal weight)',
2767
+ urgentSymptoms: warningsSigns.length
2768
+ }
2769
+ };
2770
+ });
2771
+ }
2772
+ async function runMenopauseManagement() {
2773
+ return runToolAction('menopause-management', async () => {
2774
+ const symptoms = [
2775
+ { symptom: 'Vasomotor (hot flashes)', prevalence: '75%', duration: 'Average 7 years' },
2776
+ { symptom: 'Genitourinary syndrome', prevalence: '50%', duration: 'Progressive without treatment' },
2777
+ { symptom: 'Sleep disturbance', prevalence: '40-60%', duration: 'Variable' },
2778
+ { symptom: 'Mood changes', prevalence: '20-40%', duration: 'Often perimenopausal' },
2779
+ { symptom: 'Cognitive changes', prevalence: 'Common', duration: 'Often improves post-menopause' }
2780
+ ];
2781
+ const treatments = [
2782
+ { treatment: 'Hormone therapy (systemic)', indication: 'Vasomotor symptoms, age < 60 or < 10 years post-meno' },
2783
+ { treatment: 'Vaginal estrogen', indication: 'Genitourinary syndrome, minimal systemic absorption' },
2784
+ { treatment: 'SSRIs/SNRIs', indication: 'Hot flashes, mood symptoms' },
2785
+ { treatment: 'Gabapentin', indication: 'Hot flashes, especially if sleep issues' },
2786
+ { treatment: 'Ospemifene', indication: 'Genitourinary syndrome (SERM)' },
2787
+ { treatment: 'Fezolinetant', indication: 'Hot flashes (NK3 antagonist, non-hormonal)' }
2788
+ ];
2789
+ const contraindications = [
2790
+ 'Breast cancer history', 'Endometrial cancer', 'DVT/PE history', 'Stroke or MI', 'Active liver disease'
2791
+ ];
2792
+ const checks = [
2793
+ ...symptoms.map(s => ({ name: s.symptom, ok: true, detail: `${s.prevalence}, ${s.duration}` })),
2794
+ ...treatments.map(t => ({ name: t.treatment, ok: true, detail: t.indication }))
2795
+ ];
2796
+ return {
2797
+ summary: `${symptoms.length} symptoms, ${treatments.length} treatment options`,
2798
+ checks,
2799
+ metrics: {
2800
+ htTiming: 'Initiate < 60 years old or < 10 years post-menopause',
2801
+ htDuration: 'Reassess annually, use lowest effective dose',
2802
+ boneLoss: 'Accelerated in first 5 years post-menopause'
2803
+ }
2804
+ };
2805
+ });
2806
+ }
2807
+ async function runProstateHealth() {
2808
+ return runToolAction('prostate-health', async () => {
2809
+ const conditions = [
2810
+ { condition: 'BPH', prevalence: '50% by age 60, 90% by age 85', symptoms: 'LUTS, hesitancy, frequency' },
2811
+ { condition: 'Prostatitis', prevalence: '5-10% lifetime', symptoms: 'Pelvic pain, dysuria, fever (acute)' },
2812
+ { condition: 'Prostate cancer', prevalence: '1 in 8 men', screening: 'Shared decision-making for PSA' }
2813
+ ];
2814
+ const luts = [
2815
+ { symptom: 'Weak stream', category: 'Voiding' },
2816
+ { symptom: 'Hesitancy', category: 'Voiding' },
2817
+ { symptom: 'Intermittency', category: 'Voiding' },
2818
+ { symptom: 'Frequency', category: 'Storage' },
2819
+ { symptom: 'Urgency', category: 'Storage' },
2820
+ { symptom: 'Nocturia', category: 'Storage' }
2821
+ ];
2822
+ const bphTreatment = [
2823
+ { class: 'Alpha blockers', examples: 'Tamsulosin, alfuzosin', mechanism: 'Relax smooth muscle' },
2824
+ { class: '5-alpha reductase inhibitors', examples: 'Finasteride, dutasteride', mechanism: 'Reduce prostate size' },
2825
+ { class: 'PDE5 inhibitors', examples: 'Tadalafil', mechanism: 'Also helps ED' },
2826
+ { class: 'Surgical (TURP)', examples: 'Gold standard for large prostate', mechanism: 'Resection' },
2827
+ { class: 'Minimally invasive', examples: 'UroLift, Rezum, aquablation', mechanism: 'Various' }
2828
+ ];
2829
+ const checks = [
2830
+ ...conditions.map(c => ({ name: c.condition, ok: true, detail: c.prevalence })),
2831
+ ...bphTreatment.map(b => ({ name: b.class, ok: true, detail: b.examples }))
2832
+ ];
2833
+ return {
2834
+ summary: `${conditions.length} prostate conditions, ${bphTreatment.length} BPH treatments`,
2835
+ checks,
2836
+ metrics: {
2837
+ psaSharedDecision: 'Age 55-69, discuss benefits/harms',
2838
+ ipss: 'International Prostate Symptom Score for LUTS severity',
2839
+ referralIndications: 'Elevated PSA, hematuria, urinary retention'
2840
+ }
2841
+ };
2842
+ });
2843
+ }
2844
+ async function runTravelHealth() {
2845
+ return runToolAction('travel-health', async () => {
2846
+ const vaccines = [
2847
+ { vaccine: 'Yellow fever', regions: 'Sub-Saharan Africa, South America', notes: 'Required for entry to some countries' },
2848
+ { vaccine: 'Typhoid', regions: 'South Asia, developing countries', notes: 'Oral or injectable' },
2849
+ { vaccine: 'Hepatitis A', regions: 'Developing countries', notes: 'If not immune' },
2850
+ { vaccine: 'Hepatitis B', regions: 'All travelers if not vaccinated', notes: 'Also occupational/sexual exposure' },
2851
+ { vaccine: 'Japanese encephalitis', regions: 'Rural Asia', notes: 'Extended travel' },
2852
+ { vaccine: 'Rabies', regions: 'High-risk activities or limited access to care', notes: 'Pre-exposure prophylaxis' },
2853
+ { vaccine: 'Meningococcal', regions: 'Meningitis belt (Africa), Hajj', notes: 'Quadrivalent' },
2854
+ { vaccine: 'Cholera', regions: 'Endemic areas', notes: 'Oral vaccine' }
2855
+ ];
2856
+ const malariaRegimens = [
2857
+ { drug: 'Atovaquone-proguanil (Malarone)', schedule: 'Start 1-2 days before, during, 7 days after' },
2858
+ { drug: 'Doxycycline', schedule: 'Start 1-2 days before, during, 28 days after' },
2859
+ { drug: 'Mefloquine', schedule: 'Start 2 weeks before, during, 4 weeks after' },
2860
+ { drug: 'Chloroquine', schedule: 'Only for chloroquine-sensitive areas' }
2861
+ ];
2862
+ const generalAdvice = [
2863
+ 'Safe water and food practices',
2864
+ 'Insect precautions (repellent, bed nets, clothing)',
2865
+ 'Sun protection',
2866
+ 'Altitude sickness prevention if applicable',
2867
+ 'Travel insurance with medical evacuation'
2868
+ ];
2869
+ const checks = [
2870
+ ...vaccines.map(v => ({ name: v.vaccine, ok: true, detail: v.regions })),
2871
+ ...malariaRegimens.map(m => ({ name: m.drug, ok: true, detail: m.schedule }))
2872
+ ];
2873
+ return {
2874
+ summary: `${vaccines.length} travel vaccines, ${malariaRegimens.length} malaria prophylaxis options`,
2875
+ checks,
2876
+ metrics: {
2877
+ consultTiming: 'Ideally 4-6 weeks before travel',
2878
+ cdcResource: 'wwwnc.cdc.gov/travel for country-specific recommendations',
2879
+ travelerssDiarrhea: 'Azithromycin or fluoroquinolone for treatment'
2880
+ }
2881
+ };
2882
+ });
2883
+ }
2884
+ async function runOccupationalHealth() {
2885
+ return runToolAction('occupational-health', async () => {
2886
+ const hazards = [
2887
+ { hazard: 'Noise exposure', industries: 'Construction, manufacturing', surveillance: 'Audiometry annually' },
2888
+ { hazard: 'Respiratory exposures', industries: 'Mining, construction, healthcare', surveillance: 'Spirometry, chest X-ray' },
2889
+ { hazard: 'Lead exposure', industries: 'Battery manufacturing, painting', surveillance: 'Blood lead levels' },
2890
+ { hazard: 'Ergonomic', industries: 'Office, manufacturing', surveillance: 'MSK assessment' },
2891
+ { hazard: 'Bloodborne pathogens', industries: 'Healthcare', surveillance: 'HBV vaccine, post-exposure protocol' },
2892
+ { hazard: 'Radiation', industries: 'Healthcare, nuclear', surveillance: 'Dosimetry, thyroid monitoring' },
2893
+ { hazard: 'Chemical exposures', industries: 'Various', surveillance: 'Biomonitoring per agent' }
2894
+ ];
2895
+ const requirements = [
2896
+ { requirement: 'Pre-placement exam', purpose: 'Baseline health, fitness for duty' },
2897
+ { requirement: 'Periodic surveillance', purpose: 'Monitor for occupational illness' },
2898
+ { requirement: 'Return to work', purpose: 'Assess fitness after illness/injury' },
2899
+ { requirement: 'Respirator clearance', purpose: 'Medical evaluation for respirator use' },
2900
+ { requirement: 'DOT physical', purpose: 'Commercial driver fitness' }
2901
+ ];
2902
+ const checks = [
2903
+ ...hazards.map(h => ({ name: h.hazard, ok: true, detail: `${h.industries}` })),
2904
+ ...requirements.map(r => ({ name: r.requirement, ok: true, detail: r.purpose }))
2905
+ ];
2906
+ return {
2907
+ summary: `${hazards.length} occupational hazards, ${requirements.length} exam types`,
2908
+ checks,
2909
+ metrics: {
2910
+ oshaRecordkeeping: 'Log 300 for work-related injuries/illnesses',
2911
+ nioshtopic: 'Total Worker Health - integrates safety with wellness',
2912
+ workersComp: 'Report work injuries within required timeframe'
2913
+ }
2914
+ };
2915
+ });
2916
+ }
2917
+ async function runEnvironmentalHealth() {
2918
+ return runToolAction('environmental-health', async () => {
2919
+ const exposures = [
2920
+ { exposure: 'Air pollution', health: 'Respiratory, cardiovascular', mitigation: 'Air purifiers, avoid outdoor activity on high days' },
2921
+ { exposure: 'Lead (housing)', health: 'Neurodevelopmental (children)', mitigation: 'Paint abatement, testing' },
2922
+ { exposure: 'Radon', health: 'Lung cancer (2nd leading cause)', mitigation: 'Home testing, mitigation systems' },
2923
+ { exposure: 'Arsenic (water)', health: 'Cancer, cardiovascular', mitigation: 'Water testing, filtration' },
2924
+ { exposure: 'Pesticides', health: 'Neurologic, cancer', mitigation: 'Wash produce, limit exposure' },
2925
+ { exposure: 'PFAS', health: 'Cancer, thyroid, immune', mitigation: 'Water filtration, avoid certain products' },
2926
+ { exposure: 'Mold', health: 'Respiratory, allergic', mitigation: 'Moisture control, remediation' }
2927
+ ];
2928
+ const climateHealth = [
2929
+ { effect: 'Heat-related illness', populations: 'Elderly, outdoor workers, athletes' },
2930
+ { effect: 'Air quality (wildfires)', populations: 'Respiratory disease, children, elderly' },
2931
+ { effect: 'Vector-borne diseases', populations: 'Expanding geographic range' },
2932
+ { effect: 'Extreme weather', populations: 'Mental health impacts, displacement' }
2933
+ ];
2934
+ const checks = [
2935
+ ...exposures.map(e => ({ name: e.exposure, ok: true, detail: `Health: ${e.health}` })),
2936
+ ...climateHealth.map(c => ({ name: c.effect, ok: true, detail: c.populations }))
2937
+ ];
2938
+ return {
2939
+ summary: `${exposures.length} environmental exposures, ${climateHealth.length} climate effects`,
2940
+ checks,
2941
+ metrics: {
2942
+ radonTesting: 'EPA recommends all homes be tested',
2943
+ leadTesting: 'Required in homes built before 1978 with children',
2944
+ airQualityIndex: 'Check AQI daily, especially for sensitive groups'
2945
+ }
2946
+ };
2947
+ });
2948
+ }
2949
+ async function runLongevityAssessment() {
2950
+ return runToolAction('longevity-assessment', async () => {
2951
+ const pillars = [
2952
+ { pillar: 'Nutrition', strategies: 'Mediterranean diet, intermittent fasting, caloric moderation' },
2953
+ { pillar: 'Exercise', strategies: '150+ min aerobic, resistance training, HIIT' },
2954
+ { pillar: 'Sleep', strategies: '7-9 hours, consistent schedule, sleep hygiene' },
2955
+ { pillar: 'Stress management', strategies: 'Mindfulness, social connection, purpose' },
2956
+ { pillar: 'Social connection', strategies: 'Strong relationships, community involvement' },
2957
+ { pillar: 'Cognitive engagement', strategies: 'Lifelong learning, mental challenges' },
2958
+ { pillar: 'Preventive care', strategies: 'Age-appropriate screenings, vaccinations' },
2959
+ { pillar: 'Avoid toxins', strategies: 'No smoking, limit alcohol, clean environment' }
2960
+ ];
2961
+ const biomarkers = [
2962
+ { marker: 'Blood pressure', target: '< 120/80 mmHg', relevance: 'CV mortality' },
2963
+ { marker: 'Fasting glucose', target: '< 100 mg/dL', relevance: 'Diabetes, CV risk' },
2964
+ { marker: 'LDL cholesterol', target: '< 100 mg/dL', relevance: 'CV disease' },
2965
+ { marker: 'HbA1c', target: '< 5.7%', relevance: 'Glycemic control' },
2966
+ { marker: 'hs-CRP', target: '< 1 mg/L', relevance: 'Inflammation' },
2967
+ { marker: 'Vitamin D', target: '30-50 ng/mL', relevance: 'Bone, immune health' },
2968
+ { marker: 'Body composition', target: 'BMI 18.5-24.9, low visceral fat', relevance: 'Metabolic health' },
2969
+ { marker: 'VO2 max', target: 'Above average for age', relevance: 'Cardiorespiratory fitness' }
2970
+ ];
2971
+ const checks = [
2972
+ ...pillars.map(p => ({ name: p.pillar, ok: true, detail: p.strategies })),
2973
+ ...biomarkers.map(b => ({ name: b.marker, ok: true, detail: `Target: ${b.target}` }))
2974
+ ];
2975
+ return {
2976
+ summary: `${pillars.length} longevity pillars, ${biomarkers.length} biomarkers`,
2977
+ checks,
2978
+ metrics: {
2979
+ blueZones: 'Ikaria, Okinawa, Sardinia, Nicoya, Loma Linda',
2980
+ lifeExpectancy: 'Modifiable factors account for ~25% of longevity',
2981
+ healthspan: 'Quality of life years, not just quantity'
2982
+ }
2983
+ };
2984
+ });
2985
+ }
2986
+ async function runHealthOptimization() {
2987
+ return runToolAction('health-optimization', async () => {
2988
+ const domains = [
2989
+ { domain: 'Cardiovascular', optimizations: 'Exercise, nutrition, BP/lipid control, stress management' },
2990
+ { domain: 'Metabolic', optimizations: 'Weight management, glucose control, reduce visceral fat' },
2991
+ { domain: 'Musculoskeletal', optimizations: 'Resistance training, protein intake, vitamin D, flexibility' },
2992
+ { domain: 'Neurological', optimizations: 'Sleep, cognitive stimulation, social engagement, exercise' },
2993
+ { domain: 'Immune', optimizations: 'Vaccines, sleep, stress reduction, nutrition, exercise' },
2994
+ { domain: 'Gastrointestinal', optimizations: 'Fiber, probiotics, hydration, regular meals' },
2995
+ { domain: 'Hormonal', optimizations: 'Sleep, stress management, exercise, healthy weight' },
2996
+ { domain: 'Psychological', optimizations: 'Therapy, mindfulness, social connection, purpose' }
2997
+ ];
2998
+ const actionItems = [
2999
+ 'Complete age-appropriate preventive screenings',
3000
+ 'Optimize sleep (7-9 hours, consistent schedule)',
3001
+ '150+ min moderate aerobic + 2x strength training weekly',
3002
+ 'Mediterranean-style diet, limit processed foods',
3003
+ 'Maintain healthy weight (BMI 18.5-24.9)',
3004
+ 'No smoking, limit alcohol (≤ 1-2 drinks/day)',
3005
+ 'Stress management practice daily',
3006
+ 'Strong social connections',
3007
+ 'Stay current on vaccinations',
3008
+ 'Annual wellness visit with primary care'
3009
+ ];
3010
+ const checks = domains.map(d => ({
3011
+ name: d.domain,
3012
+ ok: true,
3013
+ detail: d.optimizations
3014
+ }));
3015
+ return {
3016
+ summary: `${domains.length} health domains, ${actionItems.length} action items`,
3017
+ checks,
3018
+ metrics: {
3019
+ weeklyExercise: '150+ min moderate aerobic + 2x resistance',
3020
+ sleepTarget: '7-9 hours per night',
3021
+ dietPattern: 'Mediterranean, DASH, or plant-forward',
3022
+ stressManagement: 'Daily practice (meditation, breathing, etc.)'
3023
+ }
3024
+ };
3025
+ });
3026
+ }
3027
+ async function runAllTools(context) {
3028
+ const start = Date.now();
3029
+ const allReports = [];
3030
+ const toolIds = CLI_TOOLS.filter(t => t.id !== 'all').map(t => t.id);
3031
+ for (const id of toolIds) {
3032
+ const tool = CLI_TOOLS.find(t => t.id === id);
3033
+ if (tool) {
3034
+ try {
3035
+ const report = await tool.run(context, []);
3036
+ allReports.push(report);
3037
+ }
3038
+ catch {
3039
+ allReports.push({
3040
+ toolId: id,
3041
+ ok: false,
3042
+ summary: 'Tool execution failed',
3043
+ durationMs: 0
3044
+ });
3045
+ }
3046
+ }
3047
+ }
3048
+ const passed = allReports.filter(r => r.ok).length;
3049
+ const failed = allReports.filter(r => !r.ok).length;
3050
+ const checks = allReports.map(r => ({
3051
+ name: r.toolId,
3052
+ ok: r.ok,
3053
+ detail: r.summary
3054
+ }));
3055
+ return {
3056
+ toolId: 'all',
3057
+ ok: failed === 0,
3058
+ summary: `${passed}/${allReports.length} tools passed`,
3059
+ durationMs: Date.now() - start,
3060
+ checks,
3061
+ metrics: {
3062
+ totalTools: allReports.length,
3063
+ passed,
3064
+ failed,
3065
+ totalDurationMs: Date.now() - start
3066
+ }
3067
+ };
3068
+ }
3069
+ export function listCliTools() {
3070
+ return CLI_TOOLS;
3071
+ }
3072
+ export function getCliTool(id) {
3073
+ return CLI_TOOLS.find(tool => tool.id === id);
3074
+ }
3075
+ //# sourceMappingURL=index.js.map