@peopl-health/nexus 5.51.0-dev.7608 → 5.51.0-dev.7627
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/lib/clinical/AssistantProcessor.js +156 -12
- package/lib/clinical/context/ToolRuntimeContext.js +39 -1
- package/lib/clinical/context/turnContext.js +10 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +29 -0
- package/lib/clinical/providers/BaseLLMProvider.js +45 -5
- package/lib/clinical/services/clinicalAirtableService.js +8 -5
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/divergenceService.js +9 -2
- package/lib/clinical/services/supportActionService.js +129 -0
- package/lib/clinical/services/supportCandidateService.js +470 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/triageRecommendationService.js +456 -251
- package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
- package/lib/clinical/tools/registerClinicalTools.js +2 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +121 -0
- package/lib/controllers/dashboardController.js +5 -2
- package/lib/core/BatchingManager.js +20 -9
- package/lib/core/NexusMessaging.js +25 -6
- package/lib/core/ProcessingPipeline.js +32 -3
- package/lib/index.d.ts +325 -6
- package/lib/index.js +22 -0
- package/lib/services/airtableService.js +8 -1
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +30 -3
- package/lib/services/escalationReviewService.js +7 -7
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -137,6 +137,27 @@ The route helpers intentionally leave authentication to the host application. Mo
|
|
|
137
137
|
tenant authentication and authorization middleware before exposing them; patient routes return
|
|
138
138
|
protected health information and must never be public.
|
|
139
139
|
|
|
140
|
+
## Support-session routing
|
|
141
|
+
|
|
142
|
+
`supportCandidateService` is exported for consumers that coordinate first-session
|
|
143
|
+
nutrition and psychology invitations. Its candidate lifecycle provides atomic
|
|
144
|
+
invitation claims and one lifecycle per patient and service, including first-session
|
|
145
|
+
and follow-up invitations with cooldown enforcement.
|
|
146
|
+
|
|
147
|
+
Triage consumers opt into classification explicitly:
|
|
148
|
+
|
|
149
|
+
```js
|
|
150
|
+
handleTriageCompleted(payload, {
|
|
151
|
+
supportRouting: {
|
|
152
|
+
enabled: true,
|
|
153
|
+
autoEligible: false, // classify and persist without patient-facing automation
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Psychology routing enforces the specialist traffic light: green can enter a group,
|
|
159
|
+
orange routes to individual care first, and red routes to clinical escalation.
|
|
160
|
+
|
|
140
161
|
## Examples
|
|
141
162
|
|
|
142
163
|
General, illustrative examples meant to be copied into your own app:
|
|
@@ -13,6 +13,7 @@ const { cancelContingencies, snapshotContingencies } = require('./services/conti
|
|
|
13
13
|
const { readPendingFollowUpsForPatient, cancelPendingFollowUps } = require('./services/clinicalAirtableService');
|
|
14
14
|
const { isContingencyCancelOnReplyLive } = require('./flags/contingencyFlags');
|
|
15
15
|
const { maybeWarmPatientRisk } = require('./services/riskAssessmentService');
|
|
16
|
+
const { settleClaimedDelivery } = require('./services/deliverySettlementService');
|
|
16
17
|
const { ToolRuntimeContext } = require('./context/ToolRuntimeContext');
|
|
17
18
|
const { resolveTurnContext, TURN_KIND } = require('./context/turnContext');
|
|
18
19
|
|
|
@@ -31,9 +32,21 @@ const traceContingency = (net) => ({
|
|
|
31
32
|
patientFiresAfterSilenceMinutes: net?.patientReminder?.firesAfterSilenceMinutes ?? null,
|
|
32
33
|
});
|
|
33
34
|
|
|
35
|
+
const deliveryOutcome = (result) => {
|
|
36
|
+
if (result?.success === true
|
|
37
|
+
&& result?.delivered === true
|
|
38
|
+
&& typeof result?.messageId === 'string'
|
|
39
|
+
&& result.messageId) return 'sent';
|
|
40
|
+
if (result?.success === false
|
|
41
|
+
&& result?.delivered === false
|
|
42
|
+
&& result?.deferred !== true
|
|
43
|
+
&& result?.duplicate !== true) return 'known_not_sent';
|
|
44
|
+
return 'unknown';
|
|
45
|
+
};
|
|
46
|
+
|
|
34
47
|
class AssistantProcessor {
|
|
35
|
-
constructor({ mode = 'local', queueAdapter = null, sendMessage = null, phiProcessor = null, storeRunMetrics = null, llmMonitor = null }) {
|
|
36
|
-
Object.assign(this, { mode, queueAdapter, sendMessage, phiProcessor, storeRunMetrics, llmMonitor });
|
|
48
|
+
constructor({ mode = 'local', queueAdapter = null, sendMessage = null, phiProcessor = null, storeRunMetrics = null, llmMonitor = null, toolRuntimeRepos = {} }) {
|
|
49
|
+
Object.assign(this, { mode, queueAdapter, sendMessage, phiProcessor, storeRunMetrics, llmMonitor, toolRuntimeRepos });
|
|
37
50
|
if (mode === 'queue' && queueAdapter) {
|
|
38
51
|
queueAdapter.process('assistant.process', (payload) => this._executeLocal(payload));
|
|
39
52
|
}
|
|
@@ -74,6 +87,7 @@ class AssistantProcessor {
|
|
|
74
87
|
patientCode: thread.code,
|
|
75
88
|
turnId: runOptions.runId,
|
|
76
89
|
shouldContinue: runOptions.shouldContinue,
|
|
90
|
+
repos: this.toolRuntimeRepos,
|
|
77
91
|
shadow: Boolean(runOptions.shadow),
|
|
78
92
|
...turnContext,
|
|
79
93
|
});
|
|
@@ -88,6 +102,9 @@ class AssistantProcessor {
|
|
|
88
102
|
ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
|
|
89
103
|
}
|
|
90
104
|
if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
|
|
105
|
+
if (runOptions.prePromptResult?.metadata) {
|
|
106
|
+
ctx?.setConsumerMetadata?.(runOptions.prePromptResult.metadata);
|
|
107
|
+
}
|
|
91
108
|
assistant.toolRuntimeContext = ctx;
|
|
92
109
|
if (ctx && thread) thread.toolRuntimeContext = ctx;
|
|
93
110
|
|
|
@@ -147,6 +164,7 @@ class AssistantProcessor {
|
|
|
147
164
|
try {
|
|
148
165
|
runResult = await runAssistantWithRetries(thread, assistant, runConfig, message);
|
|
149
166
|
} catch (error) {
|
|
167
|
+
await this._settleClaimedContext(ctx, 'known_not_sent');
|
|
150
168
|
try {
|
|
151
169
|
await ctx?.store?.({ predictionTimeMs: Date.now() - startTime, error });
|
|
152
170
|
} catch (storeError) {
|
|
@@ -156,6 +174,10 @@ class AssistantProcessor {
|
|
|
156
174
|
}
|
|
157
175
|
const predictionTimeMs = Date.now() - startTime;
|
|
158
176
|
|
|
177
|
+
if (!this._contextIsLive(ctx)) {
|
|
178
|
+
await this._settleClaimedContext(ctx, 'known_not_sent');
|
|
179
|
+
}
|
|
180
|
+
|
|
159
181
|
// Audit-only: these run on every clinical turn and must not throw after the model has answered.
|
|
160
182
|
const recordSignals = (signals) => {
|
|
161
183
|
try {
|
|
@@ -204,7 +226,7 @@ class AssistantProcessor {
|
|
|
204
226
|
});
|
|
205
227
|
}
|
|
206
228
|
|
|
207
|
-
const output = sanitizeOutput(runResult?.output);
|
|
229
|
+
const output = ctx?.deliveryDirective?.body ?? sanitizeOutput(runResult?.output);
|
|
208
230
|
|
|
209
231
|
let traceStored = false;
|
|
210
232
|
try {
|
|
@@ -254,6 +276,13 @@ class AssistantProcessor {
|
|
|
254
276
|
predictionTimeMs,
|
|
255
277
|
retries: runResult?.retries || 0,
|
|
256
278
|
completed: runResult?.completed,
|
|
279
|
+
...(ctx?.deliveryDirective && {
|
|
280
|
+
deliveryDirective: {
|
|
281
|
+
operationId: ctx.deliveryDirective.operationId,
|
|
282
|
+
claimed: ctx.deliveryDirective.claimed === true,
|
|
283
|
+
settled: ctx.deliveryDirective.settled === true,
|
|
284
|
+
},
|
|
285
|
+
}),
|
|
257
286
|
};
|
|
258
287
|
}
|
|
259
288
|
|
|
@@ -270,10 +299,20 @@ class AssistantProcessor {
|
|
|
270
299
|
if (!resolved) return null;
|
|
271
300
|
|
|
272
301
|
const result = await this.executeLLM(resolved.thread, resolved.assistant, runOptions, message);
|
|
273
|
-
|
|
302
|
+
await this._storeMetricsOrDiscard(code, resolved.thread, result);
|
|
274
303
|
return result;
|
|
275
304
|
}
|
|
276
305
|
|
|
306
|
+
async _storeMetricsOrDiscard(code, thread, result) {
|
|
307
|
+
if (!this.storeRunMetrics) return;
|
|
308
|
+
try {
|
|
309
|
+
await this.storeRunMetrics(code, thread, result);
|
|
310
|
+
} catch (error) {
|
|
311
|
+
await this.discardResponse(code, result);
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
277
316
|
async _executeViaQueue({ code, runOptions = {} }) {
|
|
278
317
|
if (!this.queueAdapter) throw new Error('queueAdapter is required for queue mode');
|
|
279
318
|
const timeoutMs = runOptions.queueTimeoutMs || 120000;
|
|
@@ -282,17 +321,122 @@ class AssistantProcessor {
|
|
|
282
321
|
}
|
|
283
322
|
|
|
284
323
|
async sendResponse(code, result) {
|
|
285
|
-
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
324
|
+
const directive = result?.deliveryDirective || null;
|
|
325
|
+
if (directive && (directive.claimed !== true || directive.settled === true)) return null;
|
|
326
|
+
if (!this.sendMessage) {
|
|
327
|
+
if (directive) await this.discardResponse(code, result);
|
|
328
|
+
throw new Error('sendMessage function not configured');
|
|
329
|
+
}
|
|
330
|
+
if (!result?.output) {
|
|
331
|
+
if (directive) await this.discardResponse(code, result);
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
let sent;
|
|
335
|
+
try {
|
|
336
|
+
const outreachCarrier = result.outreachCarrier
|
|
337
|
+
? { ...result.outreachCarrier, utilityBasis: result.signals?.outreachDecision?.utilityBasis || result.outreachCarrier.utilityBasis || null }
|
|
338
|
+
: null;
|
|
339
|
+
sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt });
|
|
340
|
+
result.delivery = sent || null;
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (directive) {
|
|
343
|
+
await this._settleDelivery({
|
|
344
|
+
directive,
|
|
345
|
+
outcome: 'unknown',
|
|
346
|
+
providerMessageId: null,
|
|
347
|
+
patientCode: code,
|
|
348
|
+
turnId: result.turnId || null,
|
|
349
|
+
traceId: result.traceId || null,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
354
|
+
if (directive) {
|
|
355
|
+
const outcome = deliveryOutcome(sent);
|
|
356
|
+
await this._settleDelivery({
|
|
357
|
+
directive,
|
|
358
|
+
outcome,
|
|
359
|
+
providerMessageId: typeof sent?.messageId === 'string' && sent.messageId
|
|
360
|
+
? sent.messageId
|
|
361
|
+
: null,
|
|
362
|
+
patientCode: code,
|
|
363
|
+
turnId: result.turnId || null,
|
|
364
|
+
traceId: result.traceId || null,
|
|
365
|
+
});
|
|
366
|
+
}
|
|
293
367
|
clearBridgeState(code);
|
|
294
368
|
return result.output;
|
|
295
369
|
}
|
|
370
|
+
|
|
371
|
+
async discardResponse(code, result) {
|
|
372
|
+
const directive = result?.deliveryDirective;
|
|
373
|
+
if (!directive?.claimed || directive.settled) return false;
|
|
374
|
+
return this._settleDelivery({
|
|
375
|
+
directive,
|
|
376
|
+
outcome: 'known_not_sent',
|
|
377
|
+
providerMessageId: null,
|
|
378
|
+
patientCode: code,
|
|
379
|
+
turnId: result.turnId || null,
|
|
380
|
+
traceId: result.traceId || null,
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
_contextIsLive(ctx) {
|
|
385
|
+
if (typeof ctx?.isLive !== 'function') return true;
|
|
386
|
+
try {
|
|
387
|
+
return ctx.isLive() === true;
|
|
388
|
+
} catch {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async _settleClaimedContext(ctx, outcome) {
|
|
394
|
+
const directive = ctx?.deliveryDirective;
|
|
395
|
+
if (!directive?.claimed || directive.settled) return false;
|
|
396
|
+
if (typeof ctx?.settleDelivery === 'function') {
|
|
397
|
+
try {
|
|
398
|
+
return await ctx.settleDelivery(outcome);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
this._logSettlementFailure({ directive, outcome }, error);
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return this._settleDelivery({
|
|
405
|
+
directive,
|
|
406
|
+
outcome,
|
|
407
|
+
providerMessageId: null,
|
|
408
|
+
patientCode: ctx.patientCode || null,
|
|
409
|
+
turnId: ctx.turnId || null,
|
|
410
|
+
traceId: ctx.trace?._id ? String(ctx.trace._id) : null,
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async _settleDelivery(settlement) {
|
|
415
|
+
const settle = this.toolRuntimeRepos?.nutritionSafety?.settleDelivery;
|
|
416
|
+
if (typeof settle !== 'function') {
|
|
417
|
+
logger.warn('[AssistantProcessor] nutrition safety delivery settlement unavailable', {
|
|
418
|
+
operationId: settlement.directive.operationId,
|
|
419
|
+
outcome: settlement.outcome,
|
|
420
|
+
reason: 'nutrition_safety_settlement_unavailable',
|
|
421
|
+
});
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
try {
|
|
425
|
+
return await settleClaimedDelivery({ ...settlement, settleDelivery: settle });
|
|
426
|
+
} catch (error) {
|
|
427
|
+
this._logSettlementFailure(settlement, error);
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
_logSettlementFailure(settlement, error) {
|
|
433
|
+
logger.warn('[AssistantProcessor] nutrition safety delivery settlement failed', {
|
|
434
|
+
operationId: settlement.directive.operationId,
|
|
435
|
+
outcome: settlement.outcome,
|
|
436
|
+
reason: 'nutrition_safety_settlement_failed',
|
|
437
|
+
errorType: error?.constructor?.name || typeof error,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
296
440
|
}
|
|
297
441
|
|
|
298
442
|
module.exports = { AssistantProcessor };
|
|
@@ -3,10 +3,10 @@ const { isToolFailure, toolFailureError } = require('../helpers/toolResultHelper
|
|
|
3
3
|
const { GUARD_REFUSAL_CODES } = require('../helpers/clinicalWorkflowGuard');
|
|
4
4
|
const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
|
|
5
5
|
const { logger } = require('../../utils/logger');
|
|
6
|
+
const { settleClaimedDelivery } = require('../services/deliverySettlementService');
|
|
6
7
|
const { normalizeTurnKind, TURN_KIND } = require('./turnContext');
|
|
7
8
|
|
|
8
9
|
const UNLISTED_REFUSAL = 'unlisted_refusal';
|
|
9
|
-
|
|
10
10
|
function refusalCode(output) {
|
|
11
11
|
const raw = toolFailureError(output, UNLISTED_REFUSAL);
|
|
12
12
|
return GUARD_REFUSAL_CODES.has(raw) ? raw : UNLISTED_REFUSAL;
|
|
@@ -59,6 +59,8 @@ class ToolRuntimeContext {
|
|
|
59
59
|
this.safetyArtifact = null;
|
|
60
60
|
this.palliativeAssessment = null;
|
|
61
61
|
this.careplan = null;
|
|
62
|
+
this.consumerMetadata = null;
|
|
63
|
+
this.deliveryDirective = null;
|
|
62
64
|
this.trace = new (getTurnTraceModel())({ turnId, patientCode, sessionId, shadow });
|
|
63
65
|
this.setTurnContext({ turnKind, patientInput });
|
|
64
66
|
}
|
|
@@ -69,6 +71,12 @@ class ToolRuntimeContext {
|
|
|
69
71
|
? {
|
|
70
72
|
kind: typeof patientInput.kind === 'string' ? patientInput.kind : 'text',
|
|
71
73
|
text: typeof patientInput.text === 'string' ? patientInput.text : null,
|
|
74
|
+
...(typeof patientInput.sourceId === 'string' && patientInput.sourceId && {
|
|
75
|
+
sourceId: patientInput.sourceId,
|
|
76
|
+
}),
|
|
77
|
+
...(typeof patientInput.observedAt === 'string' && patientInput.observedAt && {
|
|
78
|
+
observedAt: patientInput.observedAt,
|
|
79
|
+
}),
|
|
72
80
|
}
|
|
73
81
|
: null;
|
|
74
82
|
this.trace?.setSignals?.({
|
|
@@ -128,6 +136,36 @@ class ToolRuntimeContext {
|
|
|
128
136
|
this.careplan = this._requireArtifact('careplan', artifact);
|
|
129
137
|
}
|
|
130
138
|
|
|
139
|
+
setConsumerMetadata(metadata) {
|
|
140
|
+
this.consumerMetadata = metadata;
|
|
141
|
+
return this;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
setDeliveryDirective(directive) {
|
|
145
|
+
const operationId = directive?.operationId;
|
|
146
|
+
const body = directive?.body;
|
|
147
|
+
if (typeof operationId !== 'string' || !/^[a-zA-Z0-9_-]{1,200}$/.test(operationId)
|
|
148
|
+
|| typeof body !== 'string' || !body.trim() || body.length > 4000) {
|
|
149
|
+
throw new Error('ToolRuntimeContext.deliveryDirective must have a valid operationId and non-empty body');
|
|
150
|
+
}
|
|
151
|
+
this.deliveryDirective = {
|
|
152
|
+
operationId, body, claimed: false, settled: false,
|
|
153
|
+
};
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async settleDelivery(outcome, providerMessageId = null) {
|
|
158
|
+
return settleClaimedDelivery({
|
|
159
|
+
directive: this.deliveryDirective,
|
|
160
|
+
settleDelivery: this.repos?.nutritionSafety?.settleDelivery,
|
|
161
|
+
outcome,
|
|
162
|
+
providerMessageId,
|
|
163
|
+
patientCode: this.patientCode,
|
|
164
|
+
turnId: this.turnId,
|
|
165
|
+
traceId: this.trace?._id ? String(this.trace._id) : null,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
131
169
|
_requireArtifact(slot, artifact) {
|
|
132
170
|
if (artifact === null || typeof artifact !== 'object' || Array.isArray(artifact)) {
|
|
133
171
|
throw new Error(`ToolRuntimeContext.${slot} must be a plain object`);
|
|
@@ -17,12 +17,22 @@ function patientInputFrom(message) {
|
|
|
17
17
|
if (message.type === 'flow' || message.flow || message.interactive?.type === 'flow'
|
|
18
18
|
|| message.interactive_type === 'flow' || message.interactive_data?.type === 'flow') kind = 'flow';
|
|
19
19
|
else if (message.type === 'media' || message.media) kind = 'media';
|
|
20
|
+
const sourceId = message.message_id ?? message.messageId ?? message.id ?? null;
|
|
21
|
+
const observedAt = normalizeObservedAt(message.createdAt ?? message.timestamp ?? null);
|
|
20
22
|
return {
|
|
21
23
|
kind,
|
|
22
24
|
text: typeof message.body === 'string' ? message.body : null,
|
|
25
|
+
...(typeof sourceId === 'string' && sourceId && { sourceId }),
|
|
26
|
+
...(observedAt && { observedAt }),
|
|
23
27
|
};
|
|
24
28
|
}
|
|
25
29
|
|
|
30
|
+
function normalizeObservedAt(value) {
|
|
31
|
+
if (value === null || value === undefined || value === '') return null;
|
|
32
|
+
const parsed = value instanceof Date ? value : new Date(value);
|
|
33
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
|
|
34
|
+
}
|
|
35
|
+
|
|
26
36
|
function resolveTurnContext({ turnKind = null, message = null } = {}) {
|
|
27
37
|
const inferredKind = turnKind || (message ? TURN_KIND.PATIENT : TURN_KIND.UNKNOWN);
|
|
28
38
|
const kind = normalizeTurnKind(inferredKind);
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const evidenceSchema = new mongoose.Schema({
|
|
6
|
+
key: { type: String, required: true },
|
|
7
|
+
source: { type: String, required: true, enum: ['triage', 'chat', 'fhir', 'airtable'] },
|
|
8
|
+
sourceId: { type: String, required: true },
|
|
9
|
+
code: { type: String, required: true },
|
|
10
|
+
summary: { type: String, default: null },
|
|
11
|
+
confidence: { type: Number, default: null },
|
|
12
|
+
}, { _id: false });
|
|
13
|
+
|
|
14
|
+
const invitationAttemptSchema = new mongoose.Schema({
|
|
15
|
+
idempotencyKey: { type: String, required: true },
|
|
16
|
+
invitationClass: { type: String, required: true, enum: ['first', 'followup'] },
|
|
17
|
+
invitationCycle: { type: String, required: true },
|
|
18
|
+
templateVersion: { type: String, required: true },
|
|
19
|
+
status: { type: String, enum: ['queued', 'sent', 'delivered', 'read', 'failed', 'unknown'], default: 'queued' },
|
|
20
|
+
providerMessageId: { type: String, default: null },
|
|
21
|
+
error: { type: String, default: null },
|
|
22
|
+
createdAt: { type: Date, default: Date.now },
|
|
23
|
+
settledAt: { type: Date, default: null },
|
|
24
|
+
}, { _id: false });
|
|
25
|
+
|
|
26
|
+
const supportCandidateSchema = new mongoose.Schema({
|
|
27
|
+
candidateId: { type: String, required: true, unique: true },
|
|
28
|
+
patientId: { type: String, required: true },
|
|
29
|
+
service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
|
|
30
|
+
disposition: {
|
|
31
|
+
type: String,
|
|
32
|
+
required: true,
|
|
33
|
+
enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'],
|
|
34
|
+
},
|
|
35
|
+
engagement: {
|
|
36
|
+
state: { type: String, enum: ['notInvited', 'invited', 'registered', 'attended', 'declined'], default: 'notInvited' },
|
|
37
|
+
lastInvitedAt: { type: Date, default: null },
|
|
38
|
+
cooldownUntil: { type: Date, default: null },
|
|
39
|
+
registrationEvidenceId: { type: String, default: null },
|
|
40
|
+
registeredAt: { type: Date, default: null },
|
|
41
|
+
attendanceEvidenceId: { type: String, default: null },
|
|
42
|
+
attendedAt: { type: Date, default: null },
|
|
43
|
+
declineEvidenceId: { type: String, default: null },
|
|
44
|
+
declinedAt: { type: Date, default: null },
|
|
45
|
+
declinePreference: { type: String, enum: [null, 'another_date', 'not_now', 'never'], default: null },
|
|
46
|
+
},
|
|
47
|
+
groupEligible: { type: Boolean, required: true },
|
|
48
|
+
urgentIntakeEligible: { type: Boolean, default: false },
|
|
49
|
+
priority: { type: String, enum: ['routine', 'soon', 'urgent'], default: 'routine' },
|
|
50
|
+
confidence: { type: Number, required: true },
|
|
51
|
+
nutritionRisk: { type: String, default: null },
|
|
52
|
+
psychologyRisk: { type: String, default: null },
|
|
53
|
+
reasonCodes: { type: [String], default: [] },
|
|
54
|
+
operationalReviews: { type: [new mongoose.Schema({
|
|
55
|
+
reasonCode: { type: String, required: true, enum: ['classification_failed', 'attendance_unavailable', 'safety_unconfirmed', 'classification_safety_unconfirmed', 'invitation_claim_failed'] },
|
|
56
|
+
sourceId: { type: String, required: true, maxlength: 256 },
|
|
57
|
+
detectedAt: { type: Date, required: true },
|
|
58
|
+
}, { _id: false })], default: [] },
|
|
59
|
+
operationalReviewOverflow: { type: Boolean, default: false },
|
|
60
|
+
evidence: { type: [evidenceSchema], default: [] },
|
|
61
|
+
sourceEventIds: { type: [String], default: [] },
|
|
62
|
+
latestSourceId: { type: String, required: true },
|
|
63
|
+
latestOrigin: { type: String, required: true },
|
|
64
|
+
decisionVersion: { type: String, required: true },
|
|
65
|
+
invitationAttempts: { type: [invitationAttemptSchema], default: [] },
|
|
66
|
+
activeInvitationKey: { type: String, default: null },
|
|
67
|
+
cooldownInvitationKey: { type: String, default: null },
|
|
68
|
+
specialistClearedAt: { type: Date, default: null },
|
|
69
|
+
escalation: {
|
|
70
|
+
risk: { type: String, default: null },
|
|
71
|
+
sourceId: { type: String, default: null },
|
|
72
|
+
origin: { type: String, default: null },
|
|
73
|
+
detectedAt: { type: Date, default: null },
|
|
74
|
+
clearedAt: { type: Date, default: null },
|
|
75
|
+
},
|
|
76
|
+
revision: { type: Number, default: 0 },
|
|
77
|
+
lastEvaluatedAt: { type: Date, required: true },
|
|
78
|
+
}, { timestamps: true });
|
|
79
|
+
|
|
80
|
+
supportCandidateSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_candidate_per_service' });
|
|
81
|
+
supportCandidateSchema.index({ disposition: 1, service: 1, priority: 1, updatedAt: -1 });
|
|
82
|
+
supportCandidateSchema.index({ 'invitationAttempts.idempotencyKey': 1 }, { sparse: true });
|
|
83
|
+
|
|
84
|
+
function getSupportCandidateModel() {
|
|
85
|
+
const conn = clinicalConnection();
|
|
86
|
+
return conn.models.SupportCandidate
|
|
87
|
+
|| conn.model('SupportCandidate', supportCandidateSchema, 'supportCandidates');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { getSupportCandidateModel, supportCandidateSchema };
|
|
@@ -53,6 +53,35 @@ const triageRecommendationEventSchema = new mongoose.Schema({
|
|
|
53
53
|
mirrorRecordId: { type: String, default: null },
|
|
54
54
|
mirrorError: { type: String, default: null },
|
|
55
55
|
mirrorPayload: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
56
|
+
supportRoutingOk: { type: Boolean, default: null },
|
|
57
|
+
supportCandidateCount: { type: Number, default: null },
|
|
58
|
+
supportRoutingError: { type: String, default: null },
|
|
59
|
+
supportReviewError: { type: String, default: null },
|
|
60
|
+
supportAction: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
61
|
+
supportActionMirrored: { type: Boolean, default: false },
|
|
62
|
+
supportMirroredActions: {
|
|
63
|
+
type: [new mongoose.Schema({
|
|
64
|
+
candidateId: { type: String, required: true },
|
|
65
|
+
type: { type: String, required: true, enum: ['group_registration', 'urgent_nutrition_intake'] },
|
|
66
|
+
}, { _id: false })],
|
|
67
|
+
default: [],
|
|
68
|
+
},
|
|
69
|
+
supportPendingCandidateIds: { type: [String], default: [] },
|
|
70
|
+
supportActionMirrorRecordId: { type: String, default: null },
|
|
71
|
+
supportMirrorRecordIds: { type: [String], default: [] },
|
|
72
|
+
supportActionError: { type: String, default: null },
|
|
73
|
+
supportPendingSettlements: {
|
|
74
|
+
type: [new mongoose.Schema({
|
|
75
|
+
candidateId: { type: String, required: true },
|
|
76
|
+
idempotencyKey: { type: String, required: true },
|
|
77
|
+
status: { type: String, required: true, enum: ['failed', 'unknown'] },
|
|
78
|
+
error: { type: String, required: true },
|
|
79
|
+
}, { _id: false })],
|
|
80
|
+
default: [],
|
|
81
|
+
},
|
|
82
|
+
supportActionMirrorUnknown: { type: Boolean, default: false },
|
|
83
|
+
supportSafetyCleared: { type: Boolean, default: false },
|
|
84
|
+
supportDeliveryCandidateIds: { type: [String], default: [] },
|
|
56
85
|
}, { timestamps: true });
|
|
57
86
|
triageRecommendationEventSchema.index({ patientCode: 1, createdAt: -1 });
|
|
58
87
|
triageRecommendationEventSchema.index({ status: 1, createdAt: -1 });
|
|
@@ -18,6 +18,7 @@ const { isJsonBlob } = require('../../utils/formatUtils');
|
|
|
18
18
|
const { isPlainObject } = require('../../utils/jsonUtils');
|
|
19
19
|
|
|
20
20
|
const CONSUMER_SIGNALS_KEY = 'consumer';
|
|
21
|
+
const MAX_ADDITIONAL_TOOL_IDS = 8;
|
|
21
22
|
|
|
22
23
|
const { getToolSchemas: getRegistrySchemas } = require('../../services/toolRegistryService');
|
|
23
24
|
const { getMessages } = require('../../services/messageService');
|
|
@@ -95,6 +96,27 @@ class BaseLLMProvider {
|
|
|
95
96
|
const { toolIds, filtered, descriptions: toolDescriptions } = await resolveTools({
|
|
96
97
|
promptId: resolvedPromptId || assistantId, assistant, presetToolIds,
|
|
97
98
|
});
|
|
99
|
+
const requestedAdditionalToolIds = Array.isArray(prePromptResult?.additionalToolIds)
|
|
100
|
+
? [...new Set(prePromptResult.additionalToolIds
|
|
101
|
+
.filter(id => typeof id === 'string' && id.trim())
|
|
102
|
+
.map(id => id.trim()))].slice(0, MAX_ADDITIONAL_TOOL_IDS)
|
|
103
|
+
: [];
|
|
104
|
+
const registeredAdditionalToolIds = requestedAdditionalToolIds.length > 0
|
|
105
|
+
? getRegistrySchemas(requestedAdditionalToolIds)
|
|
106
|
+
.map(schema => schema.function?.name)
|
|
107
|
+
.filter(Boolean)
|
|
108
|
+
: [];
|
|
109
|
+
const resolvedToolIds = filtered
|
|
110
|
+
? [...new Set([...toolIds, ...registeredAdditionalToolIds])]
|
|
111
|
+
: toolIds;
|
|
112
|
+
|
|
113
|
+
const rejectedAdditionalToolIds = requestedAdditionalToolIds
|
|
114
|
+
.filter(id => !registeredAdditionalToolIds.includes(id));
|
|
115
|
+
if (rejectedAdditionalToolIds.length > 0) {
|
|
116
|
+
logger.warn('[BaseLLMProvider] Ignoring unregistered runtime tools', {
|
|
117
|
+
toolIds: rejectedAdditionalToolIds,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
98
120
|
|
|
99
121
|
const skillCatalog = await resolveSkillCatalog(presetSkillIds);
|
|
100
122
|
const enabledSkills = skillCatalog.map((skill) => skill.name);
|
|
@@ -102,13 +124,31 @@ class BaseLLMProvider {
|
|
|
102
124
|
assistant.toolRuntimeContext.enabledSkills = enabledSkills;
|
|
103
125
|
}
|
|
104
126
|
|
|
105
|
-
const resolvedSchemas = this._resolveToolSchemas({
|
|
127
|
+
const resolvedSchemas = this._resolveToolSchemas({
|
|
128
|
+
assistant, toolIds: resolvedToolIds, filtered, toolDescriptions,
|
|
129
|
+
});
|
|
106
130
|
const { toolChoice: flooredToolChoice, toolSchemas, narrowed } = this._applyDeliveryFloor(
|
|
107
131
|
toolChoice, resolvedSchemas, Boolean(assistant?.toolRuntimeContext), turnKind);
|
|
108
|
-
const effectiveToolIds =
|
|
132
|
+
const effectiveToolIds = toolSchemas.map(s => s.function?.name).filter(Boolean);
|
|
133
|
+
const instructionToolIds = narrowed ? effectiveToolIds : resolvedToolIds;
|
|
134
|
+
const requestedToolChoice = prePromptResult?.toolChoice;
|
|
135
|
+
const requestedToolName = requestedToolChoice?.name || requestedToolChoice?.function?.name || null;
|
|
136
|
+
const supportedGenericChoices = new Set(['auto', 'none', 'required', 'any']);
|
|
137
|
+
const isGenericToolChoice = (typeof requestedToolChoice === 'string'
|
|
138
|
+
&& supportedGenericChoices.has(requestedToolChoice))
|
|
139
|
+
|| (isPlainObject(requestedToolChoice) && !requestedToolName
|
|
140
|
+
&& supportedGenericChoices.has(requestedToolChoice.type));
|
|
141
|
+
const runtimeToolChoice = requestedToolName
|
|
142
|
+
? (effectiveToolIds.includes(requestedToolName) ? requestedToolChoice : null)
|
|
143
|
+
: (isGenericToolChoice ? requestedToolChoice : null);
|
|
144
|
+
if (requestedToolName && runtimeToolChoice === null) {
|
|
145
|
+
logger.warn('[BaseLLMProvider] Ignoring forced choice for an unavailable runtime tool', {
|
|
146
|
+
toolId: requestedToolName,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
109
149
|
const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
|
|
110
150
|
const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
|
|
111
|
-
const ruleBlock = this._buildContingencyRuleMessage({ toolIds:
|
|
151
|
+
const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
|
|
112
152
|
const auditedPrompt = [
|
|
113
153
|
devContent,
|
|
114
154
|
catalogBlock,
|
|
@@ -116,7 +156,7 @@ class BaseLLMProvider {
|
|
|
116
156
|
isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds })[0]?.content || '') : '',
|
|
117
157
|
ruleBlock,
|
|
118
158
|
].filter(Boolean).join('\n\n');
|
|
119
|
-
const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds:
|
|
159
|
+
const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null });
|
|
120
160
|
|
|
121
161
|
if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
|
|
122
162
|
trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
|
|
@@ -173,7 +213,7 @@ class BaseLLMProvider {
|
|
|
173
213
|
instructions: instructions || devContent || '',
|
|
174
214
|
input,
|
|
175
215
|
toolSchemas,
|
|
176
|
-
toolChoice: narrowed ? flooredToolChoice :
|
|
216
|
+
toolChoice: narrowed ? flooredToolChoice : runtimeToolChoice || flooredToolChoice,
|
|
177
217
|
followUpToolChoice: flooredToolChoice,
|
|
178
218
|
modelConfig,
|
|
179
219
|
metadata,
|
|
@@ -441,7 +441,7 @@ async function cancelContingencyRows({ code, trace, planId, standDownReason = nu
|
|
|
441
441
|
}
|
|
442
442
|
|
|
443
443
|
// The linked mirror row, null when the triage was read and carries none, undefined when unknown.
|
|
444
|
-
async function linkedMirrorRecordId(triageRecordId) {
|
|
444
|
+
async function linkedMirrorRecordId(triageRecordId, excludeRecordIds = []) {
|
|
445
445
|
if (!RECORD_ID_RX.test(triageRecordId || '')) return undefined;
|
|
446
446
|
let rows;
|
|
447
447
|
try {
|
|
@@ -458,17 +458,19 @@ async function linkedMirrorRecordId(triageRecordId) {
|
|
|
458
458
|
}
|
|
459
459
|
if (!Array.isArray(rows) || rows.length !== 1) return undefined;
|
|
460
460
|
const links = rows[0].cluster_recommendations;
|
|
461
|
-
return Array.isArray(links)
|
|
461
|
+
return Array.isArray(links) ? links.find((id) => !excludeRecordIds.includes(id)) || null : null;
|
|
462
462
|
}
|
|
463
463
|
|
|
464
464
|
// A single create fires the downstream explode automation exactly once.
|
|
465
|
-
async function recordClusterRecommendationsMirror({ code, triageRecordId, step1 = null, step2, step3 }) {
|
|
465
|
+
async function recordClusterRecommendationsMirror({ code, triageRecordId, step1 = null, step2, step3, supportAction = null, excludeRecordId = null, excludeRecordIds = [] }) {
|
|
466
466
|
const fields = {
|
|
467
467
|
triaje_symptoms: [triageRecordId],
|
|
468
468
|
step_2: JSON.stringify(step2),
|
|
469
469
|
recommendations: JSON.stringify(step3),
|
|
470
470
|
};
|
|
471
471
|
if (step1) fields.step_1 = JSON.stringify(step1);
|
|
472
|
+
if (supportAction) fields.support_action = JSON.stringify(supportAction);
|
|
473
|
+
let confirmedAbsent = false;
|
|
472
474
|
for (let attempt = 1; attempt <= MIRROR_ATTEMPTS; attempt += 1) {
|
|
473
475
|
let recordId = null;
|
|
474
476
|
const ok = await auditedWrite({
|
|
@@ -484,7 +486,8 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
|
|
|
484
486
|
});
|
|
485
487
|
if (ok) return { ok: true, recordId };
|
|
486
488
|
// Retrying blind would explode the recommendations twice if the create had landed.
|
|
487
|
-
const linked = await linkedMirrorRecordId(triageRecordId);
|
|
489
|
+
const linked = await linkedMirrorRecordId(triageRecordId, [...excludeRecordIds, excludeRecordId].filter(Boolean));
|
|
490
|
+
confirmedAbsent = linked === null;
|
|
488
491
|
if (linked) {
|
|
489
492
|
logger.info('[clinicalAirtableService] mirror write reported an error but the row exists', { code, triageRecordId, recordId: linked });
|
|
490
493
|
return { ok: true, recordId: linked };
|
|
@@ -494,7 +497,7 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
|
|
|
494
497
|
break;
|
|
495
498
|
}
|
|
496
499
|
}
|
|
497
|
-
return { ok: false, recordId: null };
|
|
500
|
+
return { ok: false, recordId: null, ...(supportAction ? { confirmedAbsent } : {}) };
|
|
498
501
|
}
|
|
499
502
|
|
|
500
503
|
module.exports = {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const { logger } = require('../../utils/logger');
|
|
2
|
+
|
|
3
|
+
const DELIVERY_OUTCOMES = new Set(['sent', 'known_not_sent', 'unknown']);
|
|
4
|
+
|
|
5
|
+
async function settleClaimedDelivery({
|
|
6
|
+
directive,
|
|
7
|
+
settleDelivery,
|
|
8
|
+
outcome,
|
|
9
|
+
providerMessageId = null,
|
|
10
|
+
patientCode,
|
|
11
|
+
turnId = null,
|
|
12
|
+
traceId = null,
|
|
13
|
+
}) {
|
|
14
|
+
if (!directive?.claimed || directive.settled || !DELIVERY_OUTCOMES.has(outcome)
|
|
15
|
+
|| typeof settleDelivery !== 'function') return false;
|
|
16
|
+
|
|
17
|
+
const accepted = await settleDelivery({
|
|
18
|
+
operationId: directive.operationId,
|
|
19
|
+
outcome,
|
|
20
|
+
providerMessageId: typeof providerMessageId === 'string' && providerMessageId
|
|
21
|
+
? providerMessageId
|
|
22
|
+
: null,
|
|
23
|
+
patientCode,
|
|
24
|
+
turnId,
|
|
25
|
+
traceId,
|
|
26
|
+
});
|
|
27
|
+
if (accepted === false) {
|
|
28
|
+
logger.warn('[deliverySettlement] repository rejected settlement', {
|
|
29
|
+
operationId: directive.operationId,
|
|
30
|
+
outcome,
|
|
31
|
+
});
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
directive.settled = true;
|
|
35
|
+
if (outcome === 'known_not_sent') directive.claimed = false;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
module.exports = { settleClaimedDelivery };
|