@peopl-health/nexus 5.51.0-dev.7632 → 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 -142
  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/README.md CHANGED
@@ -137,27 +137,6 @@ 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
-
161
140
  ## Examples
162
141
 
163
142
  General, illustrative examples meant to be copied into your own app:
@@ -13,7 +13,6 @@ 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');
17
16
  const { ToolRuntimeContext } = require('./context/ToolRuntimeContext');
18
17
  const { resolveTurnContext, TURN_KIND } = require('./context/turnContext');
19
18
 
@@ -32,21 +31,9 @@ const traceContingency = (net) => ({
32
31
  patientFiresAfterSilenceMinutes: net?.patientReminder?.firesAfterSilenceMinutes ?? null,
33
32
  });
34
33
 
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
-
47
34
  class AssistantProcessor {
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 });
35
+ constructor({ mode = 'local', queueAdapter = null, sendMessage = null, phiProcessor = null, storeRunMetrics = null, llmMonitor = null }) {
36
+ Object.assign(this, { mode, queueAdapter, sendMessage, phiProcessor, storeRunMetrics, llmMonitor });
50
37
  if (mode === 'queue' && queueAdapter) {
51
38
  queueAdapter.process('assistant.process', (payload) => this._executeLocal(payload));
52
39
  }
@@ -87,7 +74,6 @@ class AssistantProcessor {
87
74
  patientCode: thread.code,
88
75
  turnId: runOptions.runId,
89
76
  shouldContinue: runOptions.shouldContinue,
90
- repos: this.toolRuntimeRepos,
91
77
  shadow: Boolean(runOptions.shadow),
92
78
  ...turnContext,
93
79
  });
@@ -102,9 +88,6 @@ class AssistantProcessor {
102
88
  ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
103
89
  }
104
90
  if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
105
- if (runOptions.prePromptResult?.metadata) {
106
- ctx?.setConsumerMetadata?.(runOptions.prePromptResult.metadata);
107
- }
108
91
  assistant.toolRuntimeContext = ctx;
109
92
  if (ctx && thread) thread.toolRuntimeContext = ctx;
110
93
 
@@ -164,7 +147,6 @@ class AssistantProcessor {
164
147
  try {
165
148
  runResult = await runAssistantWithRetries(thread, assistant, runConfig, message);
166
149
  } catch (error) {
167
- await this._settleClaimedContext(ctx, 'known_not_sent');
168
150
  try {
169
151
  await ctx?.store?.({ predictionTimeMs: Date.now() - startTime, error });
170
152
  } catch (storeError) {
@@ -174,10 +156,6 @@ class AssistantProcessor {
174
156
  }
175
157
  const predictionTimeMs = Date.now() - startTime;
176
158
 
177
- if (!this._contextIsLive(ctx)) {
178
- await this._settleClaimedContext(ctx, 'known_not_sent');
179
- }
180
-
181
159
  // Audit-only: these run on every clinical turn and must not throw after the model has answered.
182
160
  const recordSignals = (signals) => {
183
161
  try {
@@ -226,7 +204,7 @@ class AssistantProcessor {
226
204
  });
227
205
  }
228
206
 
229
- const output = ctx?.deliveryDirective?.body ?? sanitizeOutput(runResult?.output);
207
+ const output = sanitizeOutput(runResult?.output);
230
208
 
231
209
  let traceStored = false;
232
210
  try {
@@ -276,13 +254,6 @@ class AssistantProcessor {
276
254
  predictionTimeMs,
277
255
  retries: runResult?.retries || 0,
278
256
  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
- }),
286
257
  };
287
258
  }
288
259
 
@@ -299,20 +270,10 @@ class AssistantProcessor {
299
270
  if (!resolved) return null;
300
271
 
301
272
  const result = await this.executeLLM(resolved.thread, resolved.assistant, runOptions, message);
302
- await this._storeMetricsOrDiscard(code, resolved.thread, result);
273
+ if (this.storeRunMetrics) await this.storeRunMetrics(code, resolved.thread, result);
303
274
  return result;
304
275
  }
305
276
 
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
-
316
277
  async _executeViaQueue({ code, runOptions = {} }) {
317
278
  if (!this.queueAdapter) throw new Error('queueAdapter is required for queue mode');
318
279
  const timeoutMs = runOptions.queueTimeoutMs || 120000;
@@ -321,122 +282,17 @@ class AssistantProcessor {
321
282
  }
322
283
 
323
284
  async sendResponse(code, result) {
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
- }
285
+ if (!this.sendMessage) throw new Error('sendMessage function not configured');
286
+ if (!result?.output) return null;
287
+ // Kept on the result so a caller that needs to know whether the message actually went out
288
+ // (proactive outreach stamps a record off it) reads the send, not the model's intent.
289
+ const outreachCarrier = result.outreachCarrier
290
+ ? { ...result.outreachCarrier, utilityBasis: result.signals?.outreachDecision?.utilityBasis || result.outreachCarrier.utilityBasis || null }
291
+ : null;
292
+ result.delivery = 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 }) || null;
367
293
  clearBridgeState(code);
368
294
  return result.output;
369
295
  }
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
- }
440
296
  }
441
297
 
442
298
  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');
7
6
  const { normalizeTurnKind, TURN_KIND } = require('./turnContext');
8
7
 
9
8
  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,8 +59,6 @@ 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;
64
62
  this.trace = new (getTurnTraceModel())({ turnId, patientCode, sessionId, shadow });
65
63
  this.setTurnContext({ turnKind, patientInput });
66
64
  }
@@ -71,12 +69,6 @@ class ToolRuntimeContext {
71
69
  ? {
72
70
  kind: typeof patientInput.kind === 'string' ? patientInput.kind : 'text',
73
71
  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
- }),
80
72
  }
81
73
  : null;
82
74
  this.trace?.setSignals?.({
@@ -136,36 +128,6 @@ class ToolRuntimeContext {
136
128
  this.careplan = this._requireArtifact('careplan', artifact);
137
129
  }
138
130
 
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
-
169
131
  _requireArtifact(slot, artifact) {
170
132
  if (artifact === null || typeof artifact !== 'object' || Array.isArray(artifact)) {
171
133
  throw new Error(`ToolRuntimeContext.${slot} must be a plain object`);
@@ -17,22 +17,12 @@ 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);
22
20
  return {
23
21
  kind,
24
22
  text: typeof message.body === 'string' ? message.body : null,
25
- ...(typeof sourceId === 'string' && sourceId && { sourceId }),
26
- ...(observedAt && { observedAt }),
27
23
  };
28
24
  }
29
25
 
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
-
36
26
  function resolveTurnContext({ turnKind = null, message = null } = {}) {
37
27
  const inferredKind = turnKind || (message ? TURN_KIND.PATIENT : TURN_KIND.UNKNOWN);
38
28
  const kind = normalizeTurnKind(inferredKind);
@@ -53,34 +53,6 @@ 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
- supportMirrorRecordIds: { type: [String], default: [] },
71
- supportActionError: { type: String, default: null },
72
- supportPendingSettlements: {
73
- type: [new mongoose.Schema({
74
- candidateId: { type: String, required: true },
75
- idempotencyKey: { type: String, required: true },
76
- status: { type: String, required: true, enum: ['failed', 'unknown'] },
77
- error: { type: String, required: true },
78
- }, { _id: false })],
79
- default: [],
80
- },
81
- supportActionMirrorUnknown: { type: Boolean, default: false },
82
- supportSafetyCleared: { type: Boolean, default: false },
83
- supportDeliveryCandidateIds: { type: [String], default: [] },
84
56
  }, { timestamps: true });
85
57
  triageRecommendationEventSchema.index({ patientCode: 1, createdAt: -1 });
86
58
  triageRecommendationEventSchema.index({ status: 1, createdAt: -1 });
@@ -16,7 +16,6 @@ const { logger } = require('../../utils/logger');
16
16
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
17
17
  const { isJsonBlob } = require('../../utils/formatUtils');
18
18
  const { isPlainObject } = require('../../utils/jsonUtils');
19
- const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
20
19
 
21
20
  const CONSUMER_SIGNALS_KEY = 'consumer';
22
21
 
@@ -96,27 +95,6 @@ class BaseLLMProvider {
96
95
  const { toolIds, filtered, descriptions: toolDescriptions } = await resolveTools({
97
96
  promptId: resolvedPromptId || assistantId, assistant, presetToolIds,
98
97
  });
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
- }
120
98
 
121
99
  const skillCatalog = await resolveSkillCatalog(presetSkillIds);
122
100
  const enabledSkills = skillCatalog.map((skill) => skill.name);
@@ -124,31 +102,13 @@ class BaseLLMProvider {
124
102
  assistant.toolRuntimeContext.enabledSkills = enabledSkills;
125
103
  }
126
104
 
127
- const resolvedSchemas = this._resolveToolSchemas({
128
- assistant, toolIds: resolvedToolIds, filtered, toolDescriptions,
129
- });
105
+ const resolvedSchemas = this._resolveToolSchemas({ assistant, toolIds, filtered, toolDescriptions });
130
106
  const { toolChoice: flooredToolChoice, toolSchemas, narrowed } = this._applyDeliveryFloor(
131
107
  toolChoice, resolvedSchemas, Boolean(assistant?.toolRuntimeContext), turnKind);
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
- }
108
+ const effectiveToolIds = narrowed ? toolSchemas.map(s => s.function?.name).filter(Boolean) : toolIds;
149
109
  const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
150
110
  const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
151
- const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
111
+ const ruleBlock = this._buildContingencyRuleMessage({ toolIds: effectiveToolIds, promptVariables })[0]?.content || '';
152
112
  const auditedPrompt = [
153
113
  devContent,
154
114
  catalogBlock,
@@ -156,7 +116,7 @@ class BaseLLMProvider {
156
116
  isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds })[0]?.content || '') : '',
157
117
  ruleBlock,
158
118
  ].filter(Boolean).join('\n\n');
159
- const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null });
119
+ const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: effectiveToolIds, outreachBrief: isOutreach ? outreachBrief : null });
160
120
 
161
121
  if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
162
122
  trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
@@ -213,7 +173,7 @@ class BaseLLMProvider {
213
173
  instructions: instructions || devContent || '',
214
174
  input,
215
175
  toolSchemas,
216
- toolChoice: narrowed ? flooredToolChoice : runtimeToolChoice || flooredToolChoice,
176
+ toolChoice: narrowed ? flooredToolChoice : prePromptResult?.toolChoice || flooredToolChoice,
217
177
  followUpToolChoice: flooredToolChoice,
218
178
  modelConfig,
219
179
  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, excludeRecordIds = []) {
444
+ async function linkedMirrorRecordId(triageRecordId) {
445
445
  if (!RECORD_ID_RX.test(triageRecordId || '')) return undefined;
446
446
  let rows;
447
447
  try {
@@ -458,19 +458,17 @@ async function linkedMirrorRecordId(triageRecordId, excludeRecordIds = []) {
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) ? links.find((id) => !excludeRecordIds.includes(id)) || null : null;
461
+ return Array.isArray(links) && links.length ? links[0] : 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, supportAction = null, excludeRecordId = null, excludeRecordIds = [] }) {
465
+ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1 = null, step2, step3 }) {
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;
474
472
  for (let attempt = 1; attempt <= MIRROR_ATTEMPTS; attempt += 1) {
475
473
  let recordId = null;
476
474
  const ok = await auditedWrite({
@@ -486,8 +484,7 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
486
484
  });
487
485
  if (ok) return { ok: true, recordId };
488
486
  // Retrying blind would explode the recommendations twice if the create had landed.
489
- const linked = await linkedMirrorRecordId(triageRecordId, [...excludeRecordIds, excludeRecordId].filter(Boolean));
490
- confirmedAbsent = linked === null;
487
+ const linked = await linkedMirrorRecordId(triageRecordId);
491
488
  if (linked) {
492
489
  logger.info('[clinicalAirtableService] mirror write reported an error but the row exists', { code, triageRecordId, recordId: linked });
493
490
  return { ok: true, recordId: linked };
@@ -497,7 +494,7 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
497
494
  break;
498
495
  }
499
496
  }
500
- return { ok: false, recordId: null, ...(supportAction ? { confirmedAbsent } : {}) };
497
+ return { ok: false, recordId: null };
501
498
  }
502
499
 
503
500
  module.exports = {
@@ -6,8 +6,6 @@ const { logger } = require('../../utils/logger');
6
6
 
7
7
  const { runClinicalAgent } = require('./clinicalAgentService');
8
8
 
9
- const ORACLE_UNSUPPORTED_TOOLS = new Set(['submitSupportRoutingRecommendation']);
10
-
11
9
  async function runDivergence({ request, connection, trace, actualMessage }) {
12
10
  let post;
13
11
  const startedAt = Date.now();
@@ -25,12 +23,7 @@ async function runDivergence({ request, connection, trace, actualMessage }) {
25
23
  const expected = { ...expectedTurn, tools_invoked: oracleToolsInvoked(expectedTurn, request.enabledTools) };
26
24
  const expectedMessage = post.body?.response || '';
27
25
 
28
- const enabledTools = new Set(request.enabledTools);
29
- const rawActual = trace.toDecision();
30
- const actual = {
31
- ...rawActual,
32
- tools_invoked: (rawActual.tools_invoked || []).filter((name) => enabledTools.has(name)),
33
- };
26
+ const actual = trace.toDecision();
34
27
  const outcome = await classify({
35
28
  expected, actual, expectedMessage, actualMessage,
36
29
  });
@@ -63,7 +56,7 @@ async function diverge({ shadow, runId }) {
63
56
  clinicalData: inputs.clinicalData,
64
57
  input: inputs.input || [],
65
58
  model: inputs.model,
66
- enabledTools: (inputs.toolIds || []).filter((name) => !ORACLE_UNSUPPORTED_TOOLS.has(name)),
59
+ enabledTools: inputs.toolIds || [],
67
60
  additionalInstructions: inputs.additionalInstructions || null,
68
61
  };
69
62
  logger.debug('[divergence] oracle request', { runId, code, model: request.model, inputLen: request.input.length, tools: request.enabledTools.length });