@memberjunction/ai-prompts 6.1.4 → 6.1.6

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,13 +1,16 @@
1
- import { BaseLLM, ChatParams, ChatMessageRole, GetAIAPIKey, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText } from '@memberjunction/ai';
2
- import { GetToolCallingDecision, GetToolCallingMode, RecordToolCallingDecision, RecordToolCallingMode, ResolveNativeToolCalling } from './nativeToolCallingGate.js';
1
+ import { BaseLLM, ChatParams, ChatMessageRole, GetAIAPIKey, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText, CredentialScopeAllows } from '@memberjunction/ai';
2
+ import { GetToolCallingDecision, GetToolCallingMode, RecordToolCallingDecision, RecordToolCallingMode, ResolveNativeToolCalling, ResolveToolChoiceForRequest } from './nativeToolCallingGate.js';
3
3
  import { AIModelRunner } from './AIModelRunner.js';
4
- import { AIModelSelectionInfo } from '@memberjunction/ai-core-plus';
4
+ import { AIModelSelectionInfo, PickPromptExecutionScope } from '@memberjunction/ai-core-plus';
5
5
  import { BaseEntitySaveQueue, LogErrorEx, LogStatus, LogStatusEx, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
6
6
  import { CleanJSON, RepairJSONEscaping, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
7
7
  import { CredentialEngine } from '@memberjunction/credentials';
8
8
  import { TemplateEngineServer } from '@memberjunction/templates';
9
9
  import { ExecutionPlanner } from './ExecutionPlanner.js';
10
10
  import { AIPromptTimeoutError } from './AIPromptTimeoutError.js';
11
+ import { ParseManifestEntryMime, TrimSpacesAndTabs } from './linearTextScan.js';
12
+ /** The `providerErrorCode` that marks a request the caller cancelled — the code the drivers use. */
13
+ const CALLER_CANCELLATION_CODE = 'request_cancelled';
11
14
  import { AIEngine } from '@memberjunction/aiengine';
12
15
  import { AIEngineBase } from '@memberjunction/ai-engine-base';
13
16
  import { SystemPlaceholderManager } from '@memberjunction/ai-core-plus';
@@ -66,6 +69,8 @@ export class AIPromptRunner {
66
69
  * runs INSIDE the post-INSERT task so a slow INSERT can never clobber the finalized row). Failures
67
70
  * stay in this runner's structured log stream via the queue's `onError` hook.
68
71
  */
72
+ /** Failover fields waiting to be re-applied after a prompt run's INSERT lands; see {@link recordFailoverFields}. */
73
+ this._pendingFailoverFields = new WeakMap();
69
74
  this._promptRunQueue = new BaseEntitySaveQueue({
70
75
  onError: (message) => this.logError(message, { category: 'PromptRunSave' }),
71
76
  });
@@ -196,6 +201,11 @@ export class AIPromptRunner {
196
201
  * IMPORTANT: When ANY credential ID is found (priorities 1-4), the system uses
197
202
  * the Credentials path and ignores legacy methods (priorities 5-6).
198
203
  *
204
+ * Each tier is consulted only if {@link CredentialScopeAllows} the run's
205
+ * {@link AIPromptParams.CredentialScope} to use its source. Under `'RuntimeOnly'` that leaves
206
+ * priority 1 and the `apiKeys` entry for this driver class; bindings, the vendor default and the
207
+ * environment are skipped.
208
+ *
199
209
  * @param driverClass - The driver class name (e.g., 'OpenAILLM')
200
210
  * @param promptId - The prompt ID for looking up AIPromptModel credentials
201
211
  * @param modelId - The model ID for looking up AIPromptModel and AIModelVendor credentials
@@ -209,6 +219,26 @@ export class AIPromptRunner {
209
219
  if (params.credentialId) {
210
220
  return await this.resolveCredentialById(params.credentialId, 'per-request override', params, verbose);
211
221
  }
222
+ // Priorities 2-5 are the platform's MJ Credentials; a scope that rules them out skips straight
223
+ // to the caller's keys (and, if the scope allows it, the environment).
224
+ if (CredentialScopeAllows(params.CredentialScope, 'PlatformCredential')) {
225
+ const platformCredential = await this.resolvePlatformCredential(promptId, modelId, vendorId, params, verbose);
226
+ if (platformCredential)
227
+ return platformCredential;
228
+ }
229
+ // No credential bindings found - fall back to legacy methods
230
+ if (verbose) {
231
+ this.logStatus(` Using legacy API key resolution for driver ${driverClass}`, true, params);
232
+ }
233
+ // Priority 6 & 7: Legacy apiKeys array and environment variables (the latter only if the scope allows)
234
+ return GetAIAPIKey(driverClass, params.apiKeys, verbose, params.CredentialScope);
235
+ }
236
+ /**
237
+ * Priorities 2-5 of {@link resolveCredentialForExecution}: the platform's MJ Credentials —
238
+ * `AICredentialBinding`s on the prompt-model, the model-vendor and the vendor, then the vendor's
239
+ * default credential. `undefined` when none resolves.
240
+ */
241
+ async resolvePlatformCredential(promptId, modelId, vendorId, params, verbose) {
212
242
  // Ensure CredentialEngine is configured for binding lookups
213
243
  await CredentialEngine.Instance.Config(false, params.contextUser);
214
244
  // Priority 2: PromptModel bindings (most specific) - with failover
@@ -252,12 +282,7 @@ export class AIPromptRunner {
252
282
  }
253
283
  }
254
284
  }
255
- // No credential bindings found - fall back to legacy methods
256
- if (verbose) {
257
- this.logStatus(` Using legacy API key resolution for driver ${driverClass}`, true, params);
258
- }
259
- // Priority 6 & 7: Legacy apiKeys array and environment variables
260
- return GetAIAPIKey(driverClass, params.apiKeys, verbose);
285
+ return undefined;
261
286
  }
262
287
  /**
263
288
  * Attempts to resolve credentials from bindings with priority-based failover.
@@ -379,6 +404,10 @@ export class AIPromptRunner {
379
404
  * 6. Legacy: params.apiKeys[] array
380
405
  * 7. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
381
406
  *
407
+ * Each tier counts only if {@link CredentialScopeAllows} the run's scope to use its source: under
408
+ * `'RuntimeOnly'` only 1 and 6 count, so a candidate the caller has no key for is unavailable —
409
+ * which is what keeps failover on the caller's keys.
410
+ *
382
411
  * @param driverClass - The driver class name (e.g., 'OpenAILLM')
383
412
  * @param promptId - The prompt ID for looking up AIPromptModel bindings
384
413
  * @param modelId - The model ID for looking up AIPromptModel and AIModelVendor bindings
@@ -392,6 +421,16 @@ export class AIPromptRunner {
392
421
  // Assume valid if credential ID is provided - will be validated at execution time
393
422
  return true;
394
423
  }
424
+ // Priorities 2-5: the platform's MJ Credentials, when the scope allows them
425
+ if (CredentialScopeAllows(params?.CredentialScope, 'PlatformCredential') && this.hasPlatformCredential(promptId, modelId, vendorId)) {
426
+ return true;
427
+ }
428
+ // Priority 6 & 7: Legacy methods - check if API key is available (the environment only if the scope allows)
429
+ const apiKey = GetAIAPIKey(driverClass, params?.apiKeys, params?.verbose, params?.CredentialScope);
430
+ return this.isValidAPIKey(apiKey);
431
+ }
432
+ /** Priorities 2-5 of {@link hasCredentialsAvailable}: whether a platform MJ Credential applies. */
433
+ hasPlatformCredential(promptId, modelId, vendorId) {
395
434
  // Priority 2: PromptModel bindings
396
435
  if (promptId && modelId) {
397
436
  const promptModel = AIEngine.Instance.PromptModels.find(pm => UUIDsEqual(pm.PromptID, promptId) && UUIDsEqual(pm.ModelID, modelId));
@@ -423,9 +462,7 @@ export class AIPromptRunner {
423
462
  }
424
463
  }
425
464
  }
426
- // Priority 6 & 7: Legacy methods - check if API key is available
427
- const apiKey = GetAIAPIKey(driverClass, params?.apiKeys, params?.verbose);
428
- return this.isValidAPIKey(apiKey);
465
+ return false;
429
466
  }
430
467
  /**
431
468
  * Executes an AI prompt with full support for templates, model selection, and validation.
@@ -501,7 +538,7 @@ export class AIPromptRunner {
501
538
  // Select model using the appropriate prompt — capture the FULL result
502
539
  selection = await this.selectModel(modelSelectionPrompt, params.override?.modelId, params.contextUser, params.configurationId, params.override?.vendorId, params);
503
540
  if (!selection.model) {
504
- throw new Error(this.buildNoModelFoundMessage(modelSelectionPrompt.Name, selection.selectionInfo));
541
+ throw new Error(this.buildNoModelFoundMessage(modelSelectionPrompt.Name, selection.selectionInfo, params.CredentialScope));
505
542
  }
506
543
  // Tell the template which path this run is actually taking, BEFORE it renders. The loop
507
544
  // template drops its action catalog and the `'Actions'` step type under native mode
@@ -578,7 +615,7 @@ export class AIPromptRunner {
578
615
  }
579
616
  selection = await this.selectModel(modelSelectionPrompt, params.override?.modelId, params.contextUser, params.configurationId, params.override?.vendorId, params);
580
617
  if (!selection.model) {
581
- throw new Error(this.buildNoModelFoundMessage(modelSelectionPrompt.Name, selection.selectionInfo));
618
+ throw new Error(this.buildNoModelFoundMessage(modelSelectionPrompt.Name, selection.selectionInfo, params.CredentialScope));
582
619
  }
583
620
  }
584
621
  // Check if we need parallel execution based on ParallelizationMode
@@ -598,14 +635,19 @@ export class AIPromptRunner {
598
635
  return result;
599
636
  }
600
637
  catch (error) {
601
- this.logError(error, {
602
- prompt: params.prompt,
603
- metadata: {
604
- executionPhase: 'main-execution',
605
- hasChildPrompts: !!params.childPrompts?.length
606
- },
607
- maxErrorLength: params.maxErrorLength
608
- });
638
+ if (this.isCancellation(error, params)) {
639
+ this.logStatus(`⏹️ Prompt "${params.prompt?.Name}" was cancelled: ${error.message}`, false, params);
640
+ }
641
+ else {
642
+ this.logError(error, {
643
+ prompt: params.prompt,
644
+ metadata: {
645
+ executionPhase: 'main-execution',
646
+ hasChildPrompts: !!params.childPrompts?.length
647
+ },
648
+ maxErrorLength: params.maxErrorLength
649
+ });
650
+ }
609
651
  const endTime = new Date();
610
652
  const executionTimeMS = endTime.getTime() - startTime.getTime();
611
653
  // Update prompt run with error if it was created
@@ -698,7 +740,7 @@ export class AIPromptRunner {
698
740
  allCandidates = modelResult.allCandidates || [];
699
741
  credentialAvailability = modelResult.credentialAvailability;
700
742
  if (!selectedModel) {
701
- throw new Error(this.buildNoModelFoundMessage(modelSelectionPrompt.Name, modelSelectionInfo));
743
+ throw new Error(this.buildNoModelFoundMessage(modelSelectionPrompt.Name, modelSelectionInfo, params.CredentialScope));
702
744
  }
703
745
  }
704
746
  // Check for cancellation after model selection
@@ -736,8 +778,10 @@ export class AIPromptRunner {
736
778
  // Validation failed (Warn or Strict mode)
737
779
  errorMessage = `Validation failed: ${parsedResult.validationResult.Errors?.map(e => e.Message).join('; ')}`;
738
780
  }
781
+ const cancelled = !chatResult.success && this.isCallerCancellation(chatResult.errorInfo);
739
782
  return {
740
783
  success: chatResult.success,
784
+ ...(cancelled ? { status: 'Cancelled', cancelled: true, cancellationReason: 'user_requested' } : {}),
741
785
  rawResult: chatResult.data?.choices?.[0]?.message?.content,
742
786
  result: parsedResult?.result ? parsedResult.result : parsedResult,
743
787
  errorMessage, // Include error message for proper error propagation
@@ -839,7 +883,7 @@ export class AIPromptRunner {
839
883
  method: 'PromptSelector',
840
884
  selectorPromptId: prompt.ResultSelectorPromptID,
841
885
  };
842
- const aiSelectedResult = await this.ParallelCoordinator.selectBestResult(successfulResults, selectionConfig, undefined, params.cancellationToken);
886
+ const aiSelectedResult = await this.ParallelCoordinator.selectBestResult(successfulResults, selectionConfig, undefined, params.cancellationToken, PickPromptExecutionScope(params));
843
887
  if (aiSelectedResult) {
844
888
  selectedResult = aiSelectedResult;
845
889
  }
@@ -2048,7 +2092,7 @@ export class AIPromptRunner {
2048
2092
  * Includes details about which models were considered and why they were unavailable
2049
2093
  * so the error message is actionable for end users (e.g., missing API credentials).
2050
2094
  */
2051
- buildNoModelFoundMessage(promptName, selectionInfo) {
2095
+ buildNoModelFoundMessage(promptName, selectionInfo, credentialScope) {
2052
2096
  const base = `No suitable model found for prompt ${promptName}`;
2053
2097
  if (!selectionInfo?.modelsConsidered || selectionInfo.modelsConsidered.length === 0) {
2054
2098
  return `${base}. No model-vendor candidates were available. Please ensure AI models are configured for this prompt.`;
@@ -2061,9 +2105,14 @@ export class AIPromptRunner {
2061
2105
  return `${m.model.Name}/${vendorName}`;
2062
2106
  }).join(', ');
2063
2107
  const suffix = unavailableModels.length > 5 ? ` (${unavailableModels.length} total)` : '';
2108
+ // When the scope rules out the platform's credentials, "configure them" would point the reader
2109
+ // at exactly the fallback the caller ruled out.
2110
+ const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
2111
+ const remedy = platformAllowed
2112
+ ? `Please configure API credentials in your environment or AI Credential settings.`
2113
+ : `The credential scope is ${credentialScope}, so only the API keys supplied with this run count; supply a key for one of these vendors.`;
2064
2114
  return `${base}. No valid API credentials/keys are configured for any of the candidate model-vendor combinations. ` +
2065
- `Tried: ${triedSummary}${suffix}. ` +
2066
- `Please configure API credentials in your environment or AI Credential settings.`;
2115
+ `Tried: ${triedSummary}${suffix}. ${remedy}`;
2067
2116
  }
2068
2117
  return `${base}. ${selectionInfo.selectionReason || 'Unknown reason'}`;
2069
2118
  }
@@ -2407,6 +2456,10 @@ export class AIPromptRunner {
2407
2456
  for (let i = 0; i < allCandidates.length; i++) {
2408
2457
  const candidate = allCandidates[i];
2409
2458
  const attemptStartTime = Date.now();
2459
+ // A caller that has cancelled wants no further model calls — not this candidate, not the next.
2460
+ if (cancellationToken?.aborted) {
2461
+ return this.stopFailoverForCancellation(prompt, this.buildCancellationError(), failoverAttempts, promptRun);
2462
+ }
2410
2463
  // Skip candidates with no credentials configured. `allCandidates` is intentionally the
2411
2464
  // FULL priority-ordered list (see the DECISION note in selectModelWithAPIKeyTracked),
2412
2465
  // so it can include vendors that have no API key in this environment. Firing a live
@@ -2438,6 +2491,17 @@ export class AIPromptRunner {
2438
2491
  }
2439
2492
  // Execute the model with this candidate
2440
2493
  const result = await this.executeModel(candidate.model, renderedPrompt, prompt, params, candidate.vendorId || null, conversationMessages, templateMessageRole, cancellationToken, candidate.driverClass, candidate.apiName, candidate.supportsEffortLevel, candidate.effortLevel, candidate.promptModelConfiguration);
2494
+ // A failure caused by the caller cancelling is the caller's decision, not the model's, so it
2495
+ // is neither failed over nor reported as a model failure. A result that already says it is
2496
+ // not eligible for failover (a driver's own cancelled result) is returned as it is; one that
2497
+ // would fail over is replaced by a cancellation.
2498
+ if (!result.success && (cancellationToken?.aborted || this.isCallerCancellation(result.errorInfo))) {
2499
+ if (result.errorInfo?.canFailover !== true) {
2500
+ this.logFailoverCancellation(prompt, failoverAttempts, promptRun);
2501
+ return result;
2502
+ }
2503
+ return this.stopFailoverForCancellation(prompt, this.buildCancellationError(), failoverAttempts, promptRun);
2504
+ }
2441
2505
  // CRITICAL FIX: Check if result failed but is retriable (network errors, rate limits, etc.)
2442
2506
  // Provider drivers (GeminiLLM, OpenAILLM, etc.) catch errors internally and return ChatResult{success: false}
2443
2507
  // instead of throwing, so we must check result.success here.
@@ -2465,9 +2529,13 @@ export class AIPromptRunner {
2465
2529
  return result;
2466
2530
  }
2467
2531
  catch (error) {
2468
- lastError = error;
2532
+ lastError = this.asModelError(error);
2469
2533
  // Analyze error to get error info
2470
2534
  const errorInfo = ErrorAnalyzer.analyzeError(lastError);
2535
+ if (cancellationToken?.aborted || this.isCallerCancellation(errorInfo)) {
2536
+ const cancellation = this.isCallerCancellation(errorInfo) ? lastError : this.buildCancellationError();
2537
+ return this.stopFailoverForCancellation(prompt, cancellation, failoverAttempts, promptRun);
2538
+ }
2471
2539
  // Use shared failover error handling logic
2472
2540
  const decision = await this.processFailoverError(lastError, errorInfo, candidate, attemptStartTime, i, allCandidates, failoverAttempts, prompt, failoverConfig);
2473
2541
  // Update candidates list (may have been filtered)
@@ -2565,27 +2633,25 @@ export class AIPromptRunner {
2565
2633
  * Updates prompt run with successful failover tracking data
2566
2634
  */
2567
2635
  updatePromptRunWithFailoverSuccess(promptRun, failoverAttempts, currentModel, currentVendorId) {
2568
- promptRun.FailoverAttempts = failoverAttempts.length;
2569
- promptRun.FailoverErrors = JSON.stringify(failoverAttempts.map(a => ({
2570
- model: a.modelId,
2571
- vendor: a.vendorId,
2572
- error: a.error.message,
2573
- errorType: a.errorType
2574
- })));
2575
- promptRun.FailoverDurations = JSON.stringify(failoverAttempts.map(a => a.duration));
2576
- promptRun.TotalFailoverDuration = failoverAttempts.reduce((sum, a) => sum + a.duration, 0);
2577
- // Update ModelID if we ended up using a different model
2578
- if (!UUIDsEqual(currentModel.ID, promptRun.OriginalModelID)) {
2579
- promptRun.ModelID = currentModel.ID;
2580
- }
2581
- if (currentVendorId && !UUIDsEqual(currentVendorId, promptRun.VendorID)) {
2582
- promptRun.VendorID = currentVendorId;
2583
- }
2636
+ this.recordFailoverFields(promptRun, run => {
2637
+ this.applyFailoverAttempts(run, failoverAttempts);
2638
+ // Update ModelID if we ended up using a different model
2639
+ if (!UUIDsEqual(currentModel.ID, run.OriginalModelID)) {
2640
+ run.ModelID = currentModel.ID;
2641
+ }
2642
+ if (currentVendorId && !UUIDsEqual(currentVendorId, run.VendorID)) {
2643
+ run.VendorID = currentVendorId;
2644
+ }
2645
+ });
2584
2646
  }
2585
2647
  /**
2586
2648
  * Updates prompt run with failover failure tracking data
2587
2649
  */
2588
2650
  updatePromptRunWithFailoverFailure(promptRun, failoverAttempts) {
2651
+ this.recordFailoverFields(promptRun, run => this.applyFailoverAttempts(run, failoverAttempts));
2652
+ }
2653
+ /** Writes the failover attempts onto a prompt run: their count, errors and durations. */
2654
+ applyFailoverAttempts(promptRun, failoverAttempts) {
2589
2655
  promptRun.FailoverAttempts = failoverAttempts.length;
2590
2656
  promptRun.FailoverErrors = JSON.stringify(failoverAttempts.map(a => ({
2591
2657
  model: a.modelId,
@@ -2596,6 +2662,68 @@ export class AIPromptRunner {
2596
2662
  promptRun.FailoverDurations = JSON.stringify(failoverAttempts.map(a => a.duration));
2597
2663
  promptRun.TotalFailoverDuration = failoverAttempts.reduce((sum, a) => sum + a.duration, 0);
2598
2664
  }
2665
+ /**
2666
+ * Sets a prompt run's failover fields now, and again in the queued finalize update. The run's
2667
+ * 'Running' INSERT is queued without being awaited, and when it lands the entity reloads from what
2668
+ * was inserted — undoing any field set while it was in flight. Writing the fields inside the
2669
+ * finalize task, which runs after that reload, is what makes them persist.
2670
+ */
2671
+ recordFailoverFields(promptRun, apply) {
2672
+ apply(promptRun);
2673
+ this._pendingFailoverFields.set(promptRun, apply);
2674
+ }
2675
+ /**
2676
+ * Whether a failure was caused by the caller cancelling the request. The drivers and
2677
+ * {@link buildCancellationError} mark a cancellation the same way: not eligible for failover, with
2678
+ * the `request_cancelled` provider error code.
2679
+ */
2680
+ isCallerCancellation(errorInfo) {
2681
+ return errorInfo?.canFailover === false && errorInfo?.providerErrorCode === CALLER_CANCELLATION_CODE;
2682
+ }
2683
+ /**
2684
+ * The error for a model call the caller cancelled. It carries the same classification the drivers
2685
+ * give a cancelled request — Fatal and not eligible for failover — so ErrorAnalyzer, the failover
2686
+ * loop and the validation retries all stop on it rather than treating it as an unknown model error.
2687
+ */
2688
+ buildCancellationError(message) {
2689
+ const error = new Error(message || 'Chat completion was cancelled');
2690
+ error.errorInfo = {
2691
+ errorType: 'Unknown',
2692
+ severity: 'Fatal',
2693
+ canFailover: false,
2694
+ providerErrorCode: CALLER_CANCELLATION_CODE,
2695
+ };
2696
+ return error;
2697
+ }
2698
+ /**
2699
+ * Ends the failover loop for a caller cancellation: logs it once and returns the error result
2700
+ * without trying another candidate.
2701
+ */
2702
+ stopFailoverForCancellation(prompt, cancellation, failoverAttempts, promptRun) {
2703
+ this.logFailoverCancellation(prompt, failoverAttempts, promptRun);
2704
+ return this.createFailoverErrorResult(cancellation, failoverAttempts);
2705
+ }
2706
+ /**
2707
+ * Logs a caller cancellation that ended the failover loop, once and at info level, and records any
2708
+ * real failures that came before it on the prompt run.
2709
+ */
2710
+ logFailoverCancellation(prompt, failoverAttempts, promptRun) {
2711
+ LogStatusEx({
2712
+ message: `⏹️ Prompt "${prompt.Name}" was cancelled by the caller — not trying any further model candidates`,
2713
+ category: 'AI',
2714
+ additionalArgs: [{ promptId: prompt.ID, priorFailures: failoverAttempts.length }]
2715
+ });
2716
+ if (promptRun && failoverAttempts.length > 0) {
2717
+ this.updatePromptRunWithFailoverFailure(promptRun, failoverAttempts);
2718
+ }
2719
+ }
2720
+ /**
2721
+ * Whether an error ended a prompt run because the caller cancelled it: the caller's token is
2722
+ * aborted, or the error is classified as a cancellation.
2723
+ */
2724
+ isCancellation(error, params) {
2725
+ return params.cancellationToken?.aborted === true || this.isCallerCancellation(ErrorAnalyzer.analyzeError(error));
2726
+ }
2599
2727
  /**
2600
2728
  * Creates an error result for failed failover attempts
2601
2729
  */
@@ -2621,7 +2749,7 @@ export class AIPromptRunner {
2621
2749
  errorMessage: lastError?.message || 'Unknown error',
2622
2750
  exception: lastError,
2623
2751
  errorInfo: errorInfo,
2624
- statusText: `Failover failed after ${failoverAttempts.length} attempts`,
2752
+ statusText: this.isCallerCancellation(errorInfo) ? 'Cancelled' : `Failover failed after ${failoverAttempts.length} attempts`,
2625
2753
  timeElapsed: endTime.getTime() - startTime.getTime(),
2626
2754
  data: null
2627
2755
  };
@@ -2661,14 +2789,7 @@ export class AIPromptRunner {
2661
2789
  resolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration) {
2662
2790
  try {
2663
2791
  return ResolveNativeToolCalling({
2664
- catalogConfiguration: AIEngine.Instance.GetEffectiveModelConfiguration(model.ID, vendorId
2665
- // Must be the INFERENCE PROVIDER row, not the Model Developer row: most models carry
2666
- // two AIModelVendor rows for the same VendorID, and ModelVendors has no guaranteed
2667
- // order. Picking the developer row merges an empty config layer and silently drops any
2668
- // per-serving-path LLM.* knob (notably the SupportsNativeToolCalling kill switch).
2669
- ? model.ModelVendors?.find(mv => UUIDsEqual(mv.VendorID, vendorId)
2670
- && mv.Status === 'Active' && this.isInferenceProvider(mv))?.ID
2671
- : undefined),
2792
+ catalogConfiguration: this.catalogConfigurationFor(model, vendorId),
2672
2793
  promptConfiguration: prompt.PromptConfigurationObject,
2673
2794
  promptModelConfiguration,
2674
2795
  // Action tools and control-flow tools are counted separately: under the hybrid the control
@@ -2683,6 +2804,20 @@ export class AIPromptRunner {
2683
2804
  return { useNativeTools: false, mode: 'Envelope', controlFlow: 'envelope', toolResults: false };
2684
2805
  }
2685
2806
  }
2807
+ /**
2808
+ * The merged catalog configuration for the selected model on the selected vendor.
2809
+ *
2810
+ * Must resolve the INFERENCE PROVIDER row, not the Model Developer row: most models carry two
2811
+ * AIModelVendor rows for the same VendorID, and ModelVendors has no guaranteed order. Picking the
2812
+ * developer row merges an empty config layer and silently drops any per-serving-path LLM.* knob
2813
+ * (notably the SupportsNativeToolCalling kill switch).
2814
+ */
2815
+ catalogConfigurationFor(model, vendorId) {
2816
+ return AIEngine.Instance.GetEffectiveModelConfiguration(model.ID, vendorId
2817
+ ? model.ModelVendors?.find(mv => UUIDsEqual(mv.VendorID, vendorId)
2818
+ && mv.Status === 'Active' && this.isInferenceProvider(mv))?.ID
2819
+ : undefined);
2820
+ }
2686
2821
  applyNativeToolCalling(chatParams, prompt, params, model, vendorId, promptModelConfiguration) {
2687
2822
  const decision = this.resolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration);
2688
2823
  if (decision.warning) {
@@ -2696,7 +2831,7 @@ export class AIPromptRunner {
2696
2831
  chatParams.tools = decision.controlFlow === 'implicit'
2697
2832
  ? params.tools
2698
2833
  : params.tools?.filter((t) => !control.has(t.name));
2699
- chatParams.toolChoice = params.toolChoice;
2834
+ chatParams.toolChoice = ResolveToolChoiceForRequest(params.toolChoice, chatParams.tools, this.catalogConfigurationFor(model, vendorId));
2700
2835
  chatParams.parallelToolCalls = params.parallelToolCalls;
2701
2836
  }
2702
2837
  // Recorded even on the envelope path, so a run is always attributable to a path. The whole
@@ -2719,7 +2854,7 @@ export class AIPromptRunner {
2719
2854
  return false;
2720
2855
  }
2721
2856
  // A cancellation is the caller's decision, never a tool problem.
2722
- if (result.errorInfo?.canFailover === false && result.errorInfo?.providerErrorCode === 'request_cancelled') {
2857
+ if (this.isCallerCancellation(result.errorInfo)) {
2723
2858
  return false;
2724
2859
  }
2725
2860
  return this.isToolSpecificFailureText(`${result.errorMessage ?? ''} ${result.statusText ?? ''}`);
@@ -2806,6 +2941,13 @@ export class AIPromptRunner {
2806
2941
  // Resolve credentials using hierarchical resolution (Credentials system with legacy fallback)
2807
2942
  const apiKey = await this.resolveCredentialForExecution(driverClass, prompt.ID, model.ID, vendorId ?? undefined, params);
2808
2943
  // Create LLM instance with vendor-specific driver class
2944
+ // No key under a scope that rules out the environment must not reach a driver: the OpenAI and
2945
+ // Anthropic SDKs read OPENAI_API_KEY / ANTHROPIC_API_KEY themselves when handed none. Selection
2946
+ // and failover already skip unkeyed candidates; parallel tasks are planned without the scope.
2947
+ if (!apiKey?.trim() && !CredentialScopeAllows(params.CredentialScope, 'Environment')) {
2948
+ throw new Error(`No credentials found for driver class '${driverClass}': the credential scope is ${params.CredentialScope}, ` +
2949
+ `and this run carries no API key for it.`);
2950
+ }
2809
2951
  llm = MJGlobal.Instance.ClassFactory.CreateInstance(BaseLLM, driverClass, apiKey);
2810
2952
  // Prepare chat parameters
2811
2953
  chatParams = new ChatParams();
@@ -2841,7 +2983,7 @@ export class AIPromptRunner {
2841
2983
  // Stop sequences are handled separately: the prompt value is comma-delimited and gated by
2842
2984
  // driver support; additionalParameters supplies a ready-made array that overrides it.
2843
2985
  if (prompt.StopSequences && this.shouldApplyStopSequences(prompt, model, vendorId, llm)) {
2844
- chatParams.stopSequences = prompt.StopSequences.split(',').map((s) => s.replace(AIPromptRunner.STOP_SEQUENCE_TRIM_REGEX, '')).filter((s) => s.length > 0);
2986
+ chatParams.stopSequences = prompt.StopSequences.split(',').map((s) => TrimSpacesAndTabs(s)).filter((s) => s.length > 0);
2845
2987
  }
2846
2988
  if (params.additionalParameters?.stopSequences !== undefined) {
2847
2989
  chatParams.stopSequences = params.additionalParameters.stopSequences;
@@ -2969,6 +3111,10 @@ export class AIPromptRunner {
2969
3111
  }
2970
3112
  catch (error) {
2971
3113
  const errorInfo = ErrorAnalyzer.analyzeError(error, driverClass);
3114
+ // A caller cancellation is not a model failure. Whoever handles it logs it once, at info level.
3115
+ if (this.isCallerCancellation(errorInfo)) {
3116
+ throw error;
3117
+ }
2972
3118
  this.logError(error, {
2973
3119
  category: 'ModelExecution',
2974
3120
  model: model,
@@ -3086,18 +3232,26 @@ export class AIPromptRunner {
3086
3232
  // Neither a caller token nor a prompt timeout — execute unbounded (legacy behavior).
3087
3233
  return await llm.ChatCompletion(chatParams);
3088
3234
  }
3089
- return await Promise.race([
3090
- llm.ChatCompletion(chatParams),
3091
- new Promise((_, reject) => {
3092
- const fail = () => reject(this.buildAbortError(signal, bound));
3093
- if (signal.aborted) {
3094
- fail();
3095
- }
3096
- else {
3097
- signal.addEventListener('abort', fail, { once: true });
3098
- }
3099
- }),
3100
- ]);
3235
+ let fail;
3236
+ const aborted = new Promise((_, reject) => {
3237
+ fail = () => reject(this.buildAbortError(signal, bound));
3238
+ if (signal.aborted) {
3239
+ fail();
3240
+ }
3241
+ else {
3242
+ signal.addEventListener('abort', fail, { once: true });
3243
+ }
3244
+ });
3245
+ try {
3246
+ return await Promise.race([llm.ChatCompletion(chatParams), aborted]);
3247
+ }
3248
+ finally {
3249
+ // With no prompt timeout the signal is the caller's own token, which outlives this call: a
3250
+ // listener left on it would pile up across every prompt the caller runs.
3251
+ if (fail) {
3252
+ signal.removeEventListener('abort', fail);
3253
+ }
3254
+ }
3101
3255
  }
3102
3256
  /**
3103
3257
  * Builds the rejection error for an aborted model call — a typed {@link AIPromptTimeoutError} when
@@ -3108,7 +3262,7 @@ export class AIPromptRunner {
3108
3262
  const reason = signal.reason;
3109
3263
  return reason instanceof AIPromptTimeoutError ? reason : new Error('Chat completion timed out');
3110
3264
  }
3111
- return new Error('Chat completion was cancelled');
3265
+ return this.buildCancellationError();
3112
3266
  }
3113
3267
  /**
3114
3268
  * Walks every message in chatParams and rewrites media content blocks
@@ -3183,7 +3337,6 @@ export class AIPromptRunner {
3183
3337
  const result = [];
3184
3338
  let inManifest = false;
3185
3339
  let mutated = false;
3186
- const entryRegex = /^\*\*[A-Z]+\*\* — .+? \[(?<mime>[^\]]+)\]/;
3187
3340
  for (const line of lines) {
3188
3341
  if (line.startsWith('## Available Artifacts')) {
3189
3342
  inManifest = true;
@@ -3196,10 +3349,11 @@ export class AIPromptRunner {
3196
3349
  result.push(line);
3197
3350
  if (!inManifest)
3198
3351
  continue;
3199
- const match = entryRegex.exec(line);
3200
- if (!match)
3352
+ // `**A** — name [mime]`; parsed linearly (CodeQL js/polynomial-redos flagged the regex form).
3353
+ const entryMime = ParseManifestEntryMime(line);
3354
+ if (entryMime === null)
3201
3355
  continue;
3202
- const mime = (match.groups?.mime ?? '').toLowerCase();
3356
+ const mime = entryMime.toLowerCase();
3203
3357
  const modality = mime.split('/')[0];
3204
3358
  if (modality !== 'image' && modality !== 'audio' && modality !== 'video')
3205
3359
  continue;
@@ -3320,18 +3474,6 @@ export class AIPromptRunner {
3320
3474
  * at any level of the AIModelType → AIModel → AIModelVendor cascade.
3321
3475
  */
3322
3476
  static { this.DEFAULT_PREFILL_FALLBACK = '# **CRITICAL**\nYour response must start with exactly: {{prefill}}\nDo not add quotes, markdown formatting, or any other characters before it.'; }
3323
- /**
3324
- * Regex used to trim only horizontal whitespace (spaces and tabs) from the start and end
3325
- * of each stop sequence token after comma-splitting.
3326
- *
3327
- * We intentionally do NOT use String.trim() here because stop sequences can legitimately
3328
- * begin or end with newline characters. For example, the sequence "\n```" is designed to
3329
- * match only a closing code fence (preceded by a newline), distinguishing it from an
3330
- * opening "```json" fence that does not start with a newline. Using trim() would strip
3331
- * that leading "\n", turning "\n```" into "```" and causing the stop to fire on the
3332
- * opening fence instead — producing an empty response for non-native prefill providers.
3333
- */
3334
- static { this.STOP_SEQUENCE_TRIM_REGEX = /^[ \t]+|[ \t]+$/g; }
3335
3477
  /**
3336
3478
  * Substrings that mark a provider failure as TOOLS-specific, so the native call is worth one
3337
3479
  * envelope retry (see {@link AIPromptRunner.isToolSpecificFailure}). Drawn from how the
@@ -3600,6 +3742,10 @@ export class AIPromptRunner {
3600
3742
  }
3601
3743
  }
3602
3744
  catch (error) {
3745
+ // A cancellation ends the retries; the caller logs it and records the run as cancelled.
3746
+ if (this.isCancellation(error, params)) {
3747
+ throw error;
3748
+ }
3603
3749
  lastError = error;
3604
3750
  this.logError(error, {
3605
3751
  category: 'ExecutionRetry',
@@ -3663,6 +3809,22 @@ export class AIPromptRunner {
3663
3809
  LogStatus(` Waiting ${delaySeconds}s before retry (strategy: ${prompt.RetryStrategy || 'Fixed'})...`);
3664
3810
  await new Promise(resolve => setTimeout(resolve, delay));
3665
3811
  }
3812
+ /**
3813
+ * The Error a failover attempt records for a caught value. A streaming call rejects with its failed
3814
+ * ChatResult (BaseLLM) rather than an Error, so its `.message` was undefined and every such failure
3815
+ * reached the prompt run and the agent run as "Unknown error". Keeps the driver's classification on
3816
+ * it, which ErrorAnalyzer then honours. Any other rejected value is classified as itself, with its
3817
+ * `errorMessage` read as the message ErrorAnalyzer looks for — so a bare `{ status: 429 }` stays a
3818
+ * RateLimit and `{ errorMessage: 'Invalid API key provided' }` stays an Authentication error.
3819
+ */
3820
+ asModelError(caught) {
3821
+ if (caught instanceof Error) {
3822
+ return caught;
3823
+ }
3824
+ const wrapped = new Error(caught?.errorMessage || caught?.statusText || 'Model execution failed');
3825
+ wrapped.errorInfo = caught?.errorInfo ?? ErrorAnalyzer.analyzeError({ ...caught, message: caught?.errorMessage });
3826
+ return wrapped;
3827
+ }
3666
3828
  /**
3667
3829
  * Filters out all candidates from a vendor when a vendor-level error occurs.
3668
3830
  * Vendor-level errors affect all models from that vendor:
@@ -4311,9 +4473,11 @@ export class AIPromptRunner {
4311
4473
  throw new Error('Repair JSON prompt not found in MJ: System category');
4312
4474
  }
4313
4475
  // Run the repair prompt
4476
+ // The repair runs inside the caller's run, so it runs on the caller's user, configuration and
4477
+ // credentials — under RuntimeOnly it must not reach a key the caller's prompt could not.
4314
4478
  const repairResult = await this.ExecutePrompt({
4479
+ ...PickPromptExecutionScope(params),
4315
4480
  parentPromptRunId: currentPromptRun.ID,
4316
- contextUser: params.contextUser,
4317
4481
  prompt: repairPrompt,
4318
4482
  data: {
4319
4483
  ERROR_MESSAGE: trueError,
@@ -4650,6 +4814,16 @@ export class AIPromptRunner {
4650
4814
  promptRun.Success = modelResult.success && (parsedResult.validationResult?.Success !== false);
4651
4815
  // Set final Status based on success
4652
4816
  promptRun.Status = promptRun.Success ? 'Completed' : 'Failed';
4817
+ // A call the caller cancelled is recorded as cancelled, not as a failed model call.
4818
+ if (!modelResult.success && this.isCallerCancellation(modelResult.errorInfo)) {
4819
+ promptRun.Status = 'Cancelled';
4820
+ promptRun.Cancelled = true;
4821
+ promptRun.CancellationReason = 'user_requested';
4822
+ }
4823
+ // The failover fields were set while the INSERT may still have been in flight, and its reload
4824
+ // would have undone them: set them again here, after the reload.
4825
+ this._pendingFailoverFields.get(promptRun)?.(promptRun);
4826
+ this._pendingFailoverFields.delete(promptRun);
4653
4827
  // Set ErrorDetails if failed
4654
4828
  if (!promptRun.Success) {
4655
4829
  if (!modelResult.success && modelResult.errorMessage) {