@peopl-health/nexus 5.55.0-dev.8114 → 5.55.0-dev.8128

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 CHANGED
@@ -116,38 +116,6 @@ const bus = nexus.getMessaging().getEventBus();
116
116
  bus.on('message:received', (m) => console.log('rx', m.id));
117
117
  ```
118
118
 
119
- ## Workflows (Optional)
120
-
121
- Register a named unit of work, deduplicated by a key you derive from the trigger.
122
-
123
- ```js
124
- const runner = nexus.getMessaging().getWorkflowRunner();
125
-
126
- await runner.register({
127
- kind: 'triage-projection',
128
- dedupeKey: (trigger) => String(trigger.submissionId),
129
- prepare: async (trigger, checkpoints, save) => { /* ... */ },
130
- retrySchedule: [5, 10, 20, 40], // minutes; omit for fire-and-forget
131
- });
132
-
133
- await runner.enqueue('triage-projection', { submissionId });
134
- ```
135
-
136
- With `retrySchedule` the trigger and a checkpoint journal are stored in Mongo and the schedule runs
137
- on an in-process timer — deferred workflows never touch the queue adapter, so they add no Redis load.
138
- `prepare` resumes from `checkpoints`; call `save(patch)` before each external call so a retry does
139
- not repeat completed work. Throw an error carrying `permanent: true` to give up immediately instead
140
- of walking the schedule; the Airtable helpers tag their own permanent 4xx errors that way, in
141
- `withAirtableRetry`, which all five of them route through. They rethrow on failure too, so an
142
- Airtable outage reaches `prepare` as an exception and walks the retry schedule on its own rather
143
- than reading as success.
144
-
145
- Recovery is automatic: registering sweeps for work left behind by a previous process, and the runner
146
- keeps sweeping so work whose worker died mid-`prepare` is reclaimed once its claim goes stale.
147
- `enqueue` on an abandoned key revives it, keeping its checkpoints. Work is retained for 24 hours
148
- after its last update and then expires — the dedupe key expires with it, so idempotency has the
149
- same horizon as retention.
150
-
151
119
  ## Assistants (Optional)
152
120
 
153
121
  Register assistant classes and (optionally) a custom resolver. OpenAI is supported via `llm: 'openai'`.
@@ -14,7 +14,6 @@ const PATTERN_CONSULT_DEFAULTS = { presetId: '' };
14
14
  const RISK_ASSESSMENT_DEFAULTS = { presetId: '' };
15
15
  const TRIAGE_GATE_DEFAULTS = { presetId: '' };
16
16
  const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
17
- const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
18
17
 
19
18
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
20
19
 
@@ -52,11 +51,7 @@ async function load() {
52
51
  if (byKey.TRIAGE_PLAN && !isPlainObject(parsedTriagePlan)) throw new Error('subAgents config TRIAGE_PLAN is not a JSON object');
53
52
  const triagePlan = { ...TRIAGE_PLAN_DEFAULTS, ...(parsedTriagePlan || {}) };
54
53
 
55
- const parsedEscalationDraft = safeParse(byKey.ESCALATION_DRAFT, null);
56
- if (byKey.ESCALATION_DRAFT && !isPlainObject(parsedEscalationDraft)) throw new Error('subAgents config ESCALATION_DRAFT is not a JSON object');
57
- const escalationDraft = { ...ESCALATION_DRAFT_DEFAULTS, ...(parsedEscalationDraft || {}) };
58
-
59
- const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft };
54
+ const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan };
60
55
  cache.set(CACHE_KEY, config);
61
56
  return config;
62
57
  }
@@ -72,5 +67,4 @@ module.exports = {
72
67
  getRiskAssessment: () => get('RISK_ASSESSMENT'),
73
68
  getTriageGate: () => get('TRIAGE_GATE'),
74
69
  getTriagePlan: () => get('TRIAGE_PLAN'),
75
- getEscalationDraft: () => get('ESCALATION_DRAFT'),
76
70
  };
@@ -1,7 +1,5 @@
1
1
  const { ClinicalMention } = require('../../shared/dtos/ClinicalMention');
2
2
 
3
- const { readStructuredText } = require('./structuredTextHelper');
4
-
5
3
  function buildExtractorInput(text, detectedTags, curated, template, { priorTurns = null, patientContext = null } = {}) {
6
4
  const priorTurnsPayload = Array.isArray(priorTurns) && priorTurns.length ? { prior_turns: priorTurns } : {};
7
5
  const contextPayload = patientContext ? { patient_context: patientContext } : {};
@@ -17,6 +15,15 @@ function buildExtractorInput(text, detectedTags, curated, template, { priorTurns
17
15
  .replace('{{payload}}', () => payload);
18
16
  }
19
17
 
18
+ function readOutputText(result) {
19
+ if (result?.output_text) return result.output_text;
20
+ const output = Array.isArray(result?.output) ? result.output : [];
21
+ const message = output.find((item) => item.type === 'message');
22
+ const content = Array.isArray(message?.content) ? message.content : [];
23
+ const part = content.find((c) => typeof c?.text === 'string');
24
+ return part?.text || '';
25
+ }
26
+
20
27
  function toClinicalMention(raw, { code, turnId, index, now, intakeSource, responseFormat, spanishByTerm = {} }) {
21
28
  const rawTerm = (raw.ctcae_term || '').trim().toLowerCase();
22
29
  const ctcaeTerm = !rawTerm || rawTerm === 'other' ? null : rawTerm;
@@ -66,5 +73,6 @@ function deriveCanonicalTerm(raw, ctcaeTerm, spanishByTerm) {
66
73
 
67
74
  module.exports = {
68
75
  buildExtractorInput,
76
+ readOutputText,
69
77
  toClinicalMention,
70
78
  };
@@ -3,8 +3,6 @@ const { isDeepStrictEqual } = require('node:util');
3
3
  const divergenceConfig = require('../config/divergenceConfig');
4
4
  const { requireOpenAIProvider } = require('../config/llmConfig');
5
5
 
6
- const { readStructuredText } = require('./structuredTextHelper');
7
-
8
6
  const VERDICT_SCHEMA = {
9
7
  type: 'object',
10
8
  properties: {
@@ -17,6 +15,15 @@ const VERDICT_SCHEMA = {
17
15
 
18
16
  const ungraded = (rationale) => ({ verdict: 'review', rationale, graded: false });
19
17
 
18
+ function readVerdictText(result) {
19
+ if (result?.output_text) return result.output_text;
20
+ const output = Array.isArray(result?.output) ? result.output : [];
21
+ const message = output.find((item) => item.type === 'message');
22
+ const content = Array.isArray(message?.content) ? message.content : [];
23
+ const part = content.find((c) => typeof c?.text === 'string');
24
+ return part?.text || '';
25
+ }
26
+
20
27
  const COMPARATORS = {
21
28
  scalar: (expected, actual) => expected === actual,
22
29
  set: (expected, actual) => isDeepStrictEqual(new Set(expected || []), new Set(actual || [])),
@@ -77,7 +84,7 @@ async function stochasticDivergence(expectedMessage, actualMessage) {
77
84
  input: [{ role: 'user', content: `ORIGINAL:\n${expected}\n\nREWRITTEN:\n${actual}` }],
78
85
  text: { format: { type: 'json_schema', name: 'stochastic_verdict', schema: VERDICT_SCHEMA, strict: true } },
79
86
  });
80
- const parsed = JSON.parse(readStructuredText(result));
87
+ const parsed = JSON.parse(readVerdictText(result));
81
88
  const verdict = ['pass', 'review', 'fail'].includes(parsed.verdict) ? parsed.verdict : 'review';
82
89
  return { verdict, rationale: parsed.rationale || '', graded: true };
83
90
  } catch (error) {
@@ -313,7 +313,7 @@ class AnthropicProvider extends BaseLLMProvider {
313
313
  return { response: this._normalizeResponse(finalResponse), toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
314
314
  }
315
315
 
316
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
316
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, model = null } = {}) {
317
317
  let modelConfig = {};
318
318
  let resolvedInstructions = instructions;
319
319
  if (promptId || presetId) {
@@ -347,11 +347,8 @@ class AnthropicProvider extends BaseLLMProvider {
347
347
  { providerName: this.constructor.name },
348
348
  )
349
349
  );
350
- // The Messages API takes no free-form metadata, so the caller's correlation keys can only live
351
- // in the call audit. Dropping them silently is what leaves a generated call unattributable.
352
- const callerMetadata = Object.fromEntries(Object.entries(metadata || {}).filter(([, value]) => value != null));
353
350
  void appendCall({
354
- metadata: { source: 'structured', iterationIndex: 0, resolvedPromptId: promptId, resolvedPresetId: presetId, ...callerMetadata },
351
+ metadata: { source: 'structured', iterationIndex: 0, resolvedPromptId: promptId, resolvedPresetId: presetId },
355
352
  request: { messages, config: apiConfig },
356
353
  response: result,
357
354
  durationMs,
@@ -1,8 +1,7 @@
1
1
  const { getSafetyFlagPatterns } = require('../config/divergenceConfig');
2
2
  const { getExtractor } = require('../config/subAgentsConfig');
3
3
  const { detectSafetyFlags } = require('../helpers/safetyFlagsHelper');
4
- const { buildExtractorInput, toClinicalMention } = require('../helpers/clinicalMentionHelper');
5
- const { readStructuredText } = require('../helpers/structuredTextHelper');
4
+ const { buildExtractorInput, readOutputText, toClinicalMention } = require('../helpers/clinicalMentionHelper');
6
5
  const { isQuoteAnchored } = require('../../utils/textMatchUtils');
7
6
  const { foldAccents } = require('../../utils/formatUtils');
8
7
  const { getClinicalContext } = require('../../helpers/patientInformationHelper');
@@ -77,7 +76,7 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
77
76
 
78
77
  if (result?.status && result.status !== 'completed') throw new Error(`clinical extraction incomplete: status=${result.status}`);
79
78
 
80
- const outputText = readStructuredText(result);
79
+ const outputText = readOutputText(result);
81
80
  const parsed = safeParse(outputText, null);
82
81
  if (outputText && outputText.trim() && parsed === null) {
83
82
  logger.warn('[clinicalExtraction] model output did not parse as JSON; no mentions extracted', { turnId });
@@ -2,7 +2,7 @@ const { withTiming } = require('../../utils/tracingDecorator');
2
2
  const { getComposer } = require('../config/subAgentsConfig');
3
3
  const { getPromptBlocks } = require('../config/composerConfig');
4
4
 
5
- const { readStructuredText } = require('../helpers/structuredTextHelper');
5
+ const { readOutputText } = require('../helpers/clinicalMentionHelper');
6
6
  const { safeParse } = require('../../utils/jsonUtils');
7
7
  const { logger } = require('../../utils/logger');
8
8
 
@@ -56,7 +56,7 @@ async function renderMessage({ intentPayload, provider, trace = null }) {
56
56
  return null;
57
57
  }
58
58
 
59
- const outputText = readStructuredText(result);
59
+ const outputText = readOutputText(result);
60
60
  const parsed = safeParse(outputText, null);
61
61
  if (outputText && outputText.trim() && parsed === null) {
62
62
  logger.warn('[composerService] composer output did not parse as JSON; falling back to legacy message_text', { presetId });
@@ -1,5 +1,4 @@
1
1
  const { createLLMProvider } = require('../providers/createLLMProvider');
2
- const { readStructuredText } = require('../helpers/structuredTextHelper');
3
2
  const runtimeConfig = require('../../config/runtimeConfig');
4
3
  const { logger } = require('../../utils/logger');
5
4
 
@@ -50,6 +49,13 @@ unsure — you cannot tell which it is.
50
49
  Return one verdict per line. Give the line's number in "line" and quote its value back — not the
51
50
  field — in "value".`;
52
51
 
52
+ const readText = (result) => {
53
+ if (result?.output_text) return result.output_text;
54
+ const output = Array.isArray(result?.output) ? result.output : [];
55
+ const content = output.find((item) => item.type === 'message')?.content;
56
+ return (Array.isArray(content) ? content.find((part) => typeof part?.text === 'string') : null)?.text || '';
57
+ };
58
+
53
59
  const chunk = (values, size) => Array.from(
54
60
  { length: Math.ceil(values.length / size) },
55
61
  (_, i) => values.slice(i * size, (i + 1) * size),
@@ -97,7 +103,7 @@ async function verifyNamesSomething(candidateList) {
97
103
  text: { format: { type: 'json_schema', name: 'names_something', schema: VERDICT_SCHEMA, strict: true } },
98
104
  model: model(),
99
105
  });
100
- for (const verdict of JSON.parse(readStructuredText(result))?.verdicts ?? []) {
106
+ for (const verdict of JSON.parse(readText(result))?.verdicts ?? []) {
101
107
  const line = Number.isInteger(verdict.line) ? verdict.line : 0;
102
108
  const candidate = line >= 1 && line <= batch.length ? batch[line - 1] : null;
103
109
  if (!candidate || candidate.value !== verdict.value) { stats.unmatched += 1; continue; }
@@ -2,7 +2,7 @@ const crypto = require('node:crypto');
2
2
 
3
3
  const { getPatternConsult } = require('../config/subAgentsConfig');
4
4
  const { patternConsultStore } = require('../models/patternConsultModel');
5
- const { readStructuredText } = require('../helpers/structuredTextHelper');
5
+ const { readOutputText } = require('../helpers/clinicalMentionHelper');
6
6
  const { safeParse } = require('../../utils/jsonUtils');
7
7
  const { logger } = require('../../utils/logger');
8
8
  const { assembleLandscape } = require('./symptomLandscapeService');
@@ -90,7 +90,7 @@ async function requestPatternConsult({ concern, patientId, turnId, provider }) {
90
90
 
91
91
  if (result?.status && result.status !== 'completed') throw new Error(`pattern consult incomplete: status=${result.status}`);
92
92
 
93
- const outputText = readStructuredText(result);
93
+ const outputText = readOutputText(result);
94
94
  const parsed = safeParse(outputText, null);
95
95
  if (outputText && outputText.trim() && parsed === null) {
96
96
  logger.warn('[patternConsult] model output did not parse as JSON; degraded', { turnId });
@@ -6,7 +6,7 @@ const { requireGatewayProvider } = require('../config/llmConfig');
6
6
  const { getRiskWarmupEventModel } = require('../models/riskWarmupEventModel');
7
7
  const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
8
8
  const { isShadowRun } = require('../helpers/shadowHelper');
9
- const { readStructuredText } = require('../helpers/structuredTextHelper');
9
+ const { readOutputText } = require('../helpers/clinicalMentionHelper');
10
10
  const { pairTriageSymptoms } = require('../helpers/triageSymptomsHelper');
11
11
  const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
12
12
  const { Follow_Up_ID, Symptoms_ID } = require('../../config/airtableConfig');
@@ -105,7 +105,7 @@ async function assessPatientRisk({ code, provider }) {
105
105
  return { stored: false, reason: 'synthesis_incomplete', trigger };
106
106
  }
107
107
 
108
- const rawOutput = safeParse(readStructuredText(result), null);
108
+ const rawOutput = safeParse(readOutputText(result), null);
109
109
  if (!isPlainObject(rawOutput)) {
110
110
  logger.warn('[riskAssessment] model output did not parse as JSON', { code });
111
111
  return { stored: false, reason: 'malformed_model_output', trigger };
@@ -1,4 +1,4 @@
1
- const { readStructuredText } = require('../helpers/structuredTextHelper');
1
+ const { readOutputText } = require('../helpers/clinicalMentionHelper');
2
2
  const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
3
3
  const { safeParse } = require('../../utils/jsonUtils');
4
4
 
@@ -100,7 +100,7 @@ async function evaluateSupportRouting({ provider, patientId, origin, sourceId, c
100
100
  text: { format: { type: 'json_schema', name: 'support_routing', strict: true, schema: SUPPORT_ROUTING_SCHEMA } },
101
101
  metadata: { subAgent: 'support-routing', sourceId },
102
102
  });
103
- const parsed = safeParse(readStructuredText(result), null);
103
+ const parsed = safeParse(readOutputText(result), null);
104
104
  if (!parsed || !Array.isArray(parsed.decisions)) throw new Error('support routing response malformed');
105
105
  return new SupportRoutingRecommendation({
106
106
  patientId,
@@ -5,7 +5,7 @@ const { requireGatewayProvider } = require('../config/llmConfig');
5
5
  const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
6
6
  const { getSupportCandidateModel } = require('../models/supportCandidateModel');
7
7
  const { isShadowRun } = require('../helpers/shadowHelper');
8
- const { readStructuredText } = require('../helpers/structuredTextHelper');
8
+ const { readOutputText } = require('../helpers/clinicalMentionHelper');
9
9
  const {
10
10
  str, arr, buildRedFlag, normalizeGateEscalation, applyRouteFloor,
11
11
  } = require('../helpers/recommendationGateHelper');
@@ -752,7 +752,7 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
752
752
  if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_incomplete' } };
753
753
  continue;
754
754
  }
755
- const parsed = safeParse(readStructuredText(result), null);
755
+ const parsed = safeParse(readOutputText(result), null);
756
756
  if (!isPlainObject(parsed)) {
757
757
  if (last) return { attempts, gateRepairs, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' } };
758
758
  continue;
@@ -872,7 +872,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
872
872
  if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
873
873
  continue;
874
874
  }
875
- const parsed = safeParse(readStructuredText(result), null);
875
+ const parsed = safeParse(readOutputText(result), null);
876
876
  firstEvidence = firstEvidence ?? rawEvidence(result);
877
877
  if (!isPlainObject(parsed)) {
878
878
  lastIssues = [{ path: 'plan', problem: 'la respuesta no es un objeto JSON válido' }];
@@ -931,7 +931,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
931
931
  }
932
932
 
933
933
  function rawEvidence(result) {
934
- const text = str(readStructuredText(result)).trim();
934
+ const text = str(readOutputText(result)).trim();
935
935
  if (text) return text.slice(0, RAW_EXCERPT_MAX);
936
936
  try {
937
937
  const raw = JSON.stringify(result?.raw ?? result ?? null);
@@ -12,7 +12,6 @@ const {
12
12
  openEscalationReview,
13
13
  recordDoctorDecision,
14
14
  sendApprovedIndications,
15
- suggestDraft,
16
15
  syncEscalationReviewCase,
17
16
  } = require('../services/escalationReviewService');
18
17
 
@@ -63,16 +62,6 @@ const addEscalationReviewCallLogController = async (req, res) => {
63
62
  }
64
63
  };
65
64
 
66
- const suggestEscalationReviewDraftController = async (req, res) => {
67
- try {
68
- const { triggeredBy } = req.body || {};
69
- const draft = await suggestDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
70
- res.status(200).json({ success: true, draft });
71
- } catch (error) {
72
- respondWithError(res, error, 'generating escalation review draft', { reviewId: req.params?.id });
73
- }
74
- };
75
-
76
65
  const addEscalationReviewDraftController = async (req, res) => {
77
66
  try {
78
67
  const { doctorText, patientMessage, triggeredBy } = req.body || {};
@@ -182,6 +171,5 @@ module.exports = {
182
171
  openEscalationReviewController,
183
172
  recordEscalationReviewDecisionController,
184
173
  sendEscalationReviewIndicationsController,
185
- suggestEscalationReviewDraftController,
186
174
  syncEscalationReviewCaseController,
187
175
  };
@@ -46,7 +46,6 @@ const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
46
46
  const { createQueueAdapter } = require('../queue');
47
47
  const { ScheduledMessageJob } = require('../jobs/ScheduledMessageJob');
48
48
  const { TemplateApprovalJob } = require('../jobs/TemplateApprovalJob');
49
- const { WorkflowRunner } = require('./DeferredWorkRunner');
50
49
  const { invokeInteractiveRoute } = require('./interactiveRouteService');
51
50
 
52
51
  const { PhiProcessor } = require('./PhiProcessor');
@@ -136,8 +135,6 @@ class NexusMessaging {
136
135
  queueAdapter: this.queueAdapter,
137
136
  });
138
137
 
139
- this.workflowRunner = new WorkflowRunner({ queueAdapter: this.queueAdapter });
140
-
141
138
  this.phiProcessor = new PhiProcessor({
142
139
  encode: config.phi?.encode || false,
143
140
  ner: config.phi?.ner || null,
@@ -349,7 +346,6 @@ class NexusMessaging {
349
346
  getAssistantProcessor() { return this.assistantProcessor; }
350
347
  getLlmMonitor() { return this.llmMonitor; }
351
348
  getQueueAdapter() { return this.queueAdapter; }
352
- getWorkflowRunner() { return this.workflowRunner; }
353
349
  getPhiProcessor() { return this.phiProcessor; }
354
350
  isConnected() { return this.provider?.getConnectionStatus() ?? false; }
355
351
  isProcessing(chatId) { return this.batchingManager.isProcessing(chatId); }
@@ -1129,8 +1125,6 @@ class NexusMessaging {
1129
1125
  await withTimeout(this._reconciliationStopped, teardownMs, 'queueReconciliation.stop')
1130
1126
  .catch(error => logger.warn('[NexusMessaging] Reconciliation sweep did not settle in time', { error: error.message }));
1131
1127
 
1132
- if (this.workflowRunner) this.workflowRunner.stop();
1133
-
1134
1128
  if (this.queueAdapter) {
1135
1129
  await withTimeout(this.queueAdapter.shutdown(), teardownMs, 'queueAdapter.shutdown')
1136
1130
  .catch(error => logger.warn('[NexusMessaging] Queue shutdown did not finish', { error: error.message }));
package/lib/index.d.ts CHANGED
@@ -254,7 +254,6 @@ declare module '@peopl-health/nexus' {
254
254
  getAssistantProcessor(): AssistantProcessor;
255
255
  getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
256
256
  initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
257
- getWorkflowRunner(): WorkflowRunner;
258
257
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string }): Promise<void>;
259
258
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
260
259
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
@@ -548,17 +547,16 @@ declare module '@peopl-health/nexus' {
548
547
  export interface Workflow {
549
548
  kind: string;
550
549
  dedupeKey: (trigger: any) => string;
551
- prepare: (trigger: any, checkpoints?: any, save?: (patch: any) => Promise<void>) => Promise<any>;
552
- retrySchedule?: number[];
550
+ prepare: (trigger: any) => Promise<any>;
553
551
  }
554
552
 
555
553
  export interface WorkflowRunner {
556
554
  register(workflow: Workflow): Promise<Workflow>;
557
- enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string | null>;
558
- sweep(only?: string[]): Promise<string[]>;
559
- stop(): void;
555
+ enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string>;
560
556
  }
561
557
 
558
+ export function createWorkflowRunner(options: { queueAdapter: QueueAdapter }): WorkflowRunner;
559
+
562
560
  // Memory System
563
561
  export interface PatientMemoryDocument {
564
562
  _id: any;
package/lib/index.js CHANGED
@@ -301,6 +301,7 @@ class Nexus {
301
301
  }
302
302
 
303
303
  module.exports = {
304
+ createWorkflowRunner,
304
305
  Nexus,
305
306
  DrainingError,
306
307
  TwilioProvider,
@@ -121,7 +121,6 @@ const escalationReviewRouteDefinitions = {
121
121
  'GET /by-patient/:code': 'listEscalationReviewsController',
122
122
  'GET /:id': 'getEscalationReviewController',
123
123
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
124
- 'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
125
124
  'POST /:id/drafts': 'addEscalationReviewDraftController',
126
125
  'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
127
126
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
@@ -282,7 +281,6 @@ const builtInControllers = {
282
281
  listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
283
282
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
284
283
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
285
- suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
286
284
  addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
287
285
  handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
288
286
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
@@ -15,11 +15,6 @@ const AIRTABLE_API_URL = 'https://api.airtable.com/v0';
15
15
  const AXIOS_TIMEOUT_CODE = 'ECONNABORTED';
16
16
  const RETRY_BASE_DELAY_MS = 1000;
17
17
 
18
- function isPermanentAirtableError(error) {
19
- const status = error?.statusCode;
20
- return typeof status === 'number' && status >= 400 && status < 500 && status !== 429;
21
- }
22
-
23
18
  let isEvalMode = false;
24
19
 
25
20
  function setEvalMode(enabled) {
@@ -47,7 +42,6 @@ async function withAirtableRetry(operation, label, { retryNetworkErrors = true }
47
42
  const isTransient = TRANSIENT_STATUS_CODES.includes(error.statusCode)
48
43
  || (retryNetworkErrors && isTransientNetworkError(error));
49
44
  if (!isTransient || attempt === MAX_ATTEMPTS) {
50
- if (isPermanentAirtableError(error)) error.permanent = true;
51
45
  throw error;
52
46
  }
53
47
  const baseDelay = error.statusCode === RATE_LIMITED_STATUS ? RATE_LIMIT_DELAY_MS : RETRY_BASE_DELAY_MS;
@@ -242,7 +236,6 @@ async function upsertRecord(baseID, tableName, fields, options = {}, context = n
242
236
 
243
237
  module.exports = {
244
238
  setEvalMode,
245
- isPermanentAirtableError,
246
239
  addRecord,
247
240
  getRecords,
248
241
  getRecordByFilter,
@@ -16,7 +16,6 @@ const {
16
16
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
17
17
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
18
18
  const { sendMessage } = require('../core/NexusMessaging');
19
- const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
20
19
 
21
20
  const { getPatientInformation, logPatientChange } = require('./patientService');
22
21
  const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
@@ -358,45 +357,6 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
358
357
  return review;
359
358
  }
360
359
 
361
- // Generation writes nothing: it fills the two boxes the navigator then edits and saves with addDraft.
362
- // It is refused outside the statuses that accept a draft, so no one waits on a model for text that
363
- // the review could no longer keep.
364
- async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
365
- const reviewId = reviewIdOf(id);
366
- const operator = requiredText(requestedBy, 'requestedBy');
367
- const review = await loadReview(reviewId);
368
- if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
369
-
370
- const draft = await generateEscalationDraft({
371
- code: review.patientCode,
372
- callLogs: review.callLogs ?? [],
373
- reviewId: String(review._id),
374
- });
375
- // A generation run sends the patient's context to a model. That is what the audit exists to
376
- // record, so it is written before the failure is reported, not after it.
377
- if (draft.attempted) {
378
- const recorded = await audit(review, operator, requestId, draft.completed
379
- ? { action: 'draft_generated', protocolVersion: draft.protocolVersion }
380
- : { action: 'draft_generation_failed', reason: redactedError({ message: draft.reason }) });
381
- // logPatientChange swallows its own failures and answers null, so an unrecorded generation is
382
- // otherwise indistinguishable from a recorded one. Say so where operations will see it.
383
- if (!recorded) {
384
- logger.error('[EscalationReview] A draft generation reached a model but was not recorded in the audit log', {
385
- escalationReviewId: String(review._id),
386
- completed: Boolean(draft.completed),
387
- });
388
- }
389
- }
390
- if (!draft.completed) throw httpError(draft.configured === false ? 503 : 502, draft.reason);
391
-
392
- // Generating takes as long as a model call, and a review can be cancelled underneath it. Saying so
393
- // here is what stops a navigator from editing text that addDraft would then refuse to keep.
394
- const settled = await loadReview(reviewId);
395
- if (!DOCUMENTING_STATUSES.includes(settled.status)) throw httpError(409, STATUS_CONFLICT);
396
-
397
- return draft;
398
- }
399
-
400
360
  async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
401
361
  const reviewId = reviewIdOf(id);
402
362
  const operator = requiredText(writtenBy, 'writtenBy');
@@ -623,6 +583,5 @@ module.exports = {
623
583
  openEscalationReview,
624
584
  recordDoctorDecision,
625
585
  sendApprovedIndications,
626
- suggestDraft,
627
586
  syncEscalationReviewCase,
628
587
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.55.0-dev.8114",
3
+ "version": "5.55.0-dev.8128",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,13 +0,0 @@
1
- // Every structured sub-agent reads its text back the same way: the envelope carries output_text
2
- // when the provider flattened it, and otherwise the text lives in the first message part. Keeping
3
- // one copy is what stops two services from disagreeing when a provider envelope changes.
4
- function readStructuredText(result) {
5
- if (result?.output_text) return result.output_text;
6
- const output = Array.isArray(result?.output) ? result.output : [];
7
- const message = output.find((item) => item.type === 'message');
8
- const content = Array.isArray(message?.content) ? message.content : [];
9
- const part = content.find((candidate) => typeof candidate?.text === 'string');
10
- return part?.text || '';
11
- }
12
-
13
- module.exports = { readStructuredText };
@@ -1,216 +0,0 @@
1
- const PROTOCOL_VERSION = '2026-09-18';
2
-
3
- const MEDICAL_REVIEW = 'valoración médica';
4
-
5
- function deepFreeze(value) {
6
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
7
- Object.freeze(value);
8
- for (const nested of Object.values(value)) deepFreeze(nested);
9
- }
10
- return value;
11
- }
12
-
13
- const SYMPTOM_RELIEF_PROTOCOL = deepFreeze([
14
- {
15
- key: 'nausea_vomito',
16
- label: 'Náusea y vómito',
17
- options: [
18
- { grade: 1, brand: 'AMAL', drug: 'Ondansetrón', strength: '8 mg', instructions: '1 tableta cada 24 horas por 5 días' },
19
- ],
20
- },
21
- {
22
- key: 'reflujo',
23
- label: 'Reflujo',
24
- options: [
25
- {
26
- grade: 1,
27
- brand: null,
28
- drug: 'Esomeprazol',
29
- strength: '40 mg',
30
- instructions: '1 cápsula cada 24 horas por 5 días',
31
- alternative: {
32
- when: 'la paciente ya está tomando esomeprazol',
33
- brand: null,
34
- drug: 'Famotidina',
35
- strength: '40 mg',
36
- instructions: '1 tableta cada 24 horas por 5 días',
37
- },
38
- },
39
- ],
40
- },
41
- {
42
- key: 'diarrea',
43
- label: 'Diarrea',
44
- options: [
45
- {
46
- grade: 1,
47
- brand: null,
48
- drug: 'Loperamida',
49
- strength: '4 mg',
50
- instructions: '4 mg al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
51
- consider: true,
52
- },
53
- {
54
- grade: 2,
55
- brand: null,
56
- drug: 'Loperamida',
57
- strength: '4 mg',
58
- instructions: '4 mg al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
59
- ruleOutFirst: ['causa infecciosa', 'causa obstructiva', 'intolerancia'],
60
- },
61
- ],
62
- },
63
- {
64
- key: 'dolor_abdominal_colico',
65
- label: 'Dolor abdominal tipo cólico',
66
- options: [
67
- {
68
- grade: 1,
69
- brand: 'BUSCAPINA COMPUESTA',
70
- drug: 'Butilhioscina/Metamizol',
71
- strength: '10/250 mg',
72
- instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
73
- },
74
- ],
75
- },
76
- {
77
- key: 'estrenimiento',
78
- label: 'Estreñimiento',
79
- options: [
80
- { grade: 1, brand: 'SENOKOT', drug: 'Senósidos', strength: null, instructions: '2 tabletas cada noche por 5 días' },
81
- {
82
- grade: 2,
83
- brand: 'LACTULAX',
84
- drug: 'Lactulosa',
85
- strength: null,
86
- instructions: '10 ml cada 8 horas hasta lograr evacuación, después suspender',
87
- },
88
- ],
89
- },
90
- {
91
- key: 'mucositis',
92
- label: 'Mucositis',
93
- options: [
94
- {
95
- grade: 1,
96
- brand: null,
97
- drug: 'Colutorios alcalinos',
98
- strength: '½ L de agua con 1 cucharadita de sal y 2 cucharaditas de bicarbonato',
99
- instructions: 'enjuagues y gárgaras de 1 minuto cada 6 horas por 5 días',
100
- isPharmacological: false,
101
- },
102
- {
103
- grade: 2,
104
- brand: 'VELIAN',
105
- drug: 'Dexketoprofeno',
106
- strength: '25 mg/10 ml en sobres',
107
- instructions: '1 sobre cada 8 horas, 30 minutos antes de los alimentos, y tragar, por 7 días',
108
- escalateIf: `si persiste, ${MEDICAL_REVIEW}`,
109
- },
110
- ],
111
- },
112
- {
113
- key: 'dolor',
114
- label: 'Dolor',
115
- options: [
116
- {
117
- grade: 1,
118
- brand: 'TEMPRA / TYLENOL',
119
- drug: 'Paracetamol',
120
- strength: '750 mg',
121
- instructions: '1 a 2 tabletas cada 8 horas por razón necesaria, por 5 días',
122
- },
123
- {
124
- grade: 2,
125
- brand: 'CELEBREX',
126
- drug: 'Celecoxib',
127
- strength: '200 mg',
128
- instructions: '1 cápsula cada 24 horas con alimentos por 5 días',
129
- steppedUpFromGrade: 1,
130
- escalateIf: `siempre, ${MEDICAL_REVIEW}`,
131
- },
132
- ],
133
- },
134
- {
135
- key: 'neuropatia',
136
- label: 'Neuropatía',
137
- alwaysEscalate: MEDICAL_REVIEW,
138
- recognition: 'ardor, sensación de adormecimiento o piquetes; sigue el trayecto de un nervio, o aparece en manos y pies al mismo tiempo',
139
- options: [],
140
- },
141
- {
142
- key: 'sindrome_mano_pie',
143
- label: 'Síndrome mano-pie',
144
- options: [
145
- {
146
- grade: 1,
147
- brand: 'CERAVE',
148
- drug: 'Ceramidas',
149
- strength: null,
150
- instructions: '2 a 3 veces al día de forma continua',
151
- isPharmacological: false,
152
- },
153
- {
154
- grade: 2,
155
- brand: 'NUTRAPLUS',
156
- drug: 'Urea',
157
- strength: '10%',
158
- instructions: 'capa fina cada 12 horas de forma continua',
159
- },
160
- ],
161
- },
162
- {
163
- key: 'rinitis_alergia',
164
- label: 'Rinitis o alergia',
165
- options: [
166
- { grade: 1, brand: 'REACTINE', drug: 'Cetirizina', strength: '10 mg', instructions: '1 tableta cada 24 horas por 7 días' },
167
- { grade: 2, brand: 'REACTINE', drug: 'Cetirizina', strength: '10 mg', instructions: '1 tableta cada 24 horas por 7 días' },
168
- ],
169
- },
170
- {
171
- key: 'insomnio',
172
- label: 'Insomnio',
173
- options: [
174
- { grade: 1, brand: 'MELATOL', drug: 'Melatonina', strength: '3 mg', instructions: '1 tableta cada 24 horas por la noche por 14 días' },
175
- { grade: 2, brand: 'MELATOL', drug: 'Melatonina', strength: '3 mg', instructions: '1 tableta cada 24 horas por la noche por 14 días' },
176
- ],
177
- },
178
- ]);
179
-
180
- const byKey = new Map(SYMPTOM_RELIEF_PROTOCOL.map((entry) => [entry.key, entry]));
181
-
182
- function protocolFor(symptomKey, grade) {
183
- const entry = byKey.get(String(symptomKey ?? '').trim());
184
- if (!entry) return null;
185
-
186
- const option = entry.options.find((candidate) => candidate.grade === grade) ?? null;
187
- return {
188
- key: entry.key,
189
- label: entry.label,
190
- grade,
191
- option,
192
- alwaysEscalate: entry.alwaysEscalate ?? null,
193
- recognition: entry.recognition ?? null,
194
- hasNoOptionForGrade: option === null,
195
- };
196
- }
197
-
198
- function protocolExcerpt(symptoms = []) {
199
- const seen = new Set();
200
- const excerpt = [];
201
- for (const { key, grade } of symptoms) {
202
- const id = `${key}:${grade}`;
203
- if (seen.has(id)) continue;
204
- seen.add(id);
205
- const entry = protocolFor(key, grade);
206
- if (entry) excerpt.push(entry);
207
- }
208
- return excerpt;
209
- }
210
-
211
- module.exports = {
212
- PROTOCOL_VERSION,
213
- SYMPTOM_RELIEF_PROTOCOL,
214
- protocolFor,
215
- protocolExcerpt,
216
- };
@@ -1,112 +0,0 @@
1
- const { getEscalationDraft } = require('../config/subAgentsConfig');
2
-
3
- const { PROTOCOL_VERSION, SYMPTOM_RELIEF_PROTOCOL } = require('../protocols/symptomReliefProtocol');
4
-
5
- const { createLLMProvider } = require('../providers/createLLMProvider');
6
-
7
- const { readStructuredText } = require('../helpers/structuredTextHelper');
8
-
9
- const { getEscalationContext } = require('../../services/escalationContextService');
10
-
11
- const { logger } = require('../../utils/logger');
12
- const { safeParse } = require('../../utils/jsonUtils');
13
- const { withTiming } = require('../../utils/tracingDecorator');
14
-
15
- const CONVERSATION_TURNS = 40;
16
- const TRIAGE_LIMIT = 3;
17
- const CALL_LOG_LIMIT = 10;
18
-
19
- const trimmed = (value) => String(value ?? '').trim();
20
-
21
- function buildDraftInput({ context, callLogs, protocol }) {
22
- const conversation = Array.isArray(context?.conversation)
23
- ? context.conversation.slice(-CONVERSATION_TURNS)
24
- : context?.conversation ?? null;
25
-
26
- const triages = Array.isArray(context?.triages)
27
- ? context.triages.slice(0, TRIAGE_LIMIT)
28
- : context?.triages ?? null;
29
-
30
- return {
31
- protocolVersion: PROTOCOL_VERSION,
32
- protocol,
33
- patient: {
34
- clinicalContext: context?.agentContext ?? null,
35
- conversation,
36
- triages,
37
- carePlan: context?.carePlan ?? null,
38
- history: context?.history ?? null,
39
- },
40
- call: callLogs.slice(-CALL_LOG_LIMIT).map((log) => ({
41
- outcome: log?.outcome ?? null,
42
- notes: trimmed(log?.notes) || null,
43
- calledAt: log?.calledAt ?? null,
44
- })),
45
- sectionsUnavailable: context?.degradedSections ?? [],
46
- };
47
- }
48
-
49
- function draftProvider() {
50
- try {
51
- return createLLMProvider({ variant: 'anthropic' });
52
- } catch (error) {
53
- logger.warn('[escalationDraft] no provider available; not generating', { error: error.message });
54
- return null;
55
- }
56
- }
57
-
58
- async function generateEscalationDraft({ code, callLogs = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
59
- const { presetId } = await getEscalationDraft();
60
- const llm = provider ?? draftProvider();
61
-
62
- if (!presetId || !llm?.runStructured) {
63
- return { completed: false, configured: false, reason: 'escalation draft generation is not configured' };
64
- }
65
-
66
- const context = await getEscalationContext({ code, now });
67
- const input = buildDraftInput({ context, callLogs, protocol: SYMPTOM_RELIEF_PROTOCOL });
68
-
69
- // Past this point a generation run was issued. Whether the request actually left the process is
70
- // not knowable here — the provider resolves the preset and validates the schema before it calls
71
- // its client — so every exit reports `attempted`, meaning a run happened and ended this way, and
72
- // never that the context was certainly disclosed. Over-recording an attempt is the safe direction
73
- // for an audit trail; missing a real disclosure is not.
74
- let result;
75
- let durationMs;
76
- try {
77
- ({ result, durationMs } = await withTiming(() => llm.runStructured({
78
- presetId,
79
- input: [{ role: 'user', content: JSON.stringify(input) }],
80
- metadata: { generator: 'escalation-draft', reviewId: reviewId ?? undefined },
81
- })));
82
- } catch (error) {
83
- logger.error('[escalationDraft] the provider failed', { error: error.message, stack: error.stack, reviewId });
84
- return { completed: false, attempted: true, reason: 'the model could not be reached' };
85
- }
86
- trace?.addSubCall({ response: result, durationMs, presetId });
87
-
88
- if (result?.status && result.status !== 'completed') {
89
- logger.warn('[escalationDraft] generation did not complete', { status: result.status, reviewId });
90
- return { completed: false, attempted: true, reason: `generation incomplete: status=${result.status}` };
91
- }
92
-
93
- const parsed = safeParse(readStructuredText(result), null);
94
- const doctorText = trimmed(parsed?.doctorText);
95
- const patientMessage = trimmed(parsed?.patientMessage);
96
-
97
- if (!doctorText || !patientMessage) {
98
- logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
99
- return { completed: false, attempted: true, reason: 'the model returned no usable text' };
100
- }
101
-
102
- return {
103
- completed: true,
104
- attempted: true,
105
- doctorText,
106
- patientMessage,
107
- protocolVersion: PROTOCOL_VERSION,
108
- sectionsUnavailable: context.degradedSections ?? [],
109
- };
110
- }
111
-
112
- module.exports = { generateEscalationDraft, buildDraftInput };
@@ -1,257 +0,0 @@
1
- const { describeThrown } = require('../utils/errorUtils');
2
- const { logger } = require('../utils/logger');
3
-
4
- const { DeferredWork, RETENTION_MS } = require('../models/deferredWorkModel');
5
-
6
- const STALE_CLAIM_MS = 5 * 60 * 1000;
7
- const MINUTE_MS = 60 * 1000;
8
- const INDEX_TIMEOUT_MS = 1000;
9
- const SWEEP_INTERVAL_MS = 60 * 1000;
10
-
11
- let indexesReady = null;
12
-
13
- function ensureIndexes() {
14
- if (!indexesReady) {
15
- indexesReady = DeferredWork.init().catch((error) => {
16
- indexesReady = null;
17
- logger.error('[WorkflowRunner] Index build failed, dedupe and retention are not guaranteed', { error: error.message });
18
- });
19
- }
20
- return indexesReady;
21
- }
22
-
23
- function withIndexTimeout(promise) {
24
- let timer;
25
- const timeout = new Promise((resolve) => {
26
- timer = setTimeout(resolve, INDEX_TIMEOUT_MS);
27
- timer.unref();
28
- });
29
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
30
- }
31
-
32
- class WorkflowRunner {
33
- constructor({ queueAdapter, sweepIntervalMs = SWEEP_INTERVAL_MS } = {}) {
34
- if (!queueAdapter) throw new Error('WorkflowRunner requires a queueAdapter');
35
- this.queueAdapter = queueAdapter;
36
- this.sweepIntervalMs = sweepIntervalMs;
37
- this.sweepTimer = null;
38
- this.timers = new Map();
39
- this.workflows = new Map();
40
- this.stopped = false;
41
- }
42
-
43
- async register(workflow = {}) {
44
- if (!workflow.kind || typeof workflow.kind !== 'string') throw new Error('workflow requires a kind');
45
- if (workflow.kind.includes('__')) throw new Error(`workflow '${workflow.kind}' must not contain '__' (reserved as the jobId delimiter)`);
46
- if (typeof workflow.dedupeKey !== 'function') throw new Error(`workflow '${workflow.kind}' requires a dedupeKey function`);
47
- if (typeof workflow.prepare !== 'function') throw new Error(`workflow '${workflow.kind}' requires a prepare function`);
48
- if (this.workflows.has(workflow.kind)) throw new Error(`workflow '${workflow.kind}' is already registered`);
49
- if (workflow.retrySchedule !== undefined) {
50
- if (!Array.isArray(workflow.retrySchedule) || !workflow.retrySchedule.length) {
51
- throw new Error(`workflow '${workflow.kind}' requires a non-empty retrySchedule array`);
52
- }
53
- if (workflow.retrySchedule.some((minutes) => !Number.isFinite(minutes) || minutes <= 0)) {
54
- throw new Error(`workflow '${workflow.kind}' requires retrySchedule entries to be positive minutes`);
55
- }
56
- if (workflow.retrySchedule.some((minutes) => minutes * MINUTE_MS >= RETENTION_MS)) {
57
- throw new Error(`workflow '${workflow.kind}' requires retrySchedule entries under the ${RETENTION_MS / MINUTE_MS}m retention, or the record expires before the attempt fires`);
58
- }
59
- }
60
-
61
- this.workflows.set(workflow.kind, workflow);
62
- if (workflow.retrySchedule) {
63
- await this.sweep([workflow.kind]).catch((error) => {
64
- logger.error('[WorkflowRunner] Sweep on register failed', { kind: workflow.kind, error: error.message });
65
- });
66
- this._startSweeping();
67
- return workflow;
68
- }
69
-
70
- try {
71
- await this.queueAdapter.process(workflow.kind, (trigger) => workflow.prepare(trigger));
72
- } catch (error) {
73
- this.workflows.delete(workflow.kind);
74
- throw error;
75
- }
76
- return workflow;
77
- }
78
-
79
- enqueue(kind, trigger, options = {}) {
80
- const workflow = this.workflows.get(kind);
81
- if (!workflow) throw new Error(`no workflow registered for '${kind}'`);
82
- const dedupeKey = workflow.dedupeKey(trigger);
83
- if (dedupeKey == null || (typeof dedupeKey === 'string' && !dedupeKey.trim())) {
84
- throw new Error(`workflow '${kind}' produced an empty dedupe key`);
85
- }
86
- if (typeof dedupeKey !== 'string') throw new Error(`workflow '${kind}' produced a non-string dedupe key`);
87
- if (!workflow.retrySchedule) {
88
- return this.queueAdapter.enqueue(kind, trigger, { ...options, jobId: `${kind}__${dedupeKey}` });
89
- }
90
- return this._armDeferred(workflow, trigger, dedupeKey);
91
- }
92
-
93
- async sweep(only = null) {
94
- const deferredKinds = [...this.workflows.values()].filter((w) => w.retrySchedule).map((w) => w.kind);
95
- const kinds = only ? deferredKinds.filter((kind) => only.includes(kind)) : deferredKinds;
96
- if (!kinds.length) return [];
97
-
98
- const orphaned = await DeferredWork.find({
99
- kind: { $in: kinds },
100
- $or: [
101
- { status: 'pending' },
102
- { status: 'processing', claimedAt: { $lt: new Date(Date.now() - STALE_CLAIM_MS) } }
103
- ]
104
- });
105
-
106
- const rearmed = orphaned.map((work) => this._arm(
107
- this.workflows.get(work.kind),
108
- work._id,
109
- this._delayUntilDue(work),
110
- ));
111
- if (rearmed.length) logger.info('[WorkflowRunner] Swept', { kinds, rearmed: rearmed.length });
112
- return rearmed;
113
- }
114
-
115
- _startSweeping() {
116
- if (this.stopped || this.sweepTimer || !this.sweepIntervalMs) return;
117
- this.sweepTimer = setInterval(() => {
118
- this.sweep().catch((error) => logger.error('[WorkflowRunner] Periodic sweep failed', { error: error.message }));
119
- }, this.sweepIntervalMs);
120
- this.sweepTimer.unref();
121
- }
122
-
123
- stop() {
124
- this.stopped = true;
125
- if (this.sweepTimer) clearInterval(this.sweepTimer);
126
- this.sweepTimer = null;
127
- for (const timer of this.timers.values()) clearTimeout(timer);
128
- this.timers.clear();
129
- }
130
-
131
- async _armDeferred(workflow, trigger, dedupeKey) {
132
- const { kind } = workflow;
133
- await withIndexTimeout(ensureIndexes());
134
- const work = await DeferredWork.findOne({ kind, dedupeKey })
135
- || await DeferredWork.create({ kind, dedupeKey, trigger }).catch(async (error) => {
136
- if (error.code !== 11000) throw error;
137
- return await DeferredWork.findOne({ kind, dedupeKey });
138
- });
139
- if (work.status === 'abandoned') {
140
- const { modifiedCount } = await DeferredWork.updateOne(
141
- { _id: work._id, status: 'abandoned' },
142
- { $set: { status: 'pending', attempt: 0, nextAttemptAt: new Date(), lastError: null, claimedAt: null } }
143
- );
144
- if (!modifiedCount) return null;
145
- logger.info('[WorkflowRunner] Re-arming abandoned work', { kind, dedupeKey });
146
- return this._arm(workflow, work._id, 0);
147
- }
148
- if (work.status !== 'pending') {
149
- logger.info('[WorkflowRunner] Skipping, work is in flight or complete', { kind, dedupeKey, status: work.status });
150
- return null;
151
- }
152
- return this._arm(workflow, work._id, this._delayUntilDue(work));
153
- }
154
-
155
- _delayUntilDue(work) {
156
- return Math.max(0, new Date(work.nextAttemptAt).getTime() - Date.now());
157
- }
158
-
159
- _arm(workflow, workId, delayMs) {
160
- const id = String(workId);
161
- if (this.stopped) return id;
162
- clearTimeout(this.timers.get(id));
163
- const timer = setTimeout(() => {
164
- this.timers.delete(id);
165
- this._runDeferred(workflow, id).catch((error) => {
166
- logger.error('[WorkflowRunner] Deferred run failed', { kind: workflow.kind, deferredWorkId: id, error: error.message });
167
- });
168
- }, delayMs);
169
- timer.unref();
170
- this.timers.set(id, timer);
171
- return id;
172
- }
173
-
174
- async _runDeferred(workflow, deferredWorkId) {
175
- const claimedAt = new Date();
176
- const prior = await DeferredWork.findOneAndUpdate(
177
- {
178
- _id: deferredWorkId,
179
- $or: [
180
- { status: 'pending', nextAttemptAt: { $lte: claimedAt } },
181
- { status: 'processing', claimedAt: { $lt: new Date(claimedAt.getTime() - STALE_CLAIM_MS) } }
182
- ]
183
- },
184
- { $set: { status: 'processing', claimedAt } },
185
- { new: false }
186
- );
187
- if (!prior) {
188
- logger.info('[WorkflowRunner] Claimed elsewhere or not due', { kind: workflow.kind, deferredWorkId });
189
- return { claimed: false };
190
- }
191
-
192
- const reclaimed = prior.status === 'processing';
193
- const work = { ...prior.toObject(), attempt: prior.attempt + (reclaimed ? 1 : 0) };
194
- if (reclaimed) await this._write(work, claimedAt, { attempt: work.attempt });
195
-
196
- const checkpoints = { ...(work.checkpoints || {}) };
197
- const save = async (patch) => {
198
- Object.assign(checkpoints, patch);
199
- const $set = {};
200
- for (const [key, value] of Object.entries(patch || {})) $set[`checkpoints.${key}`] = value;
201
- if (Object.keys($set).length) await this._write(work, claimedAt, $set);
202
- };
203
-
204
- try {
205
- await workflow.prepare(work.trigger, checkpoints, save);
206
- } catch (error) {
207
- return await this._rescheduleOrAbandon(workflow, work, claimedAt, error);
208
- }
209
- await this._write(work, claimedAt, { status: 'done', claimedAt: null });
210
- return { status: 'done' };
211
- }
212
-
213
- async _write(work, claimedAt, $set) {
214
- const { matchedCount } = await DeferredWork.updateOne({ _id: work._id, claimedAt }, { $set });
215
- if (!matchedCount) logger.warn('[WorkflowRunner] Claim lost, write discarded', { deferredWorkId: String(work._id) });
216
- return matchedCount > 0;
217
- }
218
-
219
- async _rescheduleOrAbandon(workflow, work, claimedAt, error) {
220
- const lastError = describeThrown(error);
221
- const delayMinutes = workflow.retrySchedule[work.attempt];
222
- if (error?.permanent === true || delayMinutes === undefined) {
223
- await this._write(work, claimedAt, { status: 'abandoned', lastError, claimedAt: null });
224
- logger.error('[WorkflowRunner] Abandoned', {
225
- kind: workflow.kind,
226
- dedupeKey: work.dedupeKey,
227
- attempt: work.attempt,
228
- permanent: error?.permanent === true,
229
- error: lastError
230
- });
231
- return { status: 'abandoned' };
232
- }
233
-
234
- const attempt = work.attempt + 1;
235
- const delayMs = delayMinutes * MINUTE_MS;
236
- const kept = await this._write(work, claimedAt, {
237
- status: 'pending',
238
- attempt,
239
- nextAttemptAt: new Date(Date.now() + delayMs),
240
- lastError,
241
- claimedAt: null
242
- });
243
- if (!kept) return { claimed: false };
244
-
245
- logger.warn('[WorkflowRunner] Rescheduled', {
246
- kind: workflow.kind,
247
- dedupeKey: work.dedupeKey,
248
- attempt,
249
- delayMinutes,
250
- error: lastError
251
- });
252
- this._arm(workflow, work._id, delayMs);
253
- return { status: 'pending', attempt };
254
- }
255
- }
256
-
257
- module.exports = { WorkflowRunner };
@@ -1,24 +0,0 @@
1
- const mongoose = require('mongoose');
2
-
3
- const STATUS_VALUES = ['pending', 'processing', 'done', 'abandoned'];
4
- const RETENTION_MS = 24 * 60 * 60 * 1000;
5
-
6
- const deferredWorkSchema = new mongoose.Schema({
7
- kind: { type: String, required: true },
8
- dedupeKey: { type: String, required: true },
9
- trigger: { type: mongoose.Schema.Types.Mixed, default: null },
10
- checkpoints: { type: mongoose.Schema.Types.Mixed, default: () => ({}) },
11
- status: { type: String, enum: STATUS_VALUES, default: 'pending' },
12
- attempt: { type: Number, default: 0 },
13
- nextAttemptAt: { type: Date, default: Date.now },
14
- claimedAt: { type: Date, default: null },
15
- lastError: { type: String, default: null }
16
- }, { timestamps: true });
17
-
18
- deferredWorkSchema.index({ kind: 1, dedupeKey: 1 }, { unique: true, name: 'dedupe_idx' });
19
- deferredWorkSchema.index({ status: 1, nextAttemptAt: 1 }, { name: 'due_idx' });
20
- deferredWorkSchema.index({ updatedAt: 1 }, { expireAfterSeconds: RETENTION_MS / 1000, name: 'ttl_idx' });
21
-
22
- const DeferredWork = mongoose.model('DeferredWork', deferredWorkSchema);
23
-
24
- module.exports = { DeferredWork, RETENTION_MS };