@memberjunction/ai-prompts 6.1.4 → 6.2.0-edge.1

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.
@@ -0,0 +1,583 @@
1
+ /**
2
+ * @fileoverview Abstract base runner for MemberJunction AI model executions.
3
+ *
4
+ * Encapsulates modality-agnostic machinery:
5
+ * - Candidate building and selection
6
+ * - Credential resolution and failover
7
+ * - Execution bounds and timeout management
8
+ * - AIPromptRun entity lifecycle tracking and persistence
9
+ * - Retry and failover helpers
10
+ *
11
+ * @module @memberjunction/ai-prompts
12
+ * @author MemberJunction.com
13
+ */
14
+ import { BaseEntitySaveQueue, Metadata, IMetadataProvider } from '@memberjunction/core';
15
+ import { MJAIModelVendorEntity } from '@memberjunction/core-entities';
16
+ import { MJAIModelEntityExtended, MJAIPromptEntityExtended, MJAIPromptRunEntityExtended, AIPromptParams, AIModelSelectionInfo } from '@memberjunction/ai-core-plus';
17
+ import { BaseResult, AIPromptConfiguration } from '@memberjunction/ai';
18
+ /**
19
+ * The composed bound applied to a single model call: the caller's cancellation token (if any) merged
20
+ * with the prompt's configured `AIPrompt.TimeoutMS` (if any).
21
+ *
22
+ * Produced by `AIPromptRunner.createExecutionBound` and consumed by the bounded ChatCompletion race.
23
+ * `Dispose()` MUST be called when the call settles so the timeout timer and abort listener are
24
+ * released.
25
+ */
26
+ export interface ExecutionBound {
27
+ /** Merged abort signal; `undefined` when there is neither a caller token nor a prompt timeout. */
28
+ Signal?: AbortSignal;
29
+ /** The prompt-configured timeout in ms, when one applies. */
30
+ TimeoutMS?: number;
31
+ /** True once the TIMEOUT (not the caller's token) fired — used to build the right error. */
32
+ TimedOut: () => boolean;
33
+ /** Releases the timer and the caller-token listener. Safe to call multiple times. */
34
+ Dispose: () => void;
35
+ }
36
+ /**
37
+ * Represents a model-vendor pair candidate for execution
38
+ */
39
+ export interface ModelVendorCandidate {
40
+ model: MJAIModelEntityExtended;
41
+ vendorId?: string;
42
+ vendorName?: string;
43
+ driverClass: string;
44
+ apiName?: string;
45
+ supportsEffortLevel?: boolean;
46
+ effortLevel?: number;
47
+ /**
48
+ * The `PromptConfiguration` bag of the `AIPromptModel` row this candidate came from, when it came
49
+ * from one. Threaded like `effortLevel` rather than looked up later, because a candidate sourced
50
+ * from power-rank or model-type has NO prompt-model row and must contribute no override.
51
+ */
52
+ promptModelConfiguration?: AIPromptConfiguration | null;
53
+ isPreferredVendor: boolean;
54
+ priority: number;
55
+ source: 'explicit' | 'prompt-model' | 'model-type' | 'power-rank' | 'power-match-fallback';
56
+ }
57
+ /**
58
+ * Configuration for failover behavior when primary model fails.
59
+ *
60
+ * Exported because it is the return type of `AIPromptRunner.getFailoverConfiguration`, a
61
+ * `protected` method documented as an override point — a subclass cannot name its own return type
62
+ * otherwise, which made the documented extension point unusable from outside this package.
63
+ */
64
+ export interface FailoverConfiguration {
65
+ strategy: 'SameModelDifferentVendor' | 'NextBestModel' | 'PowerRank' | 'None';
66
+ maxAttempts: number;
67
+ delaySeconds: number;
68
+ modelStrategy?: 'PreferSameModel' | 'PreferDifferentModel' | 'RequireSameModel';
69
+ errorScope?: 'All' | 'NetworkOnly' | 'RateLimitOnly' | 'ServiceErrorOnly';
70
+ }
71
+ /**
72
+ * Tracks information about a failover attempt
73
+ */
74
+ export interface FailoverAttempt {
75
+ attemptNumber: number;
76
+ modelId: string;
77
+ vendorId?: string;
78
+ error: Error;
79
+ errorType: string;
80
+ duration: number;
81
+ timestamp: Date;
82
+ }
83
+ /**
84
+ * Shared machinery for runners that invoke a model and record the call as an `MJ: AI Prompt Runs`
85
+ * row: candidate model/vendor selection, credential resolution, execution bounds (timeout and
86
+ * cancellation), failover helpers, and the prompt-run save queue.
87
+ *
88
+ * `AIPromptRunner`, the chat runner, is built on it. Subclasses declare the model type they run
89
+ * through {@link BaseModelRunner.RequiredModelType}.
90
+ */
91
+ export declare abstract class BaseModelRunner {
92
+ /**
93
+ * The model type this runner requires, as the **name** of an `MJ: AI Model Types` row: `'LLM'` for
94
+ * `AIPromptRunner`, `'Embeddings'` (`AIEngine.Instance.EmbeddingModelTypeName`) for an embeddings
95
+ * runner.
96
+ *
97
+ * The contract:
98
+ * - It is a name, not an ID, so a subclass can declare it without a metadata lookup. The base
99
+ * resolves it to the type's ID through `AIEngine.Instance.ModelTypes` ({@link RequiredModelTypeID}:
100
+ * a case-insensitive, trimmed name match) and compares each model's `AIModelTypeID` with that ID
101
+ * using `UUIDsEqual`, on every candidate-selection path. Names are never compared with each other,
102
+ * and a name that matches no model type is an error.
103
+ * - It is a hard floor. `AIPrompt.AIModelTypeID` may equal it. Model types are flat, so a prompt type
104
+ * that differs would widen or contradict the floor, and the runner refuses the prompt with an error
105
+ * naming both the prompt's configured type and the runner's required type.
106
+ * - `AIPrompt.AIModelTypeID = NULL` means "whatever the runner requires" (not "any model").
107
+ * This closes a footgun where prompts with an unset column drew models of every type.
108
+ * - Bound models (`AIPromptModel`) of a different type are skipped during candidate building
109
+ * with a `LogStatus` warning, but do not fail the prompt unless no valid candidates remain.
110
+ * - Model overrides of a different type return no candidate (an override cannot violate the
111
+ * runner's hard floor).
112
+ */
113
+ abstract get RequiredModelType(): string;
114
+ protected _provider: IMetadataProvider | null;
115
+ protected _metadata: Metadata;
116
+ /**
117
+ * Optional metadata provider override. Callers should set
118
+ * `instance.Provider = providerToUse` before invoking run methods
119
+ * in multi-provider contexts. Falls back to the global default provider when unset.
120
+ */
121
+ get Provider(): IMetadataProvider;
122
+ set Provider(value: IMetadataProvider | null);
123
+ /**
124
+ * Performs robust validation of an API key
125
+ * @returns true if the API key is valid (not null, undefined, or empty/whitespace)
126
+ */
127
+ private isValidAPIKey;
128
+ /**
129
+ * Internal logging helper that wraps LogStatusEx with verbose control
130
+ * @param message The message to log
131
+ * @param verboseOnly Whether this is a verbose-only message
132
+ * @param params Optional prompt parameters for custom verbose check
133
+ */
134
+ protected logStatus(message: string, verboseOnly?: boolean, params?: AIPromptParams): void;
135
+ /**
136
+ * The category {@link logError} records when the caller passes none. Override it so a runner's
137
+ * uncategorized errors are attributed to that runner rather than to the base.
138
+ */
139
+ protected get DefaultLogCategory(): string;
140
+ /**
141
+ * Helper method for enhanced error logging with metadata
142
+ */
143
+ protected logError(error: Error | string, options?: {
144
+ category?: string;
145
+ metadata?: Record<string, any>;
146
+ prompt?: MJAIPromptEntityExtended;
147
+ model?: MJAIModelEntityExtended;
148
+ severity?: 'warning' | 'error' | 'critical';
149
+ maxErrorLength?: number;
150
+ }): void;
151
+ /**
152
+ * Checks if a model vendor is configured as an inference provider.
153
+ * Delegates to the memoized {@link AIEngine.IsInferenceProvider} helper so the
154
+ * "Inference Provider" vendor-type lookup happens once per engine load rather than on
155
+ * every candidate in every selection pass.
156
+ * @param modelVendor The model vendor to check
157
+ * @returns true if the vendor is an inference provider
158
+ */
159
+ protected IsInferenceProvider(modelVendor: MJAIModelVendorEntity): boolean;
160
+ /**
161
+ * Fire-and-forget AIPromptRun persistence. Prompt-run logging never blocks the execution path on a
162
+ * DB round-trip; the shared {@link BaseEntitySaveQueue} sequences saves for the SAME entity (the
163
+ * initial 'Running' INSERT always completes before the finalize UPDATE, and the finalize mutation
164
+ * runs INSIDE the post-INSERT task so a slow INSERT can never clobber the finalized row). Failures
165
+ * stay in this runner's structured log stream via the queue's `onError` hook.
166
+ */
167
+ protected _promptRunQueue: BaseEntitySaveQueue;
168
+ /**
169
+ * Resolves credentials for AI model execution using a hierarchical resolution system.
170
+ *
171
+ * Resolution priority (highest to lowest):
172
+ * 1. Per-request override: params.credentialId
173
+ * 2. Prompt-Model specific: AIPromptModel.CredentialID
174
+ * 3. Model-Vendor specific: AIModelVendor.CredentialID
175
+ * 4. Vendor default: AIVendor.CredentialID
176
+ * 5. Legacy: params.apiKeys[] array
177
+ * 6. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
178
+ *
179
+ * IMPORTANT: When ANY credential ID is found (priorities 1-4), the system uses
180
+ * the Credentials path and ignores legacy methods (priorities 5-6).
181
+ *
182
+ * @param driverClass - The driver class name (e.g., 'OpenAILLM')
183
+ * @param promptId - The prompt ID for looking up AIPromptModel credentials
184
+ * @param modelId - The model ID for looking up AIPromptModel and AIModelVendor credentials
185
+ * @param vendorId - The vendor ID for looking up AIModelVendor and AIVendor credentials
186
+ * @param params - The prompt execution parameters containing contextUser and optional credentialId
187
+ * @returns The API key/configuration string to pass to the LLM constructor
188
+ */
189
+ protected ResolveCredentialForExecution(driverClass: string, promptId: string | undefined, modelId: string | undefined, vendorId: string | undefined, params: AIPromptParams): Promise<string>;
190
+ /**
191
+ * Attempts to resolve credentials from bindings with priority-based failover.
192
+ * Tries each binding in priority order until one succeeds.
193
+ */
194
+ private tryCredentialBindingsWithFailover;
195
+ /**
196
+ * Attempts to resolve a single credential, returning null on failure for failover support.
197
+ */
198
+ private tryResolveCredential;
199
+ /**
200
+ * Resolves a credential by its explicit ID (used for per-request override).
201
+ * This does not support failover since it's an explicit choice.
202
+ */
203
+ private resolveCredentialById;
204
+ /**
205
+ * Finds a default credential matching a specific credential type.
206
+ */
207
+ private findDefaultCredentialByType;
208
+ /**
209
+ * Checks if credentials are available for a given model-vendor combination.
210
+ * This is a pre-flight check used during model selection to determine which
211
+ * candidates have valid authentication configured.
212
+ *
213
+ * Checks the credential hierarchy:
214
+ * 1. Per-request override: params.credentialId
215
+ * 2. PromptModel bindings: AICredentialBinding WHERE BindingType='PromptModel'
216
+ * 3. ModelVendor bindings: AICredentialBinding WHERE BindingType='ModelVendor'
217
+ * 4. Vendor bindings: AICredentialBinding WHERE BindingType='Vendor'
218
+ * 5. Type-based default: Credential.IsDefault=1 matching AIVendor.CredentialTypeID
219
+ * 6. Legacy: params.apiKeys[] array
220
+ * 7. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
221
+ *
222
+ * @param driverClass - The driver class name (e.g., 'OpenAILLM')
223
+ * @param promptId - The prompt ID for looking up AIPromptModel bindings
224
+ * @param modelId - The model ID for looking up AIPromptModel and AIModelVendor bindings
225
+ * @param vendorId - The vendor ID for looking up AIModelVendor and AIVendor bindings
226
+ * @param params - The prompt execution parameters
227
+ * @returns true if credentials are available, false otherwise
228
+ */
229
+ protected HasCredentialsAvailable(driverClass: string, promptId: string | undefined, modelId: string | undefined, vendorId: string | undefined, params?: AIPromptParams): boolean;
230
+ /**
231
+ * Resolves the runner's {@link RequiredModelType} name against `AIEngine.Instance.ModelTypes`
232
+ * (case-insensitive, trimmed) and returns its UUID. Callers compare models' `AIModelTypeID` with it
233
+ * using `UUIDsEqual`.
234
+ * Throws a descriptive error if the model type is not found in the engine metadata.
235
+ */
236
+ protected RequiredModelTypeID(): string;
237
+ /** The name of a model type for messages, or its ID when the engine doesn't know it. */
238
+ private modelTypeName;
239
+ /**
240
+ * Asserts that the prompt's configured model type matches the runner's required model type.
241
+ * If `prompt.AIModelTypeID` is null or undefined, does not throw (the runner's required type applies).
242
+ * If `prompt.AIModelTypeID` is set and does not match {@link RequiredModelTypeID}, throws a descriptive
243
+ * error naming the prompt, the prompt's configured type (resolved to name if possible), and the runner's
244
+ * required type.
245
+ */
246
+ protected AssertPromptMatchesRequiredType(prompt: MJAIPromptEntityExtended): void;
247
+ /**
248
+ * Builds a unified, ordered list of model-vendor candidates based on all selection criteria.
249
+ * Uses a 3-phase approach to properly handle SelectionStrategy='Specific' with AIPromptModel priorities.
250
+ *
251
+ * Phase 1: Handle explicit model ID (highest priority)
252
+ * Phase 2: Check if SelectionStrategy='Specific' with AIPromptModel entries - use ONLY those with AIPromptModel priorities
253
+ * Phase 3: Use general selection strategy (fallback) - blended priorities from legacy behavior
254
+ *
255
+ * @param prompt - The AI prompt with selection criteria
256
+ * @param explicitModelId - Explicitly specified model ID (highest priority)
257
+ * @param configurationId - Configuration ID for filtering
258
+ * @param preferredVendorId - Preferred vendor ID
259
+ * @returns Ordered array of model-vendor candidates (highest priority first)
260
+ */
261
+ protected BuildModelVendorCandidates(prompt: MJAIPromptEntityExtended, explicitModelId?: string, configurationId?: string, preferredVendorId?: string, verbose?: boolean): ModelVendorCandidate[];
262
+ /**
263
+ * PHASE 1: Build candidates for explicitly specified model ID.
264
+ * Returns candidates for the single model if it's active. Throws if the model is of a different type
265
+ * than the runner requires: the caller asked for that model by ID, so running a different one instead
266
+ * would be wrong, and an empty result would surface only a generic "no candidates" message.
267
+ */
268
+ private buildCandidatesForExplicitModel;
269
+ /**
270
+ * PHASE 2: Build candidates for 'Specific' selection strategy.
271
+ * Uses AIPromptModel configuration with clean ranking:
272
+ * 1. Config-matching models first (by priority DESC)
273
+ * 2. Then universal (null config) models (by priority DESC)
274
+ */
275
+ private buildCandidatesForSpecificStrategy;
276
+ /**
277
+ * Appends fallback candidates from the global model pool, sorted by proximity to the
278
+ * average power rank of the originally configured models. This ensures that when
279
+ * specific models lack credentials, the fallback uses models of similar capability
280
+ * rather than defaulting to the most or least powerful available model.
281
+ *
282
+ * Fallback candidates are given lower priority than any specific candidate so
283
+ * configured models are always preferred when their credentials are available.
284
+ */
285
+ private appendPowerMatchedFallbackCandidates;
286
+ /**
287
+ * Computes the target power rank from configured AIPromptModel records.
288
+ * Uses the weighted average (by priority) of the configured models' power ranks,
289
+ * so higher-priority models have more influence on the target.
290
+ * Falls back to simple average if priorities are all zero.
291
+ */
292
+ private computeTargetPowerRank;
293
+ /**
294
+ * Sorts models by proximity to a target power rank (closest first).
295
+ * When two models are equidistant, the higher-powered one is preferred.
296
+ */
297
+ private sortByPowerProximity;
298
+ /**
299
+ * PHASE 3: Build candidates for general selection strategies ('Default' or 'ByPower').
300
+ * Uses configuration-aware fallback hierarchy with legacy blended priority calculation.
301
+ */
302
+ private buildCandidatesForGeneralSelection;
303
+ /**
304
+ * Helper: Filter prompt models by configuration matching rules.
305
+ * Supports configuration inheritance - includes models from the entire inheritance chain.
306
+ */
307
+ private filterPromptModelsByConfiguration;
308
+ /**
309
+ * Helper: Sort prompt models for 'Specific' strategy.
310
+ * Respects configuration inheritance chain - child configs first, then parents, then null-config.
311
+ * Within each config level, sorts by priority DESC.
312
+ */
313
+ private sortPromptModelsForSpecificStrategy;
314
+ /**
315
+ * Helper: Build candidates from sorted AIPromptModel records.
316
+ * Expands VendorID=null to all vendors for that model.
317
+ */
318
+ private buildCandidatesFromPromptModels;
319
+ /**
320
+ * Helper: Create candidate for specific vendor from AIPromptModel.
321
+ */
322
+ private createCandidateForSpecificVendor;
323
+ /**
324
+ * Helper: Create candidates for all vendors of a model, sorted by vendor priority.
325
+ */
326
+ private createCandidatesForAllVendors;
327
+ /**
328
+ * Helper: true if this prompt has any AIPromptModel bindings at all, regardless of Status or
329
+ * ConfigurationID. Distinguishes "no bindings were ever configured" (general selection strategy
330
+ * should apply) from "bindings exist but are all Inactive" (no model should be selected).
331
+ */
332
+ private hasAnyPromptModelBindings;
333
+ /**
334
+ * Helper: Get prompt models for configuration with inheritance chain fallback.
335
+ * Walks the configuration inheritance chain looking for prompt models.
336
+ * Returns models from the first config in the chain that has any, or falls back to null-config.
337
+ */
338
+ private getPromptModelsForConfiguration;
339
+ /**
340
+ * Helper: Add prompt-specific candidates with blended priorities (legacy behavior).
341
+ */
342
+ private addPromptSpecificCandidates;
343
+ /**
344
+ * Helper: Add configuration fallback candidates from the inheritance chain.
345
+ * Adds models from parent configs (with decreasing priority) and null-config models as final fallback.
346
+ */
347
+ private addConfigurationFallbackCandidates;
348
+ /**
349
+ * Helper: Add strategy-based candidates when no prompt models exist.
350
+ */
351
+ private addStrategyBasedCandidates;
352
+ /**
353
+ * Helper: Get model pool filtered for strategy.
354
+ */
355
+ private getModelPoolForStrategy;
356
+ /**
357
+ * Helper: Sort model pool by selection strategy.
358
+ */
359
+ private sortModelPoolByStrategy;
360
+ /**
361
+ * Helper: Sort models by power preference.
362
+ */
363
+ private sortByPowerPreference;
364
+ /**
365
+ * Helper: Create candidates for a model with AIModelVendor priorities (legacy behavior).
366
+ */
367
+ private createCandidatesForModel;
368
+ /**
369
+ * Awaits all in-flight prompt-run saves queued by this runner instance. The normal execution path
370
+ * does NOT call this — prompt-run persistence is intentionally fire-and-forget. Exposed for tests
371
+ * and for callers that need the AIPromptRun rows durably written before proceeding.
372
+ */
373
+ WaitForPendingPromptRunSaves(): Promise<void>;
374
+ /**
375
+ * Creates the `MJ: AI Prompt Runs` record for one model call, fills the fields every runner shares,
376
+ * lets the subclass add its own request fields, then queues the INSERT (fire-and-forget).
377
+ *
378
+ * For prompt-based runners: the record is always tied to an `AIPrompt` and its `AIPromptParams`.
379
+ *
380
+ * @param applyRequestFields Sets the runner's own request columns. It runs once, after the shared
381
+ * fields are set and before the INSERT is queued, so everything it sets is on the inserted row.
382
+ * **It must be synchronous.** An `async` callback type-checks against this signature, but any
383
+ * field it sets after its first `await` races the INSERT and can miss the row.
384
+ */
385
+ protected CreateRunRecord(prompt: MJAIPromptEntityExtended, model: MJAIModelEntityExtended, params: AIPromptParams, startTime: Date, vendorId?: string, modelSelectionInfo?: AIModelSelectionInfo, applyRequestFields?: (promptRun: MJAIPromptRunEntityExtended) => void): Promise<MJAIPromptRunEntityExtended>;
386
+ /**
387
+ * Updates prompt run with successful failover tracking data
388
+ */
389
+ protected updatePromptRunWithFailoverSuccess(promptRun: MJAIPromptRunEntityExtended, failoverAttempts: FailoverAttempt[], currentModel: MJAIModelEntityExtended, currentVendorId: string | null): void;
390
+ /**
391
+ * Updates prompt run with failover failure tracking data
392
+ */
393
+ private updatePromptRunWithFailoverFailure;
394
+ /**
395
+ * Runs one model call across the failover candidates, in priority order: skips candidates with no
396
+ * credentials, lets processFailoverError decide retry / next candidate / stop, and records failover
397
+ * success or failure on the prompt run. The model call itself and the final error result are
398
+ * supplied by the subclass, so the loop works for any result type that extends BaseResult.
399
+ *
400
+ * For prompt-based runners: it takes the `AIPrompt` and `AIPromptParams` the call is for, and
401
+ * candidates that carry prompt-model fields (effort level, the `AIPromptModel` configuration).
402
+ *
403
+ * @param executeOnCandidate Makes the call on one candidate. It must use the candidate's own model,
404
+ * vendor, driver and prompt-model fields, not those of the first candidate.
405
+ * @param createErrorResult Builds the result returned when every candidate has failed.
406
+ */
407
+ protected ExecuteWithFailover<TResult extends BaseResult>(prompt: MJAIPromptEntityExtended, params: AIPromptParams, allCandidates: ModelVendorCandidate[], failoverConfig: FailoverConfiguration, executeOnCandidate: (candidate: ModelVendorCandidate) => Promise<TResult>, createErrorResult: (lastError: Error | null, failoverAttempts: FailoverAttempt[]) => TResult, promptRun?: MJAIPromptRunEntityExtended, credentialAvailability?: Map<string, boolean>): Promise<TResult>;
408
+ /**
409
+ * Engine-level default model-call timeout, in milliseconds, applied when the caller supplies no
410
+ * `AIPromptParams.timeoutMS`. `undefined` (the default) means NO implicit bound — a prompt run
411
+ * with neither a timeout nor a cancellation token stays unbounded, exactly as before, so this
412
+ * change is behavior-preserving for existing callers.
413
+ *
414
+ * Subclasses (or a host application's runner subclass) can override this to impose a global
415
+ * safety ceiling on every prompt call.
416
+ */
417
+ protected get DefaultPromptTimeoutMS(): number | undefined;
418
+ /**
419
+ * Resolves the per-model-call timeout: the caller's `AIPromptParams.timeoutMS`, else the runner's
420
+ * {@link DefaultPromptTimeoutMS}. Non-positive / non-numeric values mean "no timeout".
421
+ *
422
+ * The bound is applied PER MODEL CALL (not per prompt execution), which mirrors the parallel
423
+ * path's existing `taskTimeoutMS` semantics: each failover candidate / validation retry gets a
424
+ * fresh budget rather than sharing one wall-clock window.
425
+ *
426
+ * NOTE (issue #3064): there is deliberately NO prompt-entity source here yet — the `AIPrompt`
427
+ * table has no `TimeoutMS` column today. Once a migration adds one and CodeGen regenerates the
428
+ * entity, this becomes `prompt.TimeoutMS ?? params.timeoutMS ?? this.DefaultPromptTimeoutMS`
429
+ * and every bound below starts honoring the per-prompt configuration with no other change.
430
+ */
431
+ protected getEffectiveTimeoutMS(params: AIPromptParams): number | undefined;
432
+ /**
433
+ * Composes the caller-supplied cancellation token with the resolved model-call timeout into a
434
+ * single {@link AbortSignal} that bounds one model call. NEITHER bound is discarded:
435
+ *
436
+ * - caller token only → the caller's signal is used directly (behavior unchanged)
437
+ * - timeout only → an internal controller aborts after the timeout elapses
438
+ * - both → an internal controller relays the caller's abort AND fires on timeout;
439
+ * whichever happens first wins
440
+ * - neither → `Signal` is undefined and the call runs unbounded (legacy behavior)
441
+ *
442
+ * Implemented with an AbortController + relay listener rather than `AbortSignal.any()` so it works
443
+ * on Node 18 (where `AbortSignal.any` does not exist — it landed in Node 20.3).
444
+ */
445
+ protected createExecutionBound(prompt: MJAIPromptEntityExtended, params: AIPromptParams, cancellationToken?: AbortSignal): ExecutionBound;
446
+ /**
447
+ * Applies retry delay based on the prompt's retry strategy
448
+ */
449
+ /**
450
+ * Calculates retry delay for rate limit and other retriable errors.
451
+ * Uses the prompt's RetryStrategy and can respect suggested delays from provider.
452
+ */
453
+ private calculateRetryDelay;
454
+ protected ApplyRetryDelay(prompt: MJAIPromptEntityExtended, attemptNumber: number, suggestedDelaySeconds?: number): Promise<void>;
455
+ /**
456
+ * Filters out all candidates from a vendor when a vendor-level error occurs.
457
+ * Vendor-level errors affect all models from that vendor:
458
+ * - Authentication: Invalid API key
459
+ * - VendorValidationError: API schema/validation requirements
460
+ */
461
+ private filterVendorCandidates;
462
+ /**
463
+ * Handles rate limit errors by retrying the same model/vendor with backoff.
464
+ * Returns true if the caller should continue (retry), false if should proceed to failover.
465
+ */
466
+ private handleRateLimitRetry;
467
+ /**
468
+ * Processes a failover error (either from catch block or from failed ChatResult).
469
+ * Handles vendor filtering, rate limit retries, fatal error detection, and failover logic.
470
+ *
471
+ * @returns Decision object indicating whether to retry same model, continue to next candidate, or stop
472
+ */
473
+ private processFailoverError;
474
+ /**
475
+ * Queues the finalize UPDATE for a prompt-run record. Inside the queued task it sets, in order:
476
+ * the completion timing (`CompletedAt`, `ExecutionTimeMS`); the outcome (`Success`, and `Status` =
477
+ * `'Completed'` or `'Failed'` from it); then the subclass's result fields; then the token rollups and
478
+ * `TotalCost`.
479
+ *
480
+ * The outcome is a parameter, not left to the callback, so every runner's row leaves `'Running'`.
481
+ * It is written before the callback runs, so the row reaches its final status even if the callback
482
+ * throws (the error is logged under `PromptRunUpdate` and the rollups are skipped).
483
+ *
484
+ * For prompt-based runners, like {@link CreateRunRecord}.
485
+ *
486
+ * @param success Whether the call succeeded, as the runner judges it (the chat runner also requires
487
+ * its output to pass validation).
488
+ * @param applyResultFields Sets the runner's own result columns. It can read the timing and outcome
489
+ * already set, and may refine them (for example `ErrorDetails`). **It must be synchronous**: it runs
490
+ * inside the queued save task, and anything it sets after an `await` can miss the UPDATE.
491
+ */
492
+ protected FinalizeRunRecord(promptRun: MJAIPromptRunEntityExtended, success: boolean, endTime: Date, executionTimeMS: number, applyResultFields: (promptRun: MJAIPromptRunEntityExtended) => void): Promise<void>;
493
+ /**
494
+ * Estimates the number of tokens in a rendered prompt and conversation messages.
495
+ * This is a rough estimation based on character count and typical token ratios.
496
+ *
497
+ * @param renderedPrompt - The rendered prompt text
498
+ * @param conversationMessages - Optional conversation messages
499
+ * @returns Estimated token count
500
+ */
501
+ /**
502
+ * Retrieves failover configuration from the prompt entity.
503
+ *
504
+ * @param prompt - The AI prompt entity containing failover settings
505
+ * @returns FailoverConfiguration object with strategy and settings
506
+ *
507
+ * @remarks
508
+ * This method extracts failover configuration from the prompt entity and provides
509
+ * default values when configuration is not specified. Override this method to
510
+ * implement custom failover configuration logic.
511
+ */
512
+ protected getFailoverConfiguration(prompt: MJAIPromptEntityExtended): FailoverConfiguration;
513
+ /**
514
+ * Determines whether a failover attempt should be made based on the error and configuration.
515
+ *
516
+ * @param error - The error that occurred during execution
517
+ * @param config - The failover configuration
518
+ * @param attemptNumber - The current attempt number (1-based)
519
+ * @returns True if failover should be attempted, false otherwise
520
+ *
521
+ * @remarks
522
+ * This method uses the ErrorAnalyzer to classify errors and determine if they are
523
+ * eligible for failover based on the configured error scope. Override this method
524
+ * to implement custom failover decision logic.
525
+ */
526
+ protected shouldAttemptFailover(error: Error, config: FailoverConfiguration, attemptNumber: number): boolean;
527
+ /**
528
+ * Checks if an error type matches the configured error scope
529
+ *
530
+ * @param errorType - The error type from ErrorAnalyzer
531
+ * @param scope - The configured error scope
532
+ * @returns True if the error matches the scope
533
+ */
534
+ private errorMatchesScope;
535
+ /**
536
+ * Calculates the delay before the next failover attempt.
537
+ *
538
+ * @param attemptNumber - The current attempt number (1-based)
539
+ * @param baseDelaySeconds - The base delay in seconds from configuration
540
+ * @param previousError - The error from the previous attempt
541
+ * @returns Delay in milliseconds before the next attempt
542
+ *
543
+ * @remarks
544
+ * Implements exponential backoff with jitter by default. The delay increases
545
+ * exponentially with each attempt and includes random jitter to prevent
546
+ * thundering herd problems. Override this method to implement custom delay logic.
547
+ */
548
+ protected calculateFailoverDelay(attemptNumber: number, baseDelaySeconds: number): number;
549
+ /**
550
+ * Selects candidate models for failover based on the strategy and current failure.
551
+ *
552
+ * @param currentModel - The model that just failed
553
+ * @param currentVendorId - The vendor ID that just failed
554
+ * @param strategy - The failover strategy to use
555
+ * @param modelStrategy - The model selection preference
556
+ * @param allCandidates - All available model-vendor candidates
557
+ * @param attemptHistory - History of previous failover attempts
558
+ * @returns Array of candidates sorted by priority (highest first)
559
+ *
560
+ * @remarks
561
+ * This method implements different strategies for selecting failover candidates:
562
+ * - SameModelDifferentVendor: Try the same model with different vendors
563
+ * - NextBestModel: Try different models in order of preference
564
+ * - PowerRank: Use the global power ranking of models
565
+ *
566
+ * Override this method to implement custom candidate selection logic.
567
+ */
568
+ protected selectFailoverCandidates(currentModel: MJAIModelEntityExtended, currentVendorId: string | undefined, strategy: FailoverConfiguration['strategy'], modelStrategy: FailoverConfiguration['modelStrategy'], allCandidates: ModelVendorCandidate[], attemptHistory: FailoverAttempt[]): ModelVendorCandidate[];
569
+ /**
570
+ * Logs a failover attempt for tracking and debugging.
571
+ *
572
+ * @param promptId - The ID of the prompt being executed
573
+ * @param attempt - The failover attempt details
574
+ * @param willRetry - Whether another attempt will be made
575
+ *
576
+ * @remarks
577
+ * This method logs detailed information about each failover attempt to help with
578
+ * debugging and monitoring. Override this method to implement custom logging or
579
+ * integrate with external monitoring systems.
580
+ */
581
+ protected logFailoverAttempt(promptId: string, attempt: FailoverAttempt, willRetry: boolean): void;
582
+ }
583
+ //# sourceMappingURL=BaseModelRunner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseModelRunner.d.ts","sourceRoot":"","sources":["../src/BaseModelRunner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,mBAAmB,EAKnB,QAAQ,EACR,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAEL,qBAAqB,EAGtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,2BAA2B,EAC3B,cAAc,EACd,oBAAoB,EAErB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,UAAU,EAIV,qBAAqB,EACtB,MAAM,oBAAoB,CAAC;AAK5B;;;;;;;GAOG;AACH,MAAM,WAAW,cAAc;IAC3B,kGAAkG;IAClG,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,6DAA6D;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,QAAQ,EAAE,MAAM,OAAO,CAAC;IACxB,qFAAqF;IACrF,OAAO,EAAE,MAAM,IAAI,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,uBAAuB,CAAC;IAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,wBAAwB,CAAC,EAAE,qBAAqB,GAAG,IAAI,CAAC;IACxD,iBAAiB,EAAE,OAAO,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,UAAU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