@memberjunction/ai-prompts 6.2.2 → 6.3.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.
Files changed (60) hide show
  1. package/README.md +28 -0
  2. package/dist/AIPromptRunner.d.ts +6 -5
  3. package/dist/AIPromptRunner.d.ts.map +1 -1
  4. package/dist/AIPromptRunner.js +96 -41
  5. package/dist/AIPromptRunner.js.map +1 -1
  6. package/dist/BaseModelRunner.d.ts +33 -62
  7. package/dist/BaseModelRunner.d.ts.map +1 -1
  8. package/dist/BaseModelRunner.js +93 -231
  9. package/dist/BaseModelRunner.js.map +1 -1
  10. package/dist/ParallelExecutionCoordinator.js +3 -3
  11. package/dist/ParallelExecutionCoordinator.js.map +1 -1
  12. package/dist/decision/AIDecisionRunner.d.ts +34 -10
  13. package/dist/decision/AIDecisionRunner.d.ts.map +1 -1
  14. package/dist/decision/AIDecisionRunner.js +72 -38
  15. package/dist/decision/AIDecisionRunner.js.map +1 -1
  16. package/dist/decision/LLMDecision.d.ts +8 -0
  17. package/dist/decision/LLMDecision.d.ts.map +1 -1
  18. package/dist/decision/LLMDecision.js +15 -2
  19. package/dist/decision/LLMDecision.js.map +1 -1
  20. package/dist/decision/decision-limits.d.ts +80 -0
  21. package/dist/decision/decision-limits.d.ts.map +1 -0
  22. package/dist/decision/decision-limits.js +142 -0
  23. package/dist/decision/decision-limits.js.map +1 -0
  24. package/dist/decision/decision-runner.types.d.ts +7 -1
  25. package/dist/decision/decision-runner.types.d.ts.map +1 -1
  26. package/dist/decision/decision-runner.types.js.map +1 -1
  27. package/dist/decision/decision-use.d.ts +77 -0
  28. package/dist/decision/decision-use.d.ts.map +1 -0
  29. package/dist/decision/decision-use.js +104 -0
  30. package/dist/decision/decision-use.js.map +1 -0
  31. package/dist/decision/shadow-decision.d.ts +90 -0
  32. package/dist/decision/shadow-decision.d.ts.map +1 -0
  33. package/dist/decision/shadow-decision.js +85 -0
  34. package/dist/decision/shadow-decision.js.map +1 -0
  35. package/dist/embedding/AIEmbeddingRunner.d.ts +10 -2
  36. package/dist/embedding/AIEmbeddingRunner.d.ts.map +1 -1
  37. package/dist/embedding/AIEmbeddingRunner.js +22 -5
  38. package/dist/embedding/AIEmbeddingRunner.js.map +1 -1
  39. package/dist/embedding/embedding-runner.types.d.ts +24 -3
  40. package/dist/embedding/embedding-runner.types.d.ts.map +1 -1
  41. package/dist/embedding/embedding-runner.types.js +13 -1
  42. package/dist/embedding/embedding-runner.types.js.map +1 -1
  43. package/dist/index.d.ts +4 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +4 -0
  46. package/dist/index.js.map +1 -1
  47. package/dist/jsonRecovery.d.ts +31 -0
  48. package/dist/jsonRecovery.d.ts.map +1 -0
  49. package/dist/jsonRecovery.js +79 -0
  50. package/dist/jsonRecovery.js.map +1 -0
  51. package/dist/linearTextScan.d.ts +12 -0
  52. package/dist/linearTextScan.d.ts.map +1 -1
  53. package/dist/linearTextScan.js +36 -0
  54. package/dist/linearTextScan.js.map +1 -1
  55. package/dist/nativeToolCallingGate.d.ts +23 -4
  56. package/dist/nativeToolCallingGate.d.ts.map +1 -1
  57. package/dist/nativeToolCallingGate.js +19 -2
  58. package/dist/nativeToolCallingGate.js.map +1 -1
  59. package/dist/tsconfig.tsbuildinfo +1 -0
  60. package/package.json +12 -12
package/README.md CHANGED
@@ -303,6 +303,34 @@ if (result.Success) {
303
303
  }
304
304
  ```
305
305
 
306
+ ### Decisions
307
+
308
+ `AIDecisionRunner` runs typed decisions (Likelihood, Choice and Score questions) on `Decision`-type models. It does for a decision what `AIPromptRunner` does for a chat call: it picks a model from the decision prompt's bindings (`Default Decision` binds Jev, then LLM Decision), resolves credentials, fails over, and writes an `MJ: AI Prompt Runs` row with tokens and cost.
309
+
310
+ - **Model limits.** Each request is fitted to the candidate model's declared `ModelConfiguration.Decision` limits:
311
+ - more questions than `MaxQuestionsPerCall`: the request is split into several calls to the same model, at most four at once (`MAX_CONCURRENT_CHUNK_CALLS`), and the answers are merged;
312
+ - more Choice options or Score levels than declared, or more estimated tokens than `MaxStateTokens` (state plus the largest chunk, at four characters a token): the request fails over to the next model.
313
+ - **Timeout.** Each call is bounded by `timeoutMS`, else the prompt's `TimeoutMS`, else `DEFAULT_DECISION_TIMEOUT_MS` (60 s). A caller passing `0` opts out.
314
+ - **Media.** `AIDecisionParams.Media` carries images, audio, video or PDFs alongside the text state. Only drivers whose `SupportedMediaTypes` include every item's type are tried; the others are skipped with failover. `GeminiDecision` reads all four. The run row records each item's type, MIME type and URI or size, never its data.
315
+ - **The answering model.** `LLMDecision` reports the chat model that actually answered as the `ResolvedModel`, even after a failover inside its chat prompt, so the right calibration is applied.
316
+
317
+ **Calibration.** A decision model's raw probabilities are not calibrated. Fits are model metadata: `ModelConfiguration.Decision.Calibrations` on the answering AI model, one entry per decision use, question and exact resolved model. A consumer looks one up with `AIEngine.Instance.FindDecisionCalibration({ Use, Question }, answeredBy)` or `CalibrateDecisionProbability({ Use, Question }, probability, answeredBy)` (`AIEngineBase.Instance` in the browser); an answer from a model with no fit is treated as unsure. The `fit-decision-calibration` rig in the integration test suite fits new entries from labelled runs.
318
+
319
+ **Shadow decisions.** `StartShadowDecision` runs a decision beside the path that decides today, never lets it change the outcome, and records whether the two agreed. The decision's run is tagged `RunName = 'Shadow: <use>'` and its `Comments` hold the comparison as JSON. That is how a closed-set LLM call moves to a decision model: shadow first, then calibrate on the recorded runs, then switch.
320
+
321
+ ```typescript
322
+ const shadow = StartShadowDecision<string>({
323
+ Use: 'feedback-classifier',
324
+ Decision: params, // an AIDecisionParams
325
+ Compare: (answers, primary) => {
326
+ const chosen = answers['category']?.Kind === 'Choice' ? answers['category'].Value : null;
327
+ return { Agreed: chosen === primary, Summary: `decision ${chosen}, prompt ${primary}` };
328
+ },
329
+ });
330
+ const category = await classifyWithPrompt(); // the existing path, unchanged
331
+ void shadow.Record(category); // fire and forget
332
+ ```
333
+
306
334
  ## Usage
307
335
 
308
336
  ### Basic Prompt Execution
@@ -608,11 +608,6 @@ export declare class AIPromptRunner extends BaseModelRunner {
608
608
  * Executes the model with retry logic for validation failures
609
609
  */
610
610
  private executeWithValidationRetries;
611
- /**
612
- * Transitions to the next failover candidate.
613
- * Returns the next candidate info or null if no candidates are available.
614
- */
615
- private transitionToNextCandidate;
616
611
  /**
617
612
  * Generates a JSON schema from an example object for validation
618
613
  */
@@ -682,6 +677,12 @@ export declare class AIPromptRunner extends BaseModelRunner {
682
677
  * @throws Error if the value cannot be parsed as a date and validation is enabled
683
678
  */
684
679
  private parseDateOutput;
680
+ /**
681
+ * Parses a reply that starts with `{` or `[` but failed a plain parse. For object output, a
682
+ * complete leading JSON value followed by stray text (#3065) is used and the dropped tail is
683
+ * logged; anything else goes through `CleanJSON` as before, and its parse error reaches the caller.
684
+ */
685
+ private parseWithTrailingFragment;
685
686
  /**
686
687
  * Parses an object (JSON) output value with optional repair capabilities.
687
688
  *
@@ -1 +1 @@
1
- {"version":3,"file":"AIPromptRunner.d.ts","sourceRoot":"","sources":["../src/AIPromptRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,UAAU,EAAmB,WAAW,EAAiF,qBAAqB,EAAkI,MAAM,oBAAoB,CAAC;AACzU,OAAO,EACL,eAAe,EAEf,KAAK,oBAAoB,EAG1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAA8C,yBAAyB,EAA2G,MAAM,yBAAyB,CAAC;AACzN,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAqB,iBAAiB,EAAE,oBAAoB,EAA4B,MAAM,8BAA8B,CAAC;AACpI,OAAO,EAA0D,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGxG,OAAO,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAE9H,OAAO,EAAwB,KAAK,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAKxG,OAAO,EAAyB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OASG;YACW,iBAAiB;IAkJ/B;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;IAe9B;;OAEG;YACW,qBAAqB;IAmGnC;;OAEG;YACW,eAAe;IA2B7B;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;IAuE9B,uGAAuG;IACvG,SAAS,CAAC,mCAAmC,IAAI,uBAAuB;IAOxE;;;;;OAKG;IACH,OAAO,CAAC,kBAAkB;IAkC1B;;;OAGG;IACH,OAAO,CAAC,uBAAuB;IA0B/B,uGAAuG;IACvG,OAAO,CAAC,sBAAsB;IAQ9B;;;OAGG;IACH,OAAO,CAAC,iCAAiC;IAIzC,2GAA2G;IAC3G,OAAO,CAAC,0BAA0B;IAwBlC;;OAEG;YACW,eAAe;IAsC7B;;;;;;OAMG;IACH,OAAO,CAAC,qBAAqB;IAiN7B;;OAEG;IACH,OAAO,CAAC,gCAAgC;IAuBxC;;;;;;OAMG;IACH,OAAO,CAAC,4BAA4B;CAmBrC"}
@@ -1,16 +1,16 @@
1
1
  import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText, CredentialScopeAllows, ResolveEffectiveModelConfiguration } from '@memberjunction/ai';
2
2
  import { BaseModelRunner, } from './BaseModelRunner.js';
3
- import { GetToolCallingDecision, GetToolCallingMode, RecordToolCallingDecision, RecordToolCallingMode, ResolveNativeToolCalling, ResolveToolChoiceForRequest } from './nativeToolCallingGate.js';
3
+ import { GetToolCallingDecision, GetToolCallingMode, RecordToolCallingDecision, RecordToolCallingMode, RecoveredToolCallingDecision, ResolveNativeToolCalling, ResolveToolChoiceForRequest } from './nativeToolCallingGate.js';
4
4
  import { AIModelRunner } from './AIModelRunner.js';
5
5
  import { RecordSentPrefixFingerprint, ReplayedReasoningPrefixFingerprint, WithoutReplayedReasoning } from './replayedReasoningPrefix.js';
6
6
  import { AIModelSelectionInfo, PickPromptExecutionScope } from '@memberjunction/ai-core-plus';
7
- import { LogError, LogStatus, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
7
+ import { LogError, LogStatus, IsVerboseLoggingEnabled, Metadata, TelemetryManager } from '@memberjunction/core';
8
8
  import { CleanJSON, RepairJSONEscaping, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
9
9
  import { TemplateEngineServer } from '@memberjunction/templates';
10
10
  import { ExecutionPlanner } from './ExecutionPlanner.js';
11
11
  import { AIPromptTimeoutError } from './AIPromptTimeoutError.js';
12
12
  import { BuildNoModelFoundMessage, NOT_EVALUATED_REASON } from './no-model-found-message.js';
13
- import { ParseManifestEntryMime, TrimSpacesAndTabs } from './linearTextScan.js';
13
+ import { ContainsPlaceholderPhrase, ParseManifestEntryMime, TrimSpacesAndTabs } from './linearTextScan.js';
14
14
  import { AIEngine } from '@memberjunction/aiengine';
15
15
  import { AIEngineBase } from '@memberjunction/ai-engine-base';
16
16
  import { SystemPlaceholderManager } from '@memberjunction/ai-core-plus';
@@ -21,6 +21,7 @@ import { BuildCaptureFailedPromptRunMessages, BuildStoredPromptRunMessages, Read
21
21
  // undefined at runtime ("JSON5.parse is not a function"), silently disabling the
22
22
  // local JSON-repair tier and forcing every malformed payload onto the AI-repair path.
23
23
  import JSON5 from 'json5';
24
+ import { ExtractLeadingJSONValue } from './jsonRecovery.js';
24
25
  /**
25
26
  * Best-guess MIME family for a ChatMessage content block type when the block
26
27
  * doesn't carry its own mimeType. Used by stripUnsupportedMediaBlocks to
@@ -148,6 +149,7 @@ export class AIPromptRunner extends BaseModelRunner {
148
149
  async ExecutePrompt(params) {
149
150
  const startTime = new Date();
150
151
  const promptRun = null;
152
+ let telemetryEventId = null;
151
153
  // AIEngineBase is registered as deferred — its initial load runs in the background
152
154
  // after server boot. Make sure the cached metadata (Models, Vendors, ModelVendors,
153
155
  // ConfigurationParams, etc.) is loaded before downstream resolution / planning runs.
@@ -177,6 +179,12 @@ export class AIPromptRunner extends BaseModelRunner {
177
179
  if (prompt.Status !== 'Active') {
178
180
  throw new Error(`Prompt ${prompt.Name} is not active (Status: ${prompt.Status})`);
179
181
  }
182
+ telemetryEventId = TelemetryManager.Instance.StartEvent('AI', `ExecutePrompt:${prompt.Name}`, {
183
+ promptID: prompt.ID,
184
+ promptName: prompt.Name,
185
+ modelID: params.override?.modelId,
186
+ operationType: 'chat',
187
+ });
180
188
  let renderedPromptText = '';
181
189
  // For hierarchical prompts, we need to create the parent prompt run first to get its ID
182
190
  let parentPromptRun;
@@ -298,10 +306,28 @@ export class AIPromptRunner extends BaseModelRunner {
298
306
  }
299
307
  // Note: With template composition, we only execute once so no rollup calculations needed
300
308
  // The final composed prompt is executed as a single operation
309
+ if (telemetryEventId) {
310
+ const inputTokens = result.promptRun?.TokensPrompt ?? result.chatResult?.data?.usage?.promptTokens ?? 0;
311
+ const outputTokens = result.promptRun?.TokensCompletion ?? result.chatResult?.data?.usage?.completionTokens ?? 0;
312
+ TelemetryManager.Instance.EndEvent(telemetryEventId, {
313
+ inputTokens,
314
+ outputTokens,
315
+ modelID: selection?.model?.ID,
316
+ modelName: selection?.model?.Name,
317
+ success: result.success,
318
+ errorMessage: result.errorMessage,
319
+ });
320
+ }
301
321
  // Model selection info is now included in the result from both execution methods
302
322
  return result;
303
323
  }
304
324
  catch (error) {
325
+ if (telemetryEventId) {
326
+ TelemetryManager.Instance.EndEvent(telemetryEventId, {
327
+ success: false,
328
+ errorMessage: error instanceof Error ? error.message : String(error),
329
+ });
330
+ }
305
331
  if (this.isCancellation(error, params)) {
306
332
  this.logStatus(`⏹️ Prompt "${params.prompt?.Name}" was cancelled: ${error.message}`, false, params);
307
333
  }
@@ -1331,11 +1357,33 @@ export class AIPromptRunner extends BaseModelRunner {
1331
1357
  async executeModelWithFailover(model, renderedPrompt, prompt, params, vendorId, conversationMessages, templateMessageRole = 'system', cancellationToken, allCandidates, promptRun, vendorDriverClass, vendorApiName, vendorSupportsEffortLevel, modelEffortLevel, credentialAvailability, promptModelConfiguration) {
1332
1358
  // Get failover configuration (used for errorScope filtering)
1333
1359
  const failoverConfig = this.getFailoverConfiguration(prompt);
1334
- // If no candidates provided or failover disabled, execute normally with first model
1360
+ // If no candidates provided or failover disabled, execute normally with first model. A returned
1361
+ // result carries its own tool-calling decision; a thrown error carries the one executeModel
1362
+ // tagged it with.
1335
1363
  if (!allCandidates || allCandidates.length === 0 || failoverConfig.strategy === 'None') {
1336
1364
  return this.executeModel(model, renderedPrompt, prompt, params, vendorId, conversationMessages, templateMessageRole, cancellationToken, vendorDriverClass, vendorApiName, vendorSupportsEffortLevel, modelEffortLevel, promptModelConfiguration);
1337
1365
  }
1338
- return this.ExecuteWithFailover(prompt, params, allCandidates, failoverConfig, (candidate) => this.executeModel(candidate.model, renderedPrompt, prompt, params, candidate.vendorId || null, conversationMessages, templateMessageRole, cancellationToken, candidate.driverClass, candidate.apiName, candidate.supportsEffortLevel, candidate.effortLevel, candidate.promptModelConfiguration), (lastError, failoverAttempts) => this.createFailoverErrorResult(lastError, failoverAttempts), promptRun, credentialAvailability);
1366
+ // The tool-calling decision of the latest attempt. The error result built after the last
1367
+ // candidate fails is a new object, so without this it would record no ToolCallingMode.
1368
+ let lastDecision;
1369
+ return this.ExecuteWithFailover(prompt, params, allCandidates, failoverConfig, async (candidate) => {
1370
+ lastDecision = undefined;
1371
+ try {
1372
+ 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);
1373
+ lastDecision = GetToolCallingDecision(result);
1374
+ return result;
1375
+ }
1376
+ catch (error) {
1377
+ lastDecision = error instanceof Error ? GetToolCallingDecision(error) : undefined;
1378
+ throw error;
1379
+ }
1380
+ }, (lastError, failoverAttempts) => {
1381
+ const errorResult = this.createFailoverErrorResult(lastError, failoverAttempts);
1382
+ if (lastDecision) {
1383
+ RecordToolCallingDecision(errorResult, lastDecision);
1384
+ }
1385
+ return errorResult;
1386
+ }, promptRun, credentialAvailability);
1339
1387
  }
1340
1388
  /**
1341
1389
  * Creates an error result for failed failover attempts
@@ -1588,8 +1636,12 @@ export class AIPromptRunner extends BaseModelRunner {
1588
1636
  chatParams.tools = decision.controlFlow === 'implicit'
1589
1637
  ? params.tools
1590
1638
  : params.tools?.filter((t) => !control.has(t.name));
1591
- chatParams.toolChoice = ResolveToolChoiceForRequest(params.toolChoice, chatParams.tools, this.catalogConfigurationFor(model, vendorId));
1639
+ const catalogConfiguration = this.catalogConfigurationFor(model, vendorId);
1640
+ chatParams.toolChoice = ResolveToolChoiceForRequest(params.toolChoice, chatParams.tools, catalogConfiguration);
1592
1641
  chatParams.parallelToolCalls = params.parallelToolCalls;
1642
+ if (catalogConfiguration?.LLM?.ChatCompletionsToolsRequireNoReasoning === true) {
1643
+ chatParams.toolsRequireNoReasoning = true;
1644
+ }
1593
1645
  }
1594
1646
  // Recorded even on the envelope path, so a run is always attributable to a path. The whole
1595
1647
  // decision travels so the agent loop can read `toolResults` off the result later.
@@ -1672,6 +1724,8 @@ export class AIPromptRunner extends BaseModelRunner {
1672
1724
  const envelopePrompt = await this.rerenderOrKeep(renderedPrompt, params, { ...(params.data ?? {}), _NATIVE_TOOL_CALLING: false, _NATIVE_CONTROL_FLOW: 'envelope' });
1673
1725
  chatParams.messages = this.replaceRenderedPrompt(chatParams.messages, renderedPrompt, envelopePrompt);
1674
1726
  const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
1727
+ // The request is now the fallback, so a throw from it is recorded as one.
1728
+ RecordToolCallingMode(chatParams, 'NativeFallback');
1675
1729
  const fallbackResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
1676
1730
  RecordToolCallingMode(fallbackResult, 'NativeFallback');
1677
1731
  RecordSentPrefixFingerprint(fallbackResult, sentPrefix);
@@ -1971,10 +2025,11 @@ export class AIPromptRunner extends BaseModelRunner {
1971
2025
  // to the prompt run (mode) and to the agent loop (`toolResults` — the loop answers native
1972
2026
  // calls as tool turns only when the result says so). Copying the mode alone resets `toolResults`
1973
2027
  // to false on the fresh result object, which leaves native tool results inert.
1974
- // A fallback below overwrites the mode with 'NativeFallback'.
2028
+ // A fallback below overwrites the mode with 'NativeFallback'; a tool call the driver read back
2029
+ // out of a provider rejection records 'NativeRecovered' (#5847).
1975
2030
  const gatedDecision = GetToolCallingDecision(chatParams);
1976
2031
  if (gatedDecision) {
1977
- RecordToolCallingDecision(chatResult, gatedDecision);
2032
+ RecordToolCallingDecision(chatResult, RecoveredToolCallingDecision(gatedDecision, chatResult));
1978
2033
  }
1979
2034
  // Layer 4 fallback, part two: a native-mode call that came back as a failed result for a
1980
2035
  // TOOLS-specific reason retries the same way. Non-tool failures fall through to the existing
@@ -1989,6 +2044,12 @@ export class AIPromptRunner extends BaseModelRunner {
1989
2044
  return chatResult;
1990
2045
  }
1991
2046
  catch (error) {
2047
+ // The failover loop builds its own error result from what was thrown; tagging the error with
2048
+ // the gate's decision is what lets that result record which tool-calling path this call took.
2049
+ const thrownDecision = GetToolCallingDecision(chatParams);
2050
+ if (thrownDecision && error instanceof Error) {
2051
+ RecordToolCallingDecision(error, thrownDecision);
2052
+ }
1992
2053
  const errorInfo = ErrorAnalyzer.analyzeError(error, driverClass);
1993
2054
  // A caller cancellation is not a model failure. Whoever handles it logs it once, at info level.
1994
2055
  if (this.IsCallerCancellation(errorInfo)) {
@@ -2604,34 +2665,6 @@ export class AIPromptRunner extends BaseModelRunner {
2604
2665
  // Should not reach here, but just in case
2605
2666
  throw lastError || new Error('Execution failed after all retry attempts');
2606
2667
  }
2607
- /**
2608
- * Transitions to the next failover candidate.
2609
- * Returns the next candidate info or null if no candidates are available.
2610
- */
2611
- async transitionToNextCandidate(currentModel, currentVendorId, failoverConfig, allCandidates, failoverAttempts, promptId, failoverAttempt, attemptNumber) {
2612
- // Select next candidate using failover strategy
2613
- const nextCandidates = this.selectFailoverCandidates(currentModel, currentVendorId, failoverConfig.strategy, failoverConfig.modelStrategy, allCandidates, failoverAttempts);
2614
- if (nextCandidates.length === 0) {
2615
- // No more candidates available
2616
- this.logFailoverAttempt(promptId, failoverAttempt, false);
2617
- return null;
2618
- }
2619
- const nextCandidate = nextCandidates[0];
2620
- // Log the successful transition
2621
- this.logFailoverAttempt(promptId, failoverAttempt, true);
2622
- // Apply delay before next attempt (if not the last attempt)
2623
- if (attemptNumber < failoverConfig.maxAttempts) {
2624
- const delay = this.calculateFailoverDelay(attemptNumber, failoverConfig.delaySeconds);
2625
- await new Promise(resolve => setTimeout(resolve, delay));
2626
- }
2627
- return {
2628
- model: nextCandidate.model,
2629
- vendorId: nextCandidate.vendorId,
2630
- driverClass: nextCandidate.driverClass,
2631
- apiName: nextCandidate.apiName,
2632
- supportsEffortLevel: nextCandidate.supportsEffortLevel || false
2633
- };
2634
- }
2635
2668
  /**
2636
2669
  * Generates a JSON schema from an example object for validation
2637
2670
  */
@@ -2681,8 +2714,10 @@ export class AIPromptRunner extends BaseModelRunner {
2681
2714
  }
2682
2715
  // Check if string value contains common placeholder text
2683
2716
  if (typeof value === 'string') {
2684
- const placeholderValuePatterns = /(goes here|placeholder|example|sample value|value\d+|UUID|your .* here|insert .* here)/i;
2685
- if (placeholderValuePatterns.test(value)) {
2717
+ // "your … here" / "insert … here" are scanned linearly: as `.*` alternatives in this regex
2718
+ // they were polynomial on long OutputExample strings (#4819).
2719
+ const placeholderValuePatterns = /(goes here|placeholder|example|sample value|value\d+|UUID)/i;
2720
+ if (placeholderValuePatterns.test(value) || ContainsPlaceholderPhrase(value)) {
2686
2721
  return true;
2687
2722
  }
2688
2723
  }
@@ -2964,6 +2999,23 @@ export class AIPromptRunner extends BaseModelRunner {
2964
2999
  }
2965
3000
  return dateResult;
2966
3001
  }
3002
+ /**
3003
+ * Parses a reply that starts with `{` or `[` but failed a plain parse. For object output, a
3004
+ * complete leading JSON value followed by stray text (#3065) is used and the dropped tail is
3005
+ * logged; anything else goes through `CleanJSON` as before, and its parse error reaches the caller.
3006
+ */
3007
+ parseWithTrailingFragment(rawOutput, prompt) {
3008
+ if (prompt.OutputType === 'object') {
3009
+ const leading = ExtractLeadingJSONValue(rawOutput);
3010
+ if (leading) {
3011
+ const tail = leading.Tail.trim();
3012
+ const shown = tail.length > 200 ? `${tail.slice(0, 200)}…` : tail;
3013
+ console.warn(`AIPromptRunner: prompt "${prompt.Name}" returned a complete JSON value followed by ${tail.length} characters of stray text; using the value and dropping: ${shown}`);
3014
+ return leading.Value;
3015
+ }
3016
+ }
3017
+ return JSON.parse(CleanJSON(rawOutput));
3018
+ }
2967
3019
  /**
2968
3020
  * Parses an object (JSON) output value with optional repair capabilities.
2969
3021
  *
@@ -2987,7 +3039,7 @@ export class AIPromptRunner extends BaseModelRunner {
2987
3039
  parsedResult = JSON.parse(rawOutput);
2988
3040
  }
2989
3041
  catch {
2990
- parsedResult = JSON.parse(CleanJSON(rawOutput));
3042
+ parsedResult = this.parseWithTrailingFragment(rawOutput, prompt);
2991
3043
  }
2992
3044
  }
2993
3045
  else {
@@ -3009,8 +3061,11 @@ export class AIPromptRunner extends BaseModelRunner {
3009
3061
  return rawOutput; // Return raw output if skipping validation
3010
3062
  }
3011
3063
  }
3012
- // Clean validation syntax if needed
3013
- if (parsedResult && (cleanValidationSyntax || (!skipValidation && prompt.OutputExample))) {
3064
+ // Clean validation syntax if needed. An OutputExample alone does not ask for it under
3065
+ // ValidationBehavior 'None': that prompt opted out of validation, and cleaning rewrites reply
3066
+ // keys such as "Is it urgent?" (#4827). An explicit cleanValidationSyntax still cleans.
3067
+ const validationOff = (params?.validationBehavior || prompt.ValidationBehavior) === 'None';
3068
+ if (parsedResult && (cleanValidationSyntax || (!skipValidation && !validationOff && prompt.OutputExample))) {
3014
3069
  parsedResult = this._jsonValidator.cleanValidationSyntax(parsedResult);
3015
3070
  }
3016
3071
  return parsedResult;