@peopl-health/nexus 5.51.0-dev.7631 → 5.51.0-dev.7633

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +0 -21
  2. package/lib/clinical/AssistantProcessor.js +12 -156
  3. package/lib/clinical/context/ToolRuntimeContext.js +1 -39
  4. package/lib/clinical/context/turnContext.js +0 -10
  5. package/lib/clinical/models/triageRecommendationEventModel.js +0 -28
  6. package/lib/clinical/providers/BaseLLMProvider.js +5 -45
  7. package/lib/clinical/services/clinicalAirtableService.js +5 -8
  8. package/lib/clinical/services/divergenceService.js +2 -9
  9. package/lib/clinical/services/triageRecommendationService.js +251 -453
  10. package/lib/clinical/tools/deliverPatientMessageTool.js +23 -82
  11. package/lib/clinical/tools/registerClinicalTools.js +0 -2
  12. package/lib/controllers/dashboardController.js +2 -5
  13. package/lib/controllers/escalationReviewController.js +12 -0
  14. package/lib/core/BatchingManager.js +9 -20
  15. package/lib/core/NexusMessaging.js +6 -25
  16. package/lib/core/ProcessingPipeline.js +3 -32
  17. package/lib/index.d.ts +6 -334
  18. package/lib/index.js +0 -22
  19. package/lib/models/escalationReviewModel.js +4 -0
  20. package/lib/routes/index.js +2 -0
  21. package/lib/services/airtableService.js +1 -8
  22. package/lib/services/dashboardService.js +3 -30
  23. package/lib/services/escalationReviewService.js +43 -11
  24. package/package.json +1 -1
  25. package/lib/clinical/models/supportCandidateModel.js +0 -90
  26. package/lib/clinical/services/deliverySettlementService.js +0 -39
  27. package/lib/clinical/services/supportActionService.js +0 -129
  28. package/lib/clinical/services/supportCandidateService.js +0 -532
  29. package/lib/clinical/services/supportRoutingAgentService.js +0 -118
  30. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +0 -200
  31. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +0 -141
  32. package/lib/core/runtimeToolPolicy.js +0 -3
  33. package/lib/services/dashboard-provider-registry.js +0 -38
  34. package/lib/shared/dtos/NutritionSafetyDecision.js +0 -128
  35. package/lib/shared/dtos/SupportAction.js +0 -28
  36. package/lib/shared/dtos/SupportRoutingRecommendation.js +0 -124
package/lib/index.d.ts CHANGED
@@ -2,14 +2,9 @@ declare module '@peopl-health/nexus' {
2
2
  // Core Types
3
3
  export interface MessageData {
4
4
  id?: string;
5
- messageId?: string;
6
- message_id?: string;
7
5
  from: string;
8
6
  code?: string;
9
- body?: string;
10
7
  message?: string;
11
- timestamp?: string | Date;
12
- createdAt?: string | Date;
13
8
  fileUrl?: string;
14
9
  fileType?: 'text' | 'image' | 'document' | 'audio' | 'video';
15
10
  contentSid?: string;
@@ -235,7 +230,7 @@ declare module '@peopl-health/nexus' {
235
230
  }
236
231
 
237
232
  export class NexusMessaging {
238
- constructor(config?: NexusMessagingConfig);
233
+ constructor(config?: any);
239
234
  initializeProvider(providerType: 'twilio' | 'baileys', providerConfig: TwilioConfig | BaileysConfig): Promise<void>;
240
235
  setMessageStorage(storage: any): void;
241
236
  setHandlers(handlers: MessageHandlers): void;
@@ -306,7 +301,7 @@ declare module '@peopl-health/nexus' {
306
301
 
307
302
  // Main Nexus Class
308
303
  export interface NexusConfig {
309
- messaging?: NexusMessagingConfig;
304
+ messaging?: any;
310
305
  }
311
306
 
312
307
  export interface NerOptions {
@@ -665,208 +660,6 @@ declare module '@peopl-health/nexus' {
665
660
  export function getPatientMemory(): any;
666
661
  export function getConversationSummary(): any;
667
662
 
668
- export type SupportService = 'nutrition' | 'psychology';
669
- export type SupportDisposition = 'group' | 'individual' | 'escalated' | 'reviewRequired' | 'none';
670
- export type SupportPriority = 'routine' | 'soon' | 'urgent';
671
- export type SupportInvitationClass = 'first' | 'followup';
672
- export type SupportDeliveryStatus = 'sent' | 'delivered' | 'read' | 'failed' | 'unknown';
673
- export type SupportEngagementState = 'notInvited' | 'invited' | 'registered' | 'attended' | 'declined';
674
-
675
- export interface SupportEvidenceInput {
676
- source: 'triage' | 'chat' | 'fhir' | 'airtable';
677
- sourceId: string;
678
- code: string;
679
- summary?: string | null;
680
- confidence?: number | null;
681
- }
682
-
683
- export interface SupportEvidence extends SupportEvidenceInput {
684
- key?: string;
685
- summary: string | null;
686
- confidence: number | null;
687
- }
688
-
689
- export interface SupportSafety {
690
- suicidalIdeation?: boolean;
691
- immediateRisk?: boolean;
692
- urgentMedicalRisk?: boolean;
693
- needsHumanConfirmation?: boolean;
694
- }
695
-
696
- export interface SupportRoutingDecisionBaseInput {
697
- disposition: SupportDisposition;
698
- groupEligible: boolean;
699
- priority?: SupportPriority;
700
- confidence: number;
701
- reasonCodes?: string[];
702
- evidence: SupportEvidenceInput[];
703
- safety: SupportSafety;
704
- }
705
-
706
- export type SupportRoutingDecisionInput = SupportRoutingDecisionBaseInput & ({
707
- service: 'nutrition';
708
- nutritionRisk: 'green' | 'yellow' | 'red' | 'unknown';
709
- urgentIntakeEligible: boolean;
710
- } | {
711
- service: 'psychology';
712
- psychologyRisk: 'green' | 'orange' | 'red' | 'unknown';
713
- });
714
-
715
- export interface SupportRoutingRecommendationInput {
716
- schemaVersion?: string;
717
- decisionVersion?: string;
718
- patientId: string;
719
- origin: 'triage' | 'chat' | 'fhir';
720
- sourceId: string;
721
- createdAt: string;
722
- decisions: SupportRoutingDecisionInput[];
723
- }
724
-
725
- export interface SupportCandidateRecord {
726
- candidateId: string;
727
- patientId: string;
728
- service: SupportService;
729
- disposition: SupportDisposition;
730
- groupEligible: boolean;
731
- urgentIntakeEligible: boolean;
732
- priority: SupportPriority;
733
- confidence?: number;
734
- nutritionRisk?: 'green' | 'yellow' | 'red' | 'unknown' | null;
735
- psychologyRisk?: 'green' | 'orange' | 'red' | 'unknown' | null;
736
- reasonCodes?: string[];
737
- evidence?: SupportEvidence[];
738
- sourceEventIds?: string[];
739
- activeInvitationKey?: string | null;
740
- cooldownInvitationKey?: string | null;
741
- revision?: number;
742
- [key: string]: unknown;
743
- }
744
-
745
- export interface SupportActionRecord {
746
- candidateId: string;
747
- service: SupportService;
748
- type: 'group_registration' | 'urgent_nutrition_intake';
749
- invitationClass: SupportInvitationClass | null;
750
- idempotencyKey?: string | null;
751
- targetKey: string;
752
- priority: SupportPriority;
753
- }
754
-
755
- export interface SupportActionResult {
756
- schemaVersion: '1';
757
- patientId: string;
758
- sourceId: string;
759
- actions: SupportActionRecord[];
760
- }
761
-
762
- export interface SupportDeliveryContext {
763
- invitationClassByService?: Partial<Record<SupportService, SupportInvitationClass>>;
764
- targetKeyByService?: Partial<Record<SupportService, string>>;
765
- attendanceEvidenceByService?: Partial<Record<SupportService, {
766
- patientId: string;
767
- service: SupportService;
768
- evidenceId: string;
769
- }>>;
770
- }
771
-
772
- export interface SupportDashboardMetric {
773
- records: Array<Record<string, unknown>>;
774
- indicator: number;
775
- sample: number;
776
- total: number;
777
- struct: string[];
778
- }
779
-
780
- export interface SupportDashboardSnapshot {
781
- generatedAt: string;
782
- metrics: { exceptions: SupportDashboardMetric };
783
- }
784
-
785
- export type SupportDashboardCandidateRecord = Pick<SupportCandidateRecord,
786
- 'candidateId' | 'patientId' | 'service' | 'disposition'
787
- > & Partial<SupportCandidateRecord>;
788
-
789
- export function registerDashboardProvider(
790
- source: 'auna.support.v1',
791
- provider: (context: { now: Date }) => SupportDashboardSnapshot | Promise<SupportDashboardSnapshot>
792
- ): void;
793
-
794
- export const supportCandidateService: {
795
- updateSupportOperationalReview(request: {
796
- patientId: string;
797
- service: SupportService;
798
- reasonCode: 'classification_failed' | 'attendance_unavailable' | 'safety_unconfirmed' | 'classification_safety_unconfirmed' | 'invitation_claim_failed';
799
- sourceId: string;
800
- resolved?: boolean;
801
- noClinicalDecision?: boolean;
802
- now?: Date;
803
- }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
804
- readSupportDashboardCandidates(): Promise<SupportDashboardCandidateRecord[]>;
805
- approveCandidate(candidateId: string, options: {
806
- reviewedRevision: number;
807
- reviewedRisk: 'green' | 'yellow';
808
- Model?: unknown;
809
- }): Promise<SupportCandidateRecord | null>;
810
- candidatePatch(existing: SupportCandidateRecord | null | undefined, recommendation: SupportRoutingRecommendationInput, decision: SupportRoutingDecisionInput): Partial<SupportCandidateRecord>;
811
- claimInvitation(request: {
812
- candidateId: string;
813
- invitationClass: SupportInvitationClass;
814
- invitationCycle: string;
815
- templateVersion: string;
816
- now?: Date;
817
- }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
818
- clearCandidateEscalation(candidateId: string, options: {
819
- reviewedRevision: number;
820
- approvedForGroup?: boolean;
821
- reviewedRisk?: 'green' | 'yellow';
822
- Model?: unknown;
823
- }): Promise<SupportCandidateRecord | null>;
824
- evidenceKey(item: Pick<SupportEvidence, 'source' | 'sourceId' | 'code'>): string;
825
- initialState(decision: SupportRoutingDecisionInput): SupportDisposition;
826
- markCandidateAccepted(request: { patientId: string; service: SupportService; sessionId?: string | null }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
827
- markCandidateDeclined(request: { patientId: string; service: SupportService; preference?: 'another_date' | 'not_now' | 'never' }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
828
- nextState(existing: SupportCandidateRecord | null | undefined, decision: SupportRoutingDecisionInput): SupportDisposition;
829
- normalizeEvidence(items?: SupportEvidenceInput[]): Array<SupportEvidence & { key: string }>;
830
- recordEngagement(request: {
831
- patientId: string;
832
- service: SupportService;
833
- state: SupportEngagementState;
834
- evidenceId?: string | null;
835
- occurredAt?: string | Date | null;
836
- preference?: 'another_date' | 'not_now' | 'never' | null;
837
- }, options?: { Model?: unknown; historicalAttendance?: boolean }): Promise<SupportCandidateRecord | null>;
838
- recordLegacyInvitationResponse(request: {
839
- patientId: string;
840
- service: SupportService;
841
- outcome: 'accepted' | 'declined';
842
- sessionId?: string | null;
843
- preference?: 'another_date' | 'not_now' | 'never';
844
- }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
845
- recordSupportRoutingRecommendation(recommendation: SupportRoutingRecommendationInput, options?: { Model?: unknown }): Promise<SupportCandidateRecord[]>;
846
- rescheduleDeclinedCandidate(candidateId: string, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
847
- settleInvitation(request: {
848
- candidateId: string;
849
- idempotencyKey: string;
850
- status: SupportDeliveryStatus;
851
- providerMessageId?: string | null;
852
- error?: string | null;
853
- now?: Date;
854
- }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
855
- };
856
-
857
- export const supportActionService: {
858
- prepareSupportAction(request: {
859
- patientId: string;
860
- sourceId: string;
861
- candidates?: SupportCandidateRecord[];
862
- resolveDeliveryContext?: (context: {
863
- patientId: string;
864
- candidates: SupportCandidateRecord[];
865
- }) => SupportDeliveryContext | Promise<SupportDeliveryContext>;
866
- now?: Date;
867
- }, options?: { Model?: unknown }): Promise<SupportActionResult | null>;
868
- };
869
-
870
663
  // BatchingManager — per-chatId concurrency control
871
664
  export interface BatchingConfig {
872
665
  enabled?: boolean;
@@ -876,118 +669,6 @@ declare module '@peopl-health/nexus' {
876
669
  hooks?: Record<string, Function | Function[]>;
877
670
  }
878
671
 
879
- export type NutritionSafetyFindingCode =
880
- | 'cannot_eat'
881
- | 'cannot_keep_fluids'
882
- | 'bleeding'
883
- | 'severe_abdominal_pain';
884
- export type NutritionSafetyFindingValue = 'yes' | 'no' | 'unknown';
885
- export type NutritionSafetyQuestionCode =
886
- | 'can_eat'
887
- | 'can_keep_fluids'
888
- | 'bleeding'
889
- | 'severe_abdominal_pain';
890
- export type NutritionSafetyEvidenceSourceType = 'chat' | 'flow' | 'historical' | 'forecast';
891
- export type NutritionSafetyDisposition = 'clear' | 'clarify' | 'escalate' | 'review_required';
892
-
893
- export interface NutritionSafetyEvidenceRefInput {
894
- finding: NutritionSafetyFindingCode;
895
- source_type: NutritionSafetyEvidenceSourceType;
896
- source_id: string;
897
- observed_at: string;
898
- }
899
-
900
- export interface NutritionSafetyEvidenceRef {
901
- finding: NutritionSafetyFindingCode;
902
- sourceType: NutritionSafetyEvidenceSourceType;
903
- sourceId: string;
904
- observedAt: string;
905
- traceId?: string;
906
- }
907
-
908
- export interface NutritionSafetyDecisionInput {
909
- submission_revision: number;
910
- screen_revision: number;
911
- findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
912
- evidence_refs: NutritionSafetyEvidenceRefInput[];
913
- questions_needed: NutritionSafetyQuestionCode[];
914
- disposition: NutritionSafetyDisposition;
915
- }
916
-
917
- export class NutritionSafetyDecision {
918
- constructor(payload: NutritionSafetyDecisionInput);
919
- submissionRevision: number;
920
- screenRevision: number;
921
- findings: Record<NutritionSafetyFindingCode, NutritionSafetyFindingValue>;
922
- evidenceRefs: NutritionSafetyEvidenceRef[];
923
- questionsNeeded: NutritionSafetyQuestionCode[];
924
- disposition: NutritionSafetyDisposition;
925
- }
926
-
927
- export interface NutritionSafetyDeliveryDirective {
928
- operationId: string;
929
- body: string;
930
- }
931
-
932
- export interface NutritionSafetyCommitRequest {
933
- decision: NutritionSafetyDecision;
934
- patientCode: string;
935
- turnId: string;
936
- traceId: string;
937
- sourceId: string;
938
- observedAt: string;
939
- }
940
-
941
- export interface NutritionSafetyCommitResult {
942
- outcome: string;
943
- status?: string;
944
- screen?: { status: string; [key: string]: any };
945
- questionsNeeded?: NutritionSafetyQuestionCode[];
946
- questions_needed?: NutritionSafetyQuestionCode[];
947
- deliveryDirective?: NutritionSafetyDeliveryDirective;
948
- }
949
-
950
- export interface NutritionSafetyRepository {
951
- commitDecision(request: NutritionSafetyCommitRequest): Promise<NutritionSafetyCommitResult>;
952
- claimDelivery?(request: {
953
- operationId: string;
954
- patientCode: string;
955
- turnId: string;
956
- traceId: string | null;
957
- sourceId: string | null;
958
- }): Promise<{ acquired: boolean }>;
959
- settleDelivery?(request: {
960
- operationId: string;
961
- outcome: 'sent' | 'known_not_sent' | 'unknown';
962
- providerMessageId: string | null;
963
- patientCode: string;
964
- turnId: string | null;
965
- traceId: string | null;
966
- }): Promise<boolean | void>;
967
- }
968
-
969
- export interface ToolRuntimeRepositories {
970
- nutritionSafety?: NutritionSafetyRepository;
971
- [key: string]: any;
972
- }
973
-
974
- export const FINDING_CODES: readonly NutritionSafetyFindingCode[];
975
- export const FINDING_VALUES: readonly NutritionSafetyFindingValue[];
976
- export const FINDING_TO_QUESTION: Readonly<Record<NutritionSafetyFindingCode, NutritionSafetyQuestionCode>>;
977
- export const QUESTION_CODES: readonly NutritionSafetyQuestionCode[];
978
- export const EVIDENCE_SOURCE_TYPES: readonly NutritionSafetyEvidenceSourceType[];
979
- export const DISPOSITIONS: readonly NutritionSafetyDisposition[];
980
-
981
- export interface NexusMessagingConfig {
982
- messageBatching?: BatchingConfig;
983
- assistant?: {
984
- mode?: 'local' | 'queue';
985
- toolRuntimeRepos?: ToolRuntimeRepositories;
986
- [key: string]: any;
987
- };
988
- [key: string]: any;
989
- }
990
-
991
672
  export interface DrainResult {
992
673
  drained: boolean;
993
674
  waitedMs: number;
@@ -1024,14 +705,12 @@ declare module '@peopl-health/nexus' {
1024
705
  handleBatchedProcessing(
1025
706
  chatId: string,
1026
707
  processingFn: (runId: string) => Promise<any>,
1027
- sendResponseFn: (result: any) => Promise<void>,
1028
- discardResponseFn?: (result: any) => Promise<void>
708
+ sendResponseFn: (result: any) => Promise<void>
1029
709
  ): Promise<TurnAdmission>;
1030
710
  enqueueProcessing(
1031
711
  chatId: string,
1032
712
  processingFn: (runId: string) => Promise<any>,
1033
- sendResponseFn: (result: any) => Promise<void>,
1034
- discardResponseFn?: (result: any) => Promise<void>
713
+ sendResponseFn: (result: any) => Promise<void>
1035
714
  ): Promise<TurnAdmission>;
1036
715
  }
1037
716
 
@@ -1040,9 +719,7 @@ declare module '@peopl-health/nexus' {
1040
719
  skip?: boolean;
1041
720
  additionalInstructions?: string;
1042
721
  additionalMessages?: Array<Record<string, any>>;
1043
- toolChoice?: string | Record<string, any> | null;
1044
- /** Registered tool ids to add for this turn only. Invalid ids are ignored and the list is capped at eight. */
1045
- additionalToolIds?: string[];
722
+ toolChoice?: Record<string, any> | null;
1046
723
  /** Recorded on the turn trace under `signals.consumer`; cannot collide with nexus-owned keys. */
1047
724
  signals?: Record<string, any>;
1048
725
  metadata?: Record<string, any>;
@@ -1061,8 +738,7 @@ declare module '@peopl-health/nexus' {
1061
738
  run(
1062
739
  context: ProcessingContext,
1063
740
  executeFn: (preProcessResult: PreProcessResult, shouldContinue: () => boolean) => Promise<any>,
1064
- shouldContinue?: () => boolean,
1065
- discardResult?: (result: any) => Promise<void>
741
+ shouldContinue?: () => boolean
1066
742
  ): Promise<any>;
1067
743
  }
1068
744
 
@@ -1080,7 +756,6 @@ declare module '@peopl-health/nexus' {
1080
756
  sendMessage?: (messageData: MessageData) => Promise<any>;
1081
757
  storeRunMetrics?: (code: string, thread: any, result: any, timings?: Record<string, any>) => Promise<void>;
1082
758
  llmMonitor?: { enqueueTurn(turnId: string): Promise<string | null> } | null;
1083
- toolRuntimeRepos?: ToolRuntimeRepositories;
1084
759
  }
1085
760
 
1086
761
  export interface ProcessInput {
@@ -1101,8 +776,6 @@ declare module '@peopl-health/nexus' {
1101
776
  predictionTimeMs?: number;
1102
777
  retries?: number;
1103
778
  completed?: boolean;
1104
- /** Internal delivery ownership receipt; never contains the directive body. */
1105
- deliveryDirective?: { operationId: string; claimed: boolean; settled: boolean };
1106
779
  }
1107
780
 
1108
781
  export class AssistantProcessor {
@@ -1112,7 +785,6 @@ declare module '@peopl-health/nexus' {
1112
785
  executeLLM(thread: any, assistant: any, runOptions?: AssistantRunOptions, message?: any): Promise<LLMResult>;
1113
786
  process(input: ProcessInput): Promise<LLMResult | null>;
1114
787
  sendResponse(code: string, result: any): Promise<string | null>;
1115
- discardResponse(code: string, result: any): Promise<boolean>;
1116
788
  }
1117
789
 
1118
790
  }
package/lib/index.js CHANGED
@@ -40,18 +40,6 @@ const { syncClinicalContext } = require('./clinical/services/contextSyncRunner')
40
40
  const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
41
41
  const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
42
42
  const { MapCache } = require('./utils/MapCache');
43
- const supportCandidateService = require('./clinical/services/supportCandidateService');
44
- const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
45
- const supportActionService = require('./clinical/services/supportActionService');
46
- const {
47
- NutritionSafetyDecision,
48
- FINDING_CODES,
49
- FINDING_VALUES,
50
- FINDING_TO_QUESTION,
51
- QUESTION_CODES,
52
- EVIDENCE_SOURCE_TYPES,
53
- DISPOSITIONS,
54
- } = require('./shared/dtos/NutritionSafetyDecision');
55
43
 
56
44
  class Nexus {
57
45
  constructor(config = {}) {
@@ -310,14 +298,4 @@ module.exports = {
310
298
  DefaultMemoryManager,
311
299
  EnhancedMemoryManager,
312
300
  MapCache,
313
- supportCandidateService,
314
- registerDashboardProvider,
315
- supportActionService,
316
- NutritionSafetyDecision,
317
- FINDING_CODES,
318
- FINDING_VALUES,
319
- FINDING_TO_QUESTION,
320
- QUESTION_CODES,
321
- EVIDENCE_SOURCE_TYPES,
322
- DISPOSITIONS,
323
301
  };
@@ -7,6 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
9
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
10
+ const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready'];
10
11
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
11
12
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
12
13
 
@@ -83,6 +84,7 @@ const escalationReviewSchema = new mongoose.Schema({
83
84
  'indications_queued',
84
85
  'indications_sent',
85
86
  'closed',
87
+ 'cancelled',
86
88
  ],
87
89
  default: 'open',
88
90
  },
@@ -100,6 +102,7 @@ const escalationReviewSchema = new mongoose.Schema({
100
102
 
101
103
  escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
102
104
  escalationReviewSchema.index({ activeCaseKey: 1 }, { unique: true, sparse: true });
105
+ escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
103
106
 
104
107
  const getEscalationReview = () => {
105
108
  const dbName = getModelDatabase('EscalationReview');
@@ -110,6 +113,7 @@ const getEscalationReview = () => {
110
113
 
111
114
  module.exports = {
112
115
  CALL_OUTCOMES,
116
+ CANCELLABLE_STATUSES,
113
117
  DECISION_SOURCES,
114
118
  DOCTOR_DECISIONS,
115
119
  HANDOFF_MODES,
@@ -126,6 +126,7 @@ const escalationReviewRouteDefinitions = {
126
126
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
127
127
  'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
128
128
  'POST /:id/close': 'closeEscalationReviewController',
129
+ 'POST /:id/cancel': 'cancelEscalationReviewController',
129
130
  'POST /:id/case-sync': 'syncEscalationReviewCaseController'
130
131
  };
131
132
 
@@ -285,6 +286,7 @@ const builtInControllers = {
285
286
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
286
287
  sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
287
288
  closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
289
+ cancelEscalationReviewController: escalationReviewController.cancelEscalationReviewController,
288
290
  syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
289
291
  };
290
292
 
@@ -195,16 +195,10 @@ async function patchUpsert(baseID, tableName, fields, mergeOn, apiKey) {
195
195
  }
196
196
  }
197
197
 
198
- async function upsertRecord(baseID, tableName, fields, options = {}, context = null) {
199
- const { mergeOn, retryNetworkErrors = true } = options;
200
-
198
+ async function upsertRecord(baseID, tableName, fields, { mergeOn } = {}, context = null) {
201
199
  if (!Array.isArray(mergeOn) || mergeOn.length === 0) {
202
200
  throw new Error('[upsertRecord] mergeOn must name the fields Airtable matches on');
203
201
  }
204
- if (Object.prototype.hasOwnProperty.call(options, 'retryNetworkErrors')
205
- && typeof options.retryNetworkErrors !== 'boolean') {
206
- throw new Error('[upsertRecord] retryNetworkErrors must be a boolean');
207
- }
208
202
 
209
203
  if (isShadowRun() || isBenchMode(context)) {
210
204
  logger.info(`[upsertRecord:${isShadowRun() ? 'shadow' : 'bench'}] Suppressed`, { tableName, code: context });
@@ -222,7 +216,6 @@ async function upsertRecord(baseID, tableName, fields, options = {}, context = n
222
216
  const data = await withAirtableRetry(
223
217
  () => patchUpsert(baseID, tableName, fields, mergeOn, apiKey),
224
218
  'upsertRecord',
225
- { retryNetworkErrors },
226
219
  );
227
220
  const record = data.records[0];
228
221
  const created = (data.createdRecords || []).includes(record.id);
@@ -5,7 +5,6 @@ const { fetchBoxesFromAirtable, fetchDetailsFromAirtable, attachPreview } = requ
5
5
  const { getMexicoDateRange, buildPatientMessagesPipeline, buildToolDistributionPipeline, mergeTrendData } = require('../helpers/trendHelper');
6
6
 
7
7
  const { aggregateMessages } = require('./messageService');
8
- const { validateDashboardSource, readDashboardProvider } = require('./dashboard-provider-registry');
9
8
 
10
9
  const boxCache = new MapCache({ maxSize: 100 });
11
10
  const detailCache = new MapCache({ maxSize: 100 });
@@ -17,7 +16,7 @@ async function seedCaches() {
17
16
  const boxes = await fetchBoxesFromAirtable();
18
17
  boxes.forEach(box => boxCache.set(box.id, box));
19
18
 
20
- const details = await fetchDetailsFromAirtable(boxes.filter(box => box.config?.source === undefined));
19
+ const details = await fetchDetailsFromAirtable(boxes);
21
20
  details.forEach(({ id, records }) => {
22
21
  detailCache.set(id, records);
23
22
  const box = boxCache.get(id);
@@ -41,23 +40,10 @@ async function ensureSeeded(force) {
41
40
 
42
41
  async function getAllBoxes(force) {
43
42
  await ensureSeeded(force);
44
- const snapshots = new Map();
45
- const now = new Date();
46
- return Promise.all(Array.from(boxCache.entries()).map(async ([id, { config, ...data }]) => {
47
- if (config?.source === undefined) return { id, ...data };
48
- validateDashboardSource(config);
49
- if (!snapshots.has(config.source)) snapshots.set(config.source, readDashboardProvider(config, now));
50
- const { records, struct: _struct, ...metric } = await snapshots.get(config.source);
51
- const box = { id, ...data, ...metric };
52
- attachPreview(box, records);
53
- return box;
54
- }));
43
+ return Array.from(boxCache.entries()).map(([id, { config: _config, ...data }]) => ({ id, ...data }));
55
44
  }
56
45
 
57
46
  async function getStatsById(cacheId) {
58
- await ensureSeeded(false);
59
- const config = boxCache.get(cacheId)?.config;
60
- if (config?.source !== undefined) return { id: cacheId, ...await readDashboardProvider(config, new Date()) };
61
47
  const detail = detailCache.get(cacheId);
62
48
  if (!detail) return null;
63
49
  const struct = boxCache.get(cacheId)?.config?.columns || [];
@@ -65,24 +51,11 @@ async function getStatsById(cacheId) {
65
51
  }
66
52
 
67
53
  async function updateBox(id, data) {
68
- if (!data.config || Object.keys(data.config).length === 0) {
69
- await ensureSeeded(false);
70
- data = { ...data, config: boxCache.get(id)?.config };
71
- }
72
- if (data.config?.source !== undefined) {
73
- validateDashboardSource(data.config);
74
- data = Object.fromEntries(Object.entries(data).filter(([key]) => ['id', 'title', 'type', 'metadata', 'config'].includes(key)));
75
- if (data.metadata) {
76
- const { preview: _preview, ...metadata } = data.metadata;
77
- data.metadata = metadata;
78
- }
79
- detailCache.delete(id);
80
- }
81
54
  boxCache.set(id, data);
82
55
  logger.info('[DashboardService] Box cache updated', { id });
83
56
 
84
57
  const box = boxCache.get(id);
85
- if (box?.config?.source === undefined && box?.config?.table) {
58
+ if (box?.config?.table) {
86
59
  const [detail] = await fetchDetailsFromAirtable([box]);
87
60
  if (detail) {
88
61
  detailCache.set(detail.id, detail.records);