@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.
@@ -1,92 +1,108 @@
1
1
  import { ChatResult, ChatMessage, AIPromptConfiguration } from '@memberjunction/ai';
2
+ import { BaseModelRunner, type ModelVendorCandidate } from './BaseModelRunner.js';
2
3
  import { NativeToolCallingDecision } from './nativeToolCallingGate.js';
3
4
  import { AIModelRunner } from './AIModelRunner.js';
4
- import { AIPromptRunResult } from '@memberjunction/ai-core-plus';
5
- import { IMetadataProvider } from '@memberjunction/core';
5
+ import { AIPromptRunResult, AIModelSelectionInfo } from '@memberjunction/ai-core-plus';
6
+ import { UserInfo } from '@memberjunction/core';
6
7
  import { MJAIModelEntityExtended, MJAIPromptEntityExtended, MJAIPromptRunEntityExtended } from "@memberjunction/ai-core-plus";
7
8
  import { type IParallelExecutionCoordinator } from './ParallelExecution.js';
8
- import { TemplateMessageRole, AIPromptParams } from '@memberjunction/ai-core-plus';
9
+ import { TemplateMessageRole, ChildPromptParam, AIPromptParams } from '@memberjunction/ai-core-plus';
10
+ export type { ExecutionBound, FailoverConfiguration } from './BaseModelRunner.js';
9
11
  /**
10
- * The composed bound applied to a single model call: the caller's cancellation token (if any) merged
11
- * with the prompt's configured `AIPrompt.TimeoutMS` (if any).
12
+ * Advanced AI Prompt execution engine with comprehensive template support, hierarchical template composition,
13
+ * sophisticated model selection, parallelization, output validation, and execution tracking.
12
14
  *
13
- * Produced by `AIPromptRunner.createExecutionBound` and consumed by the bounded ChatCompletion race.
14
- * `Dispose()` MUST be called when the call settles so the timeout timer and abort listener are
15
- * released.
16
- */
17
- export interface ExecutionBound {
18
- /** Merged abort signal; `undefined` when there is neither a caller token nor a prompt timeout. */
19
- Signal?: AbortSignal;
20
- /** The prompt-configured timeout in ms, when one applies. */
21
- TimeoutMS?: number;
22
- /** True once the TIMEOUT (not the caller's token) fired — used to build the right error. */
23
- TimedOut: () => boolean;
24
- /** Releases the timer and the caller-token listener. Safe to call multiple times. */
25
- Dispose: () => void;
26
- }
27
- /**
28
- * Represents a model-vendor pair candidate for execution
29
- */
30
- interface ModelVendorCandidate {
31
- model: MJAIModelEntityExtended;
32
- vendorId?: string;
33
- vendorName?: string;
34
- driverClass: string;
35
- apiName?: string;
36
- supportsEffortLevel?: boolean;
37
- effortLevel?: number;
38
- /**
39
- * The `PromptConfiguration` bag of the `AIPromptModel` row this candidate came from, when it came
40
- * from one. Threaded like `effortLevel` rather than looked up later, because a candidate sourced
41
- * from power-rank or model-type has NO prompt-model row and must contribute no override.
42
- */
43
- promptModelConfiguration?: AIPromptConfiguration | null;
44
- isPreferredVendor: boolean;
45
- priority: number;
46
- source: 'explicit' | 'prompt-model' | 'model-type' | 'power-rank' | 'power-match-fallback';
47
- }
48
- /**
49
- * Configuration for failover behavior when primary model fails.
15
+ * ## Core Features
16
+ * - **Template-based prompt generation** using MJ Templates system
17
+ * - **Hierarchical template composition** with depth-first rendering and parallel template processing
18
+ * - **Advanced model selection** strategies (Default, Specific, ByPower)
19
+ * - **Parallel execution** with multiple models and execution groups
20
+ * - **Structured output validation** and type conversion with retry logic
21
+ * - **Comprehensive execution tracking** with agent run linking
22
+ * - **Configuration-driven behavior** with caching and performance optimization
23
+ * - **Real-time progress updates** and streaming response support
24
+ *
25
+ * ## Hierarchical Template Composition
26
+ * When `childPrompts` array is provided in {@link AIPromptParams}:
27
+ * 1. Renders child prompt templates in depth-first manner (children before parents)
28
+ * 2. At each level, renders sibling templates in parallel for optimal performance
29
+ * 3. Recursively handles grandchild templates (unlimited nesting depth)
30
+ * 4. Substitutes rendered child templates into corresponding placeholders in parent template
31
+ * 5. Executes the final composed prompt as a single operation
32
+ *
33
+ * This enables complex prompt composition patterns where templates can be built from reusable
34
+ * sub-templates, creating sophisticated prompts through hierarchical template inheritance.
50
35
  *
51
- * Exported because it is the return type of `AIPromptRunner.getFailoverConfiguration`, a
52
- * `protected` method documented as an override point — a subclass cannot name its own return type
53
- * otherwise, which made the documented extension point unusable from outside this package.
36
+ * ## Agent Integration
37
+ * - Supports agent decision-making workflows with structured JSON responses
38
+ * - Enables hierarchical template patterns in AI agents
39
+ *
40
+ * @example Basic Usage
41
+ * ```typescript
42
+ * const runner = new AIPromptRunner();
43
+ * const params = new AIPromptParams();
44
+ * params.prompt = aiPrompt;
45
+ * params.data = { key: 'value' };
46
+ * const result = await runner.ExecutePrompt(params);
47
+ * ```
48
+ *
49
+ * @example Hierarchical Template Composition
50
+ * ```typescript
51
+ * const params = new AIPromptParams();
52
+ * params.prompt = parentPrompt;
53
+ * params.childPrompts = [
54
+ * new ChildPromptParam(analysisPrompt, 'analysis'),
55
+ * new ChildPromptParam(summaryPrompt, 'summary'),
56
+ * new ChildPromptParam(complexChild, 'complex') // This can have its own child templates
57
+ * ];
58
+ * params.data = { userInput: 'complex data to process' };
59
+ * const result = await runner.ExecutePrompt(params);
60
+ * // Child templates render first, then parent template uses {{ analysis }}, {{ summary }}, {{ complex }}
61
+ * // Final composed prompt is executed once
62
+ * ```
54
63
  */
55
- export interface FailoverConfiguration {
56
- strategy: 'SameModelDifferentVendor' | 'NextBestModel' | 'PowerRank' | 'None';
57
- maxAttempts: number;
58
- delaySeconds: number;
59
- modelStrategy?: 'PreferSameModel' | 'PreferDifferentModel' | 'RequireSameModel';
60
- errorScope?: 'All' | 'NetworkOnly' | 'RateLimitOnly' | 'ServiceErrorOnly';
61
- }
62
64
  /**
63
- * Tracks information about a failover attempt
65
+ * Bundles the full output of selectModel so it can be threaded through
66
+ * ExecutePrompt → executeSinglePrompt / executePromptInParallel without
67
+ * discarding vendor-resolution data that would need to be re-derived.
64
68
  */
65
- interface FailoverAttempt {
66
- attemptNumber: number;
67
- modelId: string;
68
- vendorId?: string;
69
- error: Error;
70
- errorType: string;
71
- duration: number;
72
- timestamp: Date;
69
+ export interface ModelSelectionResult {
70
+ model: MJAIModelEntityExtended | null;
71
+ vendorDriverClass?: string;
72
+ vendorApiName?: string;
73
+ vendorSupportsEffortLevel?: boolean;
74
+ modelEffortLevel?: number;
75
+ /** The selected candidate's AIPromptModel `PromptConfiguration`, for the native tool-calling gate. */
76
+ promptModelConfiguration?: AIPromptConfiguration | null;
77
+ selectionInfo?: AIModelSelectionInfo;
78
+ allCandidates: ModelVendorCandidate[];
79
+ /**
80
+ * Per-candidate credential-availability already computed by
81
+ * {@link AIPromptRunner.selectModelWithAPIKeyTracked} during selection, keyed by
82
+ * `driverClass:modelID:vendorId` (the same key {@link AIPromptRunner.executeModelWithFailover}
83
+ * uses for its own cache). Lets failover REUSE selection's credential probes instead of
84
+ * recomputing `HasCredentialsAvailable` for the prefix it already walked.
85
+ *
86
+ * Because selection short-circuits once the highest-priority credentialed candidate is found
87
+ * (see the DECISION note in {@link AIPromptRunner.selectModelWithAPIKeyTracked}), this map
88
+ * only contains the candidates UP TO AND INCLUDING the selected one. The not-evaluated tail is
89
+ * intentionally absent so failover still probes it lazily — only if it ever has to walk down
90
+ * there during an actual failover.
91
+ */
92
+ credentialAvailability?: Map<string, boolean>;
73
93
  }
74
- export declare class AIPromptRunner {
75
- private _metadata;
94
+ export declare class AIPromptRunner extends BaseModelRunner {
95
+ /**
96
+ * The model type this runner requires. Returns 'LLM' for AIPromptRunner.
97
+ */
98
+ get RequiredModelType(): string;
99
+ /** Keeps this runner's uncategorized errors logged under `AIPromptRunner`, as before the base class existed. */
100
+ protected get DefaultLogCategory(): string;
76
101
  private _templateEngine;
77
102
  private _executionPlanner;
78
103
  private _parallelCoordinator?;
79
104
  private _jsonValidator;
80
105
  private _modelRunner;
81
- private _provider;
82
- /**
83
- * Fire-and-forget AIPromptRun persistence. Prompt-run logging never blocks the execution path on a
84
- * DB round-trip; the shared {@link BaseEntitySaveQueue} sequences saves for the SAME entity (the
85
- * initial 'Running' INSERT always completes before the finalize UPDATE, and the finalize mutation
86
- * runs INSIDE the post-INSERT task so a slow INSERT can never clobber the finalized row). Failures
87
- * stay in this runner's structured log stream via the queue's `onError` hook.
88
- */
89
- private _promptRunQueue;
90
106
  /**
91
107
  * Process-wide cache of parsed `OutputExample` JSON, keyed by the raw example string.
92
108
  * A prompt's OutputExample is a static string reused across every run and every validation
@@ -102,13 +118,6 @@ export declare class AIPromptRunner {
102
118
  * already been selected. See the DECISION note in {@link selectModelWithAPIKeyTracked}.
103
119
  */
104
120
  private static readonly NOT_EVALUATED_REASON;
105
- /**
106
- * Optional metadata provider override. Callers should set
107
- * `instance.Provider = providerToUse` before invoking run methods
108
- * in multi-provider contexts. Falls back to the global default provider when unset.
109
- */
110
- get Provider(): IMetadataProvider;
111
- set Provider(value: IMetadataProvider | null);
112
121
  constructor();
113
122
  /** ClassFactory key the parallel coordinator self-registers under (see {@link ParallelCoordinator}). */
114
123
  private static readonly PARALLEL_COORDINATOR_KEY;
@@ -130,100 +139,6 @@ export declare class AIPromptRunner {
130
139
  * Use this when you need tracked embedding execution with AIPromptRun record creation.
131
140
  */
132
141
  get ModelRunner(): AIModelRunner;
133
- /**
134
- * Performs robust validation of an API key
135
- * @returns true if the API key is valid (not null, undefined, or empty/whitespace)
136
- */
137
- private isValidAPIKey;
138
- /**
139
- * Internal logging helper that wraps LogStatusEx with verbose control
140
- * @param message The message to log
141
- * @param verboseOnly Whether this is a verbose-only message
142
- * @param params Optional prompt parameters for custom verbose check
143
- */
144
- protected logStatus(message: string, verboseOnly?: boolean, params?: AIPromptParams): void;
145
- /**
146
- * Helper method for enhanced error logging with metadata
147
- */
148
- protected logError(error: Error | string, options?: {
149
- category?: string;
150
- metadata?: Record<string, any>;
151
- prompt?: MJAIPromptEntityExtended;
152
- model?: MJAIModelEntityExtended;
153
- severity?: 'warning' | 'error' | 'critical';
154
- maxErrorLength?: number;
155
- }): void;
156
- /**
157
- * Checks if a model vendor is configured as an inference provider.
158
- * Delegates to the memoized {@link AIEngine.IsInferenceProvider} helper so the
159
- * "Inference Provider" vendor-type lookup happens once per engine load rather than on
160
- * every candidate in every selection pass.
161
- * @param modelVendor The model vendor to check
162
- * @returns true if the vendor is an inference provider
163
- */
164
- private isInferenceProvider;
165
- /**
166
- * Resolves credentials for AI model execution using a hierarchical resolution system.
167
- *
168
- * Resolution priority (highest to lowest):
169
- * 1. Per-request override: params.credentialId
170
- * 2. Prompt-Model specific: AIPromptModel.CredentialID
171
- * 3. Model-Vendor specific: AIModelVendor.CredentialID
172
- * 4. Vendor default: AIVendor.CredentialID
173
- * 5. Legacy: params.apiKeys[] array
174
- * 6. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
175
- *
176
- * IMPORTANT: When ANY credential ID is found (priorities 1-4), the system uses
177
- * the Credentials path and ignores legacy methods (priorities 5-6).
178
- *
179
- * @param driverClass - The driver class name (e.g., 'OpenAILLM')
180
- * @param promptId - The prompt ID for looking up AIPromptModel credentials
181
- * @param modelId - The model ID for looking up AIPromptModel and AIModelVendor credentials
182
- * @param vendorId - The vendor ID for looking up AIModelVendor and AIVendor credentials
183
- * @param params - The prompt execution parameters containing contextUser and optional credentialId
184
- * @returns The API key/configuration string to pass to the LLM constructor
185
- */
186
- private resolveCredentialForExecution;
187
- /**
188
- * Attempts to resolve credentials from bindings with priority-based failover.
189
- * Tries each binding in priority order until one succeeds.
190
- */
191
- private tryCredentialBindingsWithFailover;
192
- /**
193
- * Attempts to resolve a single credential, returning null on failure for failover support.
194
- */
195
- private tryResolveCredential;
196
- /**
197
- * Resolves a credential by its explicit ID (used for per-request override).
198
- * This does not support failover since it's an explicit choice.
199
- */
200
- private resolveCredentialById;
201
- /**
202
- * Finds a default credential matching a specific credential type.
203
- */
204
- private findDefaultCredentialByType;
205
- /**
206
- * Checks if credentials are available for a given model-vendor combination.
207
- * This is a pre-flight check used during model selection to determine which
208
- * candidates have valid authentication configured.
209
- *
210
- * Checks the credential hierarchy:
211
- * 1. Per-request override: params.credentialId
212
- * 2. PromptModel bindings: AICredentialBinding WHERE BindingType='PromptModel'
213
- * 3. ModelVendor bindings: AICredentialBinding WHERE BindingType='ModelVendor'
214
- * 4. Vendor bindings: AICredentialBinding WHERE BindingType='Vendor'
215
- * 5. Type-based default: Credential.IsDefault=1 matching AIVendor.CredentialTypeID
216
- * 6. Legacy: params.apiKeys[] array
217
- * 7. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
218
- *
219
- * @param driverClass - The driver class name (e.g., 'OpenAILLM')
220
- * @param promptId - The prompt ID for looking up AIPromptModel bindings
221
- * @param modelId - The model ID for looking up AIPromptModel and AIModelVendor bindings
222
- * @param vendorId - The vendor ID for looking up AIModelVendor and AIVendor bindings
223
- * @param params - The prompt execution parameters
224
- * @returns true if credentials are available, false otherwise
225
- */
226
- private hasCredentialsAvailable;
227
142
  /**
228
143
  * Executes an AI prompt with full support for templates, model selection, and validation.
229
144
  *
@@ -293,6 +208,24 @@ export declare class AIPromptRunner {
293
208
  * @param cancellationToken - Cancellation token for aborting rendering
294
209
  * @returns Promise with rendered templates map
295
210
  */
211
+ /**
212
+ * Render a set of child prompt templates WITHOUT executing anything, returning the rendered text
213
+ * keyed by each child's parent placeholder — exactly what the hierarchical execution path embeds
214
+ * into the parent template.
215
+ *
216
+ * Exposed for callers that need a child's rendered text before the run: the loop agent uses it to
217
+ * relocate a volatile specialization into the trailing runtime-state message (see
218
+ * `ResolveSpecializationPlacement` in `@memberjunction/ai-agents`) while the system prompt renders a
219
+ * stub in its place. Rendering is deterministic for the same inputs, so a subsequent execution of
220
+ * the same params reproduces the same text.
221
+ *
222
+ * @param childPrompts The child prompt params, as they would be passed in `AIPromptParams.childPrompts`.
223
+ * @param params The parent params (context user, data, template data) the children render against.
224
+ * @param cancellationToken Optional abort signal.
225
+ */
226
+ RenderChildPromptTemplates(childPrompts: ChildPromptParam[], params: AIPromptParams, cancellationToken?: AbortSignal): Promise<{
227
+ renderedTemplates: Record<string, string>;
228
+ }>;
296
229
  private renderChildPromptTemplates;
297
230
  /**
298
231
  * Renders a prompt template with child prompt templates merged into the data context.
@@ -305,129 +238,10 @@ export declare class AIPromptRunner {
305
238
  private renderPromptWithChildTemplates;
306
239
  /**
307
240
  * Selects the appropriate AI model based on prompt configuration and parameters.
308
- * Uses the unified buildModelVendorCandidates method to create an ordered list of candidates,
241
+ * Uses the unified BuildModelVendorCandidates method to create an ordered list of candidates,
309
242
  * then selects the first one with an available API key.
310
243
  */
311
- private selectModel;
312
- /**
313
- * Builds a unified, ordered list of model-vendor candidates based on all selection criteria.
314
- * Uses a 3-phase approach to properly handle SelectionStrategy='Specific' with AIPromptModel priorities.
315
- *
316
- * Phase 1: Handle explicit model ID (highest priority)
317
- * Phase 2: Check if SelectionStrategy='Specific' with AIPromptModel entries - use ONLY those with AIPromptModel priorities
318
- * Phase 3: Use general selection strategy (fallback) - blended priorities from legacy behavior
319
- *
320
- * @param prompt - The AI prompt with selection criteria
321
- * @param explicitModelId - Explicitly specified model ID (highest priority)
322
- * @param configurationId - Configuration ID for filtering
323
- * @param preferredVendorId - Preferred vendor ID
324
- * @returns Ordered array of model-vendor candidates (highest priority first)
325
- */
326
- private buildModelVendorCandidates;
327
- /**
328
- * PHASE 1: Build candidates for explicitly specified model ID.
329
- * Returns candidates for the single model if it's active and compatible.
330
- */
331
- private buildCandidatesForExplicitModel;
332
- /**
333
- * PHASE 2: Build candidates for 'Specific' selection strategy.
334
- * Uses AIPromptModel configuration with clean ranking:
335
- * 1. Config-matching models first (by priority DESC)
336
- * 2. Then universal (null config) models (by priority DESC)
337
- */
338
- private buildCandidatesForSpecificStrategy;
339
- /**
340
- * Appends fallback candidates from the global model pool, sorted by proximity to the
341
- * average power rank of the originally configured models. This ensures that when
342
- * specific models lack credentials, the fallback uses models of similar capability
343
- * rather than defaulting to the most or least powerful available model.
344
- *
345
- * Fallback candidates are given lower priority than any specific candidate so
346
- * configured models are always preferred when their credentials are available.
347
- */
348
- private appendPowerMatchedFallbackCandidates;
349
- /**
350
- * Computes the target power rank from configured AIPromptModel records.
351
- * Uses the weighted average (by priority) of the configured models' power ranks,
352
- * so higher-priority models have more influence on the target.
353
- * Falls back to simple average if priorities are all zero.
354
- */
355
- private computeTargetPowerRank;
356
- /**
357
- * Sorts models by proximity to a target power rank (closest first).
358
- * When two models are equidistant, the higher-powered one is preferred.
359
- */
360
- private sortByPowerProximity;
361
- /**
362
- * PHASE 3: Build candidates for general selection strategies ('Default' or 'ByPower').
363
- * Uses configuration-aware fallback hierarchy with legacy blended priority calculation.
364
- */
365
- private buildCandidatesForGeneralSelection;
366
- /**
367
- * Helper: Filter prompt models by configuration matching rules.
368
- * Supports configuration inheritance - includes models from the entire inheritance chain.
369
- */
370
- private filterPromptModelsByConfiguration;
371
- /**
372
- * Helper: Sort prompt models for 'Specific' strategy.
373
- * Respects configuration inheritance chain - child configs first, then parents, then null-config.
374
- * Within each config level, sorts by priority DESC.
375
- */
376
- private sortPromptModelsForSpecificStrategy;
377
- /**
378
- * Helper: Build candidates from sorted AIPromptModel records.
379
- * Expands VendorID=null to all vendors for that model.
380
- */
381
- private buildCandidatesFromPromptModels;
382
- /**
383
- * Helper: Create candidate for specific vendor from AIPromptModel.
384
- */
385
- private createCandidateForSpecificVendor;
386
- /**
387
- * Helper: Create candidates for all vendors of a model, sorted by vendor priority.
388
- */
389
- private createCandidatesForAllVendors;
390
- /**
391
- * Helper: true if this prompt has any AIPromptModel bindings at all, regardless of Status or
392
- * ConfigurationID. Distinguishes "no bindings were ever configured" (general selection strategy
393
- * should apply) from "bindings exist but are all Inactive" (no model should be selected).
394
- */
395
- private hasAnyPromptModelBindings;
396
- /**
397
- * Helper: Get prompt models for configuration with inheritance chain fallback.
398
- * Walks the configuration inheritance chain looking for prompt models.
399
- * Returns models from the first config in the chain that has any, or falls back to null-config.
400
- */
401
- private getPromptModelsForConfiguration;
402
- /**
403
- * Helper: Add prompt-specific candidates with blended priorities (legacy behavior).
404
- */
405
- private addPromptSpecificCandidates;
406
- /**
407
- * Helper: Add configuration fallback candidates from the inheritance chain.
408
- * Adds models from parent configs (with decreasing priority) and null-config models as final fallback.
409
- */
410
- private addConfigurationFallbackCandidates;
411
- /**
412
- * Helper: Add strategy-based candidates when no prompt models exist.
413
- */
414
- private addStrategyBasedCandidates;
415
- /**
416
- * Helper: Get model pool filtered for strategy.
417
- */
418
- private getModelPoolForStrategy;
419
- /**
420
- * Helper: Sort model pool by selection strategy.
421
- */
422
- private sortModelPoolByStrategy;
423
- /**
424
- * Helper: Sort models by power preference.
425
- */
426
- private sortByPowerPreference;
427
- /**
428
- * Helper: Create candidates for a model with AIModelVendor priorities (legacy behavior).
429
- */
430
- private createCandidatesForModel;
244
+ protected selectModel(prompt: MJAIPromptEntityExtended, explicitModelId?: string, contextUser?: UserInfo, configurationId?: string, vendorId?: string, params?: AIPromptParams): Promise<ModelSelectionResult>;
431
245
  /**
432
246
  * Creates a properly typed AIModelSelectionInfo instance.
433
247
  * TypeScript requires instantiating the class to get the getValidCandidates() method.
@@ -450,24 +264,6 @@ export declare class AIPromptRunner {
450
264
  * so the error message is actionable for end users (e.g., missing API credentials).
451
265
  */
452
266
  private buildNoModelFoundMessage;
453
- /**
454
- * Creates an AIPromptRun entity for execution tracking
455
- */
456
- /**
457
- * Resolves the scalar inference parameters for a run: each value is the per-request override
458
- * from `additionalParameters` when supplied, otherwise the prompt's configured default. This
459
- * is the single source of truth for parameter precedence so {@link executeModel} (ChatParams)
460
- * and {@link createPromptRun} (the persisted record) stay in lockstep. Stop sequences and
461
- * assistant prefill are intentionally excluded — their representations differ per target.
462
- */
463
- private resolveScalarInferenceParams;
464
- /**
465
- * Awaits all in-flight prompt-run saves queued by this runner instance. The normal execution path
466
- * does NOT call this — prompt-run persistence is intentionally fire-and-forget. Exposed for tests
467
- * and for callers that need the AIPromptRun rows durably written before proceeding.
468
- */
469
- WaitForPendingPromptRunSaves(): Promise<void>;
470
- private createPromptRun;
471
267
  /**
472
268
  * Renders the prompt template with provided data
473
269
  */
@@ -480,30 +276,14 @@ export declare class AIPromptRunner {
480
276
  * capabilities. It will attempt to execute with different models/vendors according
481
277
  * to the configured failover strategy when errors occur.
482
278
  *
483
- * The method calls several smaller, focused helper methods:
484
- * - buildFailoverCandidates: Creates candidate models based on type restrictions
485
- * - createCandidatesFromModels: Converts models to vendor-specific candidates
486
- * - updatePromptRunWithFailoverSuccess: Records successful failover metadata
487
- * - updatePromptRunWithFailoverFailure: Records failed failover metadata
488
- * - createFailoverErrorResult: Creates standardized error response
279
+ * Candidates come from model selection (`allCandidates`), already filtered to the prompt's
280
+ * model type by ID. When failover applies, the loop itself is
281
+ * {@link BaseModelRunner.ExecuteWithFailover}: this method supplies the chat call on each candidate
282
+ * (`executeModel` with that candidate's model, vendor, driver, effort level and prompt-model
283
+ * configuration) and the final error result (`createFailoverErrorResult`). The base records
284
+ * failover success or failure on the prompt run.
489
285
  */
490
286
  protected executeModelWithFailover(model: MJAIModelEntityExtended, renderedPrompt: string, prompt: MJAIPromptEntityExtended, params: AIPromptParams, vendorId: string | null, conversationMessages?: ChatMessage[], templateMessageRole?: TemplateMessageRole, cancellationToken?: AbortSignal, allCandidates?: ModelVendorCandidate[], promptRun?: MJAIPromptRunEntityExtended, vendorDriverClass?: string, vendorApiName?: string, vendorSupportsEffortLevel?: boolean, modelEffortLevel?: number, credentialAvailability?: Map<string, boolean>, promptModelConfiguration?: AIPromptConfiguration | null): Promise<ChatResult>;
491
- /**
492
- * Builds failover candidates for a prompt based on available models and type restrictions
493
- */
494
- protected buildFailoverCandidates(prompt: MJAIPromptEntityExtended): Promise<ModelVendorCandidate[]>;
495
- /**
496
- * Creates model-vendor candidates from a list of models
497
- */
498
- protected createCandidatesFromModels(models: MJAIModelEntityExtended[]): ModelVendorCandidate[];
499
- /**
500
- * Updates prompt run with successful failover tracking data
501
- */
502
- protected updatePromptRunWithFailoverSuccess(promptRun: MJAIPromptRunEntityExtended, failoverAttempts: FailoverAttempt[], currentModel: MJAIModelEntityExtended, currentVendorId: string | null): void;
503
- /**
504
- * Updates prompt run with failover failure tracking data
505
- */
506
- private updatePromptRunWithFailoverFailure;
507
287
  /**
508
288
  * Creates an error result for failed failover attempts
509
289
  */
@@ -540,6 +320,8 @@ export declare class AIPromptRunner {
540
320
  * Never throws: the gate is an opt-in enhancement and must not be able to fail a run that would
541
321
  * otherwise succeed, so any configuration problem resolves to the path that has always worked.
542
322
  */
323
+ ResolveNativeToolCallingDecision(prompt: MJAIPromptEntityExtended, params: AIPromptParams, model: MJAIModelEntityExtended, vendorId: string | null, promptModelConfiguration?: AIPromptConfiguration | null): NativeToolCallingDecision;
324
+ /** @deprecated Use {@link ResolveNativeToolCallingDecision}. */
543
325
  resolveNativeToolCallingDecision(prompt: MJAIPromptEntityExtended, params: AIPromptParams, model: MJAIModelEntityExtended, vendorId: string | null, promptModelConfiguration?: AIPromptConfiguration | null): NativeToolCallingDecision;
544
326
  private applyNativeToolCalling;
545
327
  /**
@@ -569,44 +351,6 @@ export declare class AIPromptRunner {
569
351
  /** Scans provider prose for a tools marker. Shared by the thrown-error and failed-result paths. */
570
352
  private isToolSpecificFailureText;
571
353
  protected executeModel(model: MJAIModelEntityExtended, renderedPrompt: string, prompt: MJAIPromptEntityExtended, params: AIPromptParams, vendorId: string | null, conversationMessages?: ChatMessage[], templateMessageRole?: TemplateMessageRole, cancellationToken?: AbortSignal, vendorDriverClass?: string, vendorApiName?: string, vendorSupportsEffortLevel?: boolean, modelEffortLevel?: number, promptModelConfiguration?: AIPromptConfiguration | null): Promise<ChatResult>;
572
- /**
573
- * Engine-level default model-call timeout, in milliseconds, applied when the caller supplies no
574
- * `AIPromptParams.timeoutMS`. `undefined` (the default) means NO implicit bound — a prompt run
575
- * with neither a timeout nor a cancellation token stays unbounded, exactly as before, so this
576
- * change is behavior-preserving for existing callers.
577
- *
578
- * Subclasses (or a host application's runner subclass) can override this to impose a global
579
- * safety ceiling on every prompt call.
580
- */
581
- protected get DefaultPromptTimeoutMS(): number | undefined;
582
- /**
583
- * Resolves the per-model-call timeout: the caller's `AIPromptParams.timeoutMS`, else the runner's
584
- * {@link DefaultPromptTimeoutMS}. Non-positive / non-numeric values mean "no timeout".
585
- *
586
- * The bound is applied PER MODEL CALL (not per prompt execution), which mirrors the parallel
587
- * path's existing `taskTimeoutMS` semantics: each failover candidate / validation retry gets a
588
- * fresh budget rather than sharing one wall-clock window.
589
- *
590
- * NOTE (issue #3064): there is deliberately NO prompt-entity source here yet — the `AIPrompt`
591
- * table has no `TimeoutMS` column today. Once a migration adds one and CodeGen regenerates the
592
- * entity, this becomes `prompt.TimeoutMS ?? params.timeoutMS ?? this.DefaultPromptTimeoutMS`
593
- * and every bound below starts honoring the per-prompt configuration with no other change.
594
- */
595
- protected getEffectiveTimeoutMS(params: AIPromptParams): number | undefined;
596
- /**
597
- * Composes the caller-supplied cancellation token with the resolved model-call timeout into a
598
- * single {@link AbortSignal} that bounds one model call. NEITHER bound is discarded:
599
- *
600
- * - caller token only → the caller's signal is used directly (behavior unchanged)
601
- * - timeout only → an internal controller aborts after the timeout elapses
602
- * - both → an internal controller relays the caller's abort AND fires on timeout;
603
- * whichever happens first wins
604
- * - neither → `Signal` is undefined and the call runs unbounded (legacy behavior)
605
- *
606
- * Implemented with an AbortController + relay listener rather than `AbortSignal.any()` so it works
607
- * on Node 18 (where `AbortSignal.any` does not exist — it landed in Node 20.3).
608
- */
609
- protected createExecutionBound(prompt: MJAIPromptEntityExtended, params: AIPromptParams, cancellationToken?: AbortSignal): ExecutionBound;
610
354
  /**
611
355
  * Runs the model call, racing it against the composed execution bound so a hung provider surfaces
612
356
  * as a rejected promise the caller's failover/retry logic can act on.
@@ -664,23 +408,6 @@ export declare class AIPromptRunner {
664
408
  */
665
409
  private injectNativeFileInputs;
666
410
  private buildMessageArray;
667
- /**
668
- * Default fallback instruction text used when no PrefillFallbackText is configured
669
- * at any level of the AIModelType → AIModel → AIModelVendor cascade.
670
- */
671
- private static readonly DEFAULT_PREFILL_FALLBACK;
672
- /**
673
- * Regex used to trim only horizontal whitespace (spaces and tabs) from the start and end
674
- * of each stop sequence token after comma-splitting.
675
- *
676
- * We intentionally do NOT use String.trim() here because stop sequences can legitimately
677
- * begin or end with newline characters. For example, the sequence "\n```" is designed to
678
- * match only a closing code fence (preceded by a newline), distinguishing it from an
679
- * opening "```json" fence that does not start with a newline. Using trim() would strip
680
- * that leading "\n", turning "\n```" into "```" and causing the stop to fire on the
681
- * opening fence instead — producing an empty response for non-native prefill providers.
682
- */
683
- private static readonly STOP_SEQUENCE_TRIM_REGEX;
684
411
  /**
685
412
  * Substrings that mark a provider failure as TOOLS-specific, so the native call is worth one
686
413
  * envelope retry (see {@link AIPromptRunner.isToolSpecificFailure}). Drawn from how the
@@ -737,58 +464,31 @@ export declare class AIPromptRunner {
737
464
  */
738
465
  private shouldApplyStopSequences;
739
466
  private resolveSupportsPrefill;
740
- /**
741
- * Resolves the prefill fallback instruction text using the cascade:
742
- * AIModelType → AIModel → AIModelVendor (most specific non-null wins).
743
- * Falls back to DEFAULT_PREFILL_FALLBACK if none are configured.
744
- */
745
- private resolvePrefillFallbackText;
746
467
  /**
747
468
  * Applies assistant prefill to ChatParams based on prompt configuration and provider support.
748
469
  * Handles the full prefill resolution logic including fallback to system instructions.
749
470
  */
750
471
  private applyAssistantPrefill;
751
472
  /**
752
- * Executes the model with retry logic for validation failures
753
- */
754
- private executeWithValidationRetries;
755
- /**
756
- * Applies retry delay based on the prompt's retry strategy
757
- */
758
- /**
759
- * Calculates retry delay for rate limit and other retriable errors.
760
- * Uses the prompt's RetryStrategy and can respect suggested delays from provider.
761
- */
762
- private calculateRetryDelay;
763
- private applyRetryDelay;
764
- /**
765
- * Filters out all candidates from a vendor when a vendor-level error occurs.
766
- * Vendor-level errors affect all models from that vendor:
767
- * - Authentication: Invalid API key
768
- * - VendorValidationError: API schema/validation requirements
473
+ * Default fallback instruction text used when no PrefillFallbackText is configured
474
+ * at any level of the AIModelType → AIModel → AIModelVendor cascade.
769
475
  */
770
- private filterVendorCandidates;
476
+ private static readonly DEFAULT_PREFILL_FALLBACK;
771
477
  /**
772
- * Handles rate limit errors by retrying the same model/vendor with backoff.
773
- * Returns true if the caller should continue (retry), false if should proceed to failover.
478
+ * Resolves the prefill fallback instruction text using the cascade:
479
+ * AIModelType → AIModel → AIModelVendor (most specific non-null wins).
480
+ * Falls back to DEFAULT_PREFILL_FALLBACK if none are configured.
774
481
  */
775
- private handleRateLimitRetry;
482
+ private resolvePrefillFallbackText;
776
483
  /**
777
- * Processes a failover error (either from catch block or from failed ChatResult).
778
- * Handles vendor filtering, rate limit retries, fatal error detection, and failover logic.
779
- *
780
- * @returns Decision object indicating whether to retry same model, continue to next candidate, or stop
484
+ * Executes the model with retry logic for validation failures
781
485
  */
782
- private processFailoverError;
486
+ private executeWithValidationRetries;
783
487
  /**
784
488
  * Transitions to the next failover candidate.
785
489
  * Returns the next candidate info or null if no candidates are available.
786
490
  */
787
491
  private transitionToNextCandidate;
788
- /**
789
- * Provides a human-readable description of the validation decision
790
- */
791
- private getValidationDecisionDescription;
792
492
  /**
793
493
  * Generates a JSON schema from an example object for validation
794
494
  */
@@ -911,104 +611,38 @@ export declare class AIPromptRunner {
911
611
  */
912
612
  private validateAgainstSchema;
913
613
  /**
914
- * Updates the AIPromptRun entity with execution results
915
- */
916
- private updatePromptRun;
917
- /**
918
- * Populates a prompt-run's finalized fields (result, tokens, cost, timing, rollups) from the model
919
- * result. Runs INSIDE the post-INSERT save task — see {@link updatePromptRun}. Errors here are
920
- * logged (non-fatal): the AIPromptRun is observability, not part of the prompt's success contract.
921
- */
922
- private applyFinalizedPromptRunFields;
923
- /**
924
- * Estimates the number of tokens in a rendered prompt and conversation messages.
925
- * This is a rough estimation based on character count and typical token ratios.
926
- *
927
- * @param renderedPrompt - The rendered prompt text
928
- * @param conversationMessages - Optional conversation messages
929
- * @returns Estimated token count
930
- */
931
- /**
932
- * Retrieves failover configuration from the prompt entity.
933
- *
934
- * @param prompt - The AI prompt entity containing failover settings
935
- * @returns FailoverConfiguration object with strategy and settings
936
- *
937
- * @remarks
938
- * This method extracts failover configuration from the prompt entity and provides
939
- * default values when configuration is not specified. Override this method to
940
- * implement custom failover configuration logic.
614
+ * Creates an AIPromptRun entity for execution tracking
941
615
  */
942
- protected getFailoverConfiguration(prompt: MJAIPromptEntityExtended): FailoverConfiguration;
616
+ private createPromptRun;
943
617
  /**
944
- * Determines whether a failover attempt should be made based on the error and configuration.
945
- *
946
- * @param error - The error that occurred during execution
947
- * @param config - The failover configuration
948
- * @param attemptNumber - The current attempt number (1-based)
949
- * @returns True if failover should be attempted, false otherwise
950
- *
951
- * @remarks
952
- * This method uses the ErrorAnalyzer to classify errors and determine if they are
953
- * eligible for failover based on the configured error scope. Override this method
954
- * to implement custom failover decision logic.
618
+ * Sets a prompt-run's chat-specific request fields: messages, prefill, sampling parameters,
619
+ * response format, streaming, effort level, child prompt and the validation/retry columns. Called by
620
+ * {@link BaseModelRunner.CreateRunRecord} just before the INSERT is queued.
955
621
  */
956
- protected shouldAttemptFailover(error: Error, config: FailoverConfiguration, attemptNumber: number): boolean;
622
+ private applyChatRequestFields;
957
623
  /**
958
- * Checks if an error type matches the configured error scope
959
- *
960
- * @param errorType - The error type from ErrorAnalyzer
961
- * @param scope - The configured error scope
962
- * @returns True if the error matches the scope
624
+ * Updates the AIPromptRun entity with execution results
963
625
  */
964
- private errorMatchesScope;
626
+ private updatePromptRun;
965
627
  /**
966
- * Calculates the delay before the next failover attempt.
967
- *
968
- * @param attemptNumber - The current attempt number (1-based)
969
- * @param baseDelaySeconds - The base delay in seconds from configuration
970
- * @param previousError - The error from the previous attempt
971
- * @returns Delay in milliseconds before the next attempt
972
- *
973
- * @remarks
974
- * Implements exponential backoff with jitter by default. The delay increases
975
- * exponentially with each attempt and includes random jitter to prevent
976
- * thundering herd problems. Override this method to implement custom delay logic.
628
+ * Populates a prompt-run's chat-specific finalized fields (result, tokens, cost, timing, validation)
629
+ * from the model result. Runs INSIDE the post-INSERT save task — see {@link BaseModelRunner.FinalizeRunRecord},
630
+ * which sets the completion timing, `Success` and `Status` before this runs and the rollups after it,
631
+ * and logs (non-fatal) any error thrown here: the AIPromptRun is observability, not part of the
632
+ * prompt's success contract.
977
633
  */
978
- protected calculateFailoverDelay(attemptNumber: number, baseDelaySeconds: number): number;
634
+ private applyChatResultFields;
979
635
  /**
980
- * Selects candidate models for failover based on the strategy and current failure.
981
- *
982
- * @param currentModel - The model that just failed
983
- * @param currentVendorId - The vendor ID that just failed
984
- * @param strategy - The failover strategy to use
985
- * @param modelStrategy - The model selection preference
986
- * @param allCandidates - All available model-vendor candidates
987
- * @param attemptHistory - History of previous failover attempts
988
- * @returns Array of candidates sorted by priority (highest first)
989
- *
990
- * @remarks
991
- * This method implements different strategies for selecting failover candidates:
992
- * - SameModelDifferentVendor: Try the same model with different vendors
993
- * - NextBestModel: Try different models in order of preference
994
- * - PowerRank: Use the global power ranking of models
995
- *
996
- * Override this method to implement custom candidate selection logic.
636
+ * Provides a human-readable description of the validation decision
997
637
  */
998
- protected selectFailoverCandidates(currentModel: MJAIModelEntityExtended, currentVendorId: string | undefined, strategy: FailoverConfiguration['strategy'], modelStrategy: FailoverConfiguration['modelStrategy'], allCandidates: ModelVendorCandidate[], attemptHistory: FailoverAttempt[]): ModelVendorCandidate[];
638
+ private getValidationDecisionDescription;
999
639
  /**
1000
- * Logs a failover attempt for tracking and debugging.
1001
- *
1002
- * @param promptId - The ID of the prompt being executed
1003
- * @param attempt - The failover attempt details
1004
- * @param willRetry - Whether another attempt will be made
1005
- *
1006
- * @remarks
1007
- * This method logs detailed information about each failover attempt to help with
1008
- * debugging and monitoring. Override this method to implement custom logging or
1009
- * integrate with external monitoring systems.
640
+ * Resolves the scalar inference parameters for a run: each value is the per-request override
641
+ * from `additionalParameters` when supplied, otherwise the prompt's configured default. This
642
+ * is the single source of truth for parameter precedence so {@link executeModel} (ChatParams)
643
+ * and {@link createPromptRun} (the persisted record) stay in lockstep. Stop sequences and
644
+ * assistant prefill are intentionally excluded — their representations differ per target.
1010
645
  */
1011
- protected logFailoverAttempt(promptId: string, attempt: FailoverAttempt, willRetry: boolean): void;
646
+ private resolveScalarInferenceParams;
1012
647
  }
1013
- export {};
1014
648
  //# sourceMappingURL=AIPromptRunner.d.ts.map