@memberjunction/ai-prompts 5.51.2 → 5.51.4

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.
@@ -75,6 +75,8 @@ export declare class AIPromptRunner {
75
75
  * runs INSIDE the post-INSERT task so a slow INSERT can never clobber the finalized row). Failures
76
76
  * stay in this runner's structured log stream via the queue's `onError` hook.
77
77
  */
78
+ /** Failover fields waiting to be re-applied after a prompt run's INSERT lands; see {@link recordFailoverFields}. */
79
+ private readonly _pendingFailoverFields;
78
80
  private _promptRunQueue;
79
81
  /**
80
82
  * Process-wide cache of parsed `OutputExample` JSON, keyed by the raw example string.
@@ -487,6 +489,50 @@ export declare class AIPromptRunner {
487
489
  * Updates prompt run with failover failure tracking data
488
490
  */
489
491
  private updatePromptRunWithFailoverFailure;
492
+ /** Writes the failover attempts onto a prompt run: their count, errors and durations. */
493
+ private applyFailoverAttempts;
494
+ /**
495
+ * Sets a prompt run's failover fields now, and again in the queued finalize update. The run's
496
+ * 'Running' INSERT is queued without being awaited, and when it lands the entity reloads from what
497
+ * was inserted — undoing any field set while it was in flight. Writing the fields inside the
498
+ * finalize task, which runs after that reload, is what makes them persist.
499
+ */
500
+ private recordFailoverFields;
501
+ /**
502
+ * Whether a failure was caused by the caller cancelling the request. The drivers and
503
+ * {@link buildCancellationError} mark a cancellation the same way: not eligible for failover, with
504
+ * the `request_cancelled` provider error code.
505
+ */
506
+ private isCallerCancellation;
507
+ /**
508
+ * The error for a model call the caller cancelled. It carries the same classification the drivers
509
+ * give a cancelled request — Fatal and not eligible for failover — so ErrorAnalyzer, the failover
510
+ * loop and the validation retries all stop on it rather than treating it as an unknown model error.
511
+ */
512
+ private buildCancellationError;
513
+ /**
514
+ * Ends the failover loop for a caller cancellation: logs it once and returns the error result
515
+ * without trying another candidate.
516
+ */
517
+ private stopFailoverForCancellation;
518
+ /**
519
+ * Logs a caller cancellation that ended the failover loop, once and at info level, and records any
520
+ * real failures that came before it on the prompt run.
521
+ */
522
+ private logFailoverCancellation;
523
+ /**
524
+ * Whether an error ended a prompt run because the caller cancelled it: the caller's token is
525
+ * aborted, or the error is classified as a cancellation.
526
+ */
527
+ private isCancellation;
528
+ /**
529
+ * The classification an error already carries on `errorInfo`, if it has a complete one. This line's
530
+ * ErrorAnalyzer re-reads every error from its message, which would turn a classified cancellation
531
+ * back into an unknown, failover-eligible error.
532
+ */
533
+ private carriedErrorInfo;
534
+ /** The carried classification of an error that is a caller cancellation, else undefined. */
535
+ private carriedCancellation;
490
536
  /**
491
537
  * Creates an error result for failed failover attempts
492
538
  */
@@ -785,7 +831,26 @@ export declare class AIPromptRunner {
785
831
  */
786
832
  private parseObjectOutput;
787
833
  /**
788
- * Attempts to repair malformed JSON using a two-step process.
834
+ * Resolves the parse error that actually describes the model's output.
835
+ *
836
+ * The error reaching the repair path comes from `JSON.parse(CleanJSON(rawOutput))`, so it may
837
+ * describe one of CleanJSON's intermediate transforms rather than the response itself. That
838
+ * distinction is not cosmetic: a repair pass needs the failure offset in the *original* bytes,
839
+ * and the AI repair prompt is actively misled by an error describing text it was never shown.
840
+ *
841
+ * Observed in production: an unescaped quote at offset 23011 was reported as
842
+ * `Unexpected token 'm', "mermaid\ns"...` because CleanJSON had extracted a mermaid fence out of
843
+ * a string value before failing. Every downstream consumer — the repair model, the validation
844
+ * record, the logs — inherited that misdiagnosis.
845
+ *
846
+ * @param rawOutput - The model's unmodified output
847
+ * @param originalError - The error caught upstream, used as a fallback
848
+ * @returns The message that best describes what is wrong with `rawOutput`
849
+ */
850
+ private resolveTrueParseError;
851
+ /**
852
+ * Attempts to repair malformed JSON using a multi-step process: JSON5, then deterministic
853
+ * lexical repair, then an AI repair prompt.
789
854
  *
790
855
  * @param rawOutput - The malformed JSON string
791
856
  * @param originalError - The original parsing error
@@ -1 +1 @@
1
- {"version":3,"file":"AIPromptRunner.d.ts","sourceRoot":"","sources":["../src/AIPromptRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,UA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ACrC,cAAc,EAAE,eAAe,EAAE,GAChC,oBAAoB,EAAE;IAgIzB;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,kBAAkB,CAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,eAAe,EACxB,SAAS,EAAE,OAAO,GACjB,IAAI;CA6BR"}
@@ -2,11 +2,13 @@ import { BaseLLM, ChatParams, ChatMessageRole, GetAIAPIKey, ErrorAnalyzer, Resol
2
2
  import { AIModelRunner } from './AIModelRunner.js';
3
3
  import { AIModelSelectionInfo } from '@memberjunction/ai-core-plus';
4
4
  import { BaseEntitySaveQueue, LogErrorEx, LogStatus, LogStatusEx, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
5
- import { CleanJSON, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
5
+ import { CleanJSON, RepairJSONEscaping, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
6
6
  import { CredentialEngine } from '@memberjunction/credentials';
7
7
  import { TemplateEngineServer } from '@memberjunction/templates';
8
8
  import { ExecutionPlanner } from './ExecutionPlanner.js';
9
9
  import { AIPromptTimeoutError } from './AIPromptTimeoutError.js';
10
+ /** The `providerErrorCode` that marks a request the caller cancelled — the code the drivers use. */
11
+ const CALLER_CANCELLATION_CODE = 'request_cancelled';
10
12
  import { AIEngine } from '@memberjunction/aiengine';
11
13
  import { AIEngineBase } from '@memberjunction/ai-engine-base';
12
14
  import { SystemPlaceholderManager } from '@memberjunction/ai-core-plus';
@@ -65,6 +67,8 @@ export class AIPromptRunner {
65
67
  * runs INSIDE the post-INSERT task so a slow INSERT can never clobber the finalized row). Failures
66
68
  * stay in this runner's structured log stream via the queue's `onError` hook.
67
69
  */
70
+ /** Failover fields waiting to be re-applied after a prompt run's INSERT lands; see {@link recordFailoverFields}. */
71
+ this._pendingFailoverFields = new WeakMap();
68
72
  this._promptRunQueue = new BaseEntitySaveQueue({
69
73
  onError: (message) => this.logError(message, { category: 'PromptRunSave' }),
70
74
  });
@@ -574,14 +578,19 @@ export class AIPromptRunner {
574
578
  return result;
575
579
  }
576
580
  catch (error) {
577
- this.logError(error, {
578
- prompt: params.prompt,
579
- metadata: {
580
- executionPhase: 'main-execution',
581
- hasChildPrompts: !!params.childPrompts?.length
582
- },
583
- maxErrorLength: params.maxErrorLength
584
- });
581
+ if (this.isCancellation(error, params)) {
582
+ this.logStatus(`⏹️ Prompt "${params.prompt?.Name}" was cancelled: ${error.message}`, false, params);
583
+ }
584
+ else {
585
+ this.logError(error, {
586
+ prompt: params.prompt,
587
+ metadata: {
588
+ executionPhase: 'main-execution',
589
+ hasChildPrompts: !!params.childPrompts?.length
590
+ },
591
+ maxErrorLength: params.maxErrorLength
592
+ });
593
+ }
585
594
  const endTime = new Date();
586
595
  const executionTimeMS = endTime.getTime() - startTime.getTime();
587
596
  // Update prompt run with error if it was created
@@ -707,8 +716,10 @@ export class AIPromptRunner {
707
716
  // Validation failed (Warn or Strict mode)
708
717
  errorMessage = `Validation failed: ${parsedResult.validationResult.Errors?.map(e => e.Message).join('; ')}`;
709
718
  }
719
+ const cancelled = !chatResult.success && this.isCallerCancellation(chatResult.errorInfo);
710
720
  return {
711
721
  success: chatResult.success,
722
+ ...(cancelled ? { status: 'Cancelled', cancelled: true, cancellationReason: 'user_requested' } : {}),
712
723
  rawResult: chatResult.data?.choices?.[0]?.message?.content,
713
724
  result: parsedResult?.result ? parsedResult.result : parsedResult,
714
725
  errorMessage, // Include error message for proper error propagation
@@ -2345,6 +2356,10 @@ export class AIPromptRunner {
2345
2356
  for (let i = 0; i < allCandidates.length; i++) {
2346
2357
  const candidate = allCandidates[i];
2347
2358
  const attemptStartTime = Date.now();
2359
+ // A caller that has cancelled wants no further model calls — not this candidate, not the next.
2360
+ if (cancellationToken?.aborted) {
2361
+ return this.stopFailoverForCancellation(prompt, this.buildCancellationError(), failoverAttempts, promptRun);
2362
+ }
2348
2363
  // Skip candidates with no credentials configured. `allCandidates` is intentionally the
2349
2364
  // FULL priority-ordered list (see the DECISION note in selectModelWithAPIKeyTracked),
2350
2365
  // so it can include vendors that have no API key in this environment. Firing a live
@@ -2376,6 +2391,17 @@ export class AIPromptRunner {
2376
2391
  }
2377
2392
  // Execute the model with this candidate
2378
2393
  const result = await this.executeModel(candidate.model, renderedPrompt, prompt, params, candidate.vendorId || null, conversationMessages, templateMessageRole, cancellationToken, candidate.driverClass, candidate.apiName, candidate.supportsEffortLevel, candidate.effortLevel);
2394
+ // A failure caused by the caller cancelling is the caller's decision, not the model's, so it
2395
+ // is neither failed over nor reported as a model failure. A result that already says it is
2396
+ // not eligible for failover (a driver's own cancelled result) is returned as it is; one that
2397
+ // would fail over is replaced by a cancellation.
2398
+ if (!result.success && (cancellationToken?.aborted || this.isCallerCancellation(result.errorInfo))) {
2399
+ if (result.errorInfo?.canFailover !== true) {
2400
+ this.logFailoverCancellation(prompt, failoverAttempts, promptRun);
2401
+ return result;
2402
+ }
2403
+ return this.stopFailoverForCancellation(prompt, this.buildCancellationError(), failoverAttempts, promptRun);
2404
+ }
2379
2405
  // CRITICAL FIX: Check if result failed but is retriable (network errors, rate limits, etc.)
2380
2406
  // Provider drivers (GeminiLLM, OpenAILLM, etc.) catch errors internally and return ChatResult{success: false}
2381
2407
  // instead of throwing, so we must check result.success here.
@@ -2406,6 +2432,11 @@ export class AIPromptRunner {
2406
2432
  lastError = error;
2407
2433
  // Analyze error to get error info
2408
2434
  const errorInfo = ErrorAnalyzer.analyzeError(lastError);
2435
+ const cancelledError = this.isCallerCancellation(this.carriedErrorInfo(lastError) ?? errorInfo);
2436
+ if (cancellationToken?.aborted || cancelledError) {
2437
+ const cancellation = cancelledError ? lastError : this.buildCancellationError();
2438
+ return this.stopFailoverForCancellation(prompt, cancellation, failoverAttempts, promptRun);
2439
+ }
2409
2440
  // Use shared failover error handling logic
2410
2441
  const decision = await this.processFailoverError(lastError, errorInfo, candidate, attemptStartTime, i, allCandidates, failoverAttempts, prompt, failoverConfig);
2411
2442
  // Update candidates list (may have been filtered)
@@ -2503,27 +2534,25 @@ export class AIPromptRunner {
2503
2534
  * Updates prompt run with successful failover tracking data
2504
2535
  */
2505
2536
  updatePromptRunWithFailoverSuccess(promptRun, failoverAttempts, currentModel, currentVendorId) {
2506
- promptRun.FailoverAttempts = failoverAttempts.length;
2507
- promptRun.FailoverErrors = JSON.stringify(failoverAttempts.map(a => ({
2508
- model: a.modelId,
2509
- vendor: a.vendorId,
2510
- error: a.error.message,
2511
- errorType: a.errorType
2512
- })));
2513
- promptRun.FailoverDurations = JSON.stringify(failoverAttempts.map(a => a.duration));
2514
- promptRun.TotalFailoverDuration = failoverAttempts.reduce((sum, a) => sum + a.duration, 0);
2515
- // Update ModelID if we ended up using a different model
2516
- if (!UUIDsEqual(currentModel.ID, promptRun.OriginalModelID)) {
2517
- promptRun.ModelID = currentModel.ID;
2518
- }
2519
- if (currentVendorId && !UUIDsEqual(currentVendorId, promptRun.VendorID)) {
2520
- promptRun.VendorID = currentVendorId;
2521
- }
2537
+ this.recordFailoverFields(promptRun, run => {
2538
+ this.applyFailoverAttempts(run, failoverAttempts);
2539
+ // Update ModelID if we ended up using a different model
2540
+ if (!UUIDsEqual(currentModel.ID, run.OriginalModelID)) {
2541
+ run.ModelID = currentModel.ID;
2542
+ }
2543
+ if (currentVendorId && !UUIDsEqual(currentVendorId, run.VendorID)) {
2544
+ run.VendorID = currentVendorId;
2545
+ }
2546
+ });
2522
2547
  }
2523
2548
  /**
2524
2549
  * Updates prompt run with failover failure tracking data
2525
2550
  */
2526
2551
  updatePromptRunWithFailoverFailure(promptRun, failoverAttempts) {
2552
+ this.recordFailoverFields(promptRun, run => this.applyFailoverAttempts(run, failoverAttempts));
2553
+ }
2554
+ /** Writes the failover attempts onto a prompt run: their count, errors and durations. */
2555
+ applyFailoverAttempts(promptRun, failoverAttempts) {
2527
2556
  promptRun.FailoverAttempts = failoverAttempts.length;
2528
2557
  promptRun.FailoverErrors = JSON.stringify(failoverAttempts.map(a => ({
2529
2558
  model: a.modelId,
@@ -2534,6 +2563,84 @@ export class AIPromptRunner {
2534
2563
  promptRun.FailoverDurations = JSON.stringify(failoverAttempts.map(a => a.duration));
2535
2564
  promptRun.TotalFailoverDuration = failoverAttempts.reduce((sum, a) => sum + a.duration, 0);
2536
2565
  }
2566
+ /**
2567
+ * Sets a prompt run's failover fields now, and again in the queued finalize update. The run's
2568
+ * 'Running' INSERT is queued without being awaited, and when it lands the entity reloads from what
2569
+ * was inserted — undoing any field set while it was in flight. Writing the fields inside the
2570
+ * finalize task, which runs after that reload, is what makes them persist.
2571
+ */
2572
+ recordFailoverFields(promptRun, apply) {
2573
+ apply(promptRun);
2574
+ this._pendingFailoverFields.set(promptRun, apply);
2575
+ }
2576
+ /**
2577
+ * Whether a failure was caused by the caller cancelling the request. The drivers and
2578
+ * {@link buildCancellationError} mark a cancellation the same way: not eligible for failover, with
2579
+ * the `request_cancelled` provider error code.
2580
+ */
2581
+ isCallerCancellation(errorInfo) {
2582
+ return errorInfo?.canFailover === false && errorInfo?.providerErrorCode === CALLER_CANCELLATION_CODE;
2583
+ }
2584
+ /**
2585
+ * The error for a model call the caller cancelled. It carries the same classification the drivers
2586
+ * give a cancelled request — Fatal and not eligible for failover — so ErrorAnalyzer, the failover
2587
+ * loop and the validation retries all stop on it rather than treating it as an unknown model error.
2588
+ */
2589
+ buildCancellationError(message) {
2590
+ const error = new Error(message || 'Chat completion was cancelled');
2591
+ error.errorInfo = {
2592
+ errorType: 'Unknown',
2593
+ severity: 'Fatal',
2594
+ canFailover: false,
2595
+ providerErrorCode: CALLER_CANCELLATION_CODE,
2596
+ };
2597
+ return error;
2598
+ }
2599
+ /**
2600
+ * Ends the failover loop for a caller cancellation: logs it once and returns the error result
2601
+ * without trying another candidate.
2602
+ */
2603
+ stopFailoverForCancellation(prompt, cancellation, failoverAttempts, promptRun) {
2604
+ this.logFailoverCancellation(prompt, failoverAttempts, promptRun);
2605
+ return this.createFailoverErrorResult(cancellation, failoverAttempts);
2606
+ }
2607
+ /**
2608
+ * Logs a caller cancellation that ended the failover loop, once and at info level, and records any
2609
+ * real failures that came before it on the prompt run.
2610
+ */
2611
+ logFailoverCancellation(prompt, failoverAttempts, promptRun) {
2612
+ LogStatusEx({
2613
+ message: `⏹️ Prompt "${prompt.Name}" was cancelled by the caller — not trying any further model candidates`,
2614
+ category: 'AI',
2615
+ additionalArgs: [{ promptId: prompt.ID, priorFailures: failoverAttempts.length }]
2616
+ });
2617
+ if (promptRun && failoverAttempts.length > 0) {
2618
+ this.updatePromptRunWithFailoverFailure(promptRun, failoverAttempts);
2619
+ }
2620
+ }
2621
+ /**
2622
+ * Whether an error ended a prompt run because the caller cancelled it: the caller's token is
2623
+ * aborted, or the error is classified as a cancellation.
2624
+ */
2625
+ isCancellation(error, params) {
2626
+ return params.cancellationToken?.aborted === true || this.isCallerCancellation(this.carriedErrorInfo(error) ?? ErrorAnalyzer.analyzeError(error));
2627
+ }
2628
+ /**
2629
+ * The classification an error already carries on `errorInfo`, if it has a complete one. This line's
2630
+ * ErrorAnalyzer re-reads every error from its message, which would turn a classified cancellation
2631
+ * back into an unknown, failover-eligible error.
2632
+ */
2633
+ carriedErrorInfo(error) {
2634
+ const info = error?.errorInfo;
2635
+ return info && typeof info.errorType === 'string' && typeof info.severity === 'string' && typeof info.canFailover === 'boolean'
2636
+ ? info
2637
+ : undefined;
2638
+ }
2639
+ /** The carried classification of an error that is a caller cancellation, else undefined. */
2640
+ carriedCancellation(error) {
2641
+ const carried = this.carriedErrorInfo(error);
2642
+ return this.isCallerCancellation(carried) ? carried : undefined;
2643
+ }
2537
2644
  /**
2538
2645
  * Creates an error result for failed failover attempts
2539
2646
  */
@@ -2546,7 +2653,7 @@ export class AIPromptRunner {
2546
2653
  // If ContextLengthExceeded and all failover attempts failed, this is fatal
2547
2654
  let errorInfo;
2548
2655
  if (lastError) {
2549
- errorInfo = ErrorAnalyzer.analyzeError(lastError);
2656
+ errorInfo = this.carriedCancellation(lastError) ?? ErrorAnalyzer.analyzeError(lastError);
2550
2657
  // Override severity to Fatal if context length exceeded and no larger models exist
2551
2658
  if (hasContextLengthError && errorInfo.errorType === 'ContextLengthExceeded') {
2552
2659
  errorInfo.severity = 'Fatal';
@@ -2559,7 +2666,7 @@ export class AIPromptRunner {
2559
2666
  errorMessage: lastError?.message || 'Unknown error',
2560
2667
  exception: lastError,
2561
2668
  errorInfo: errorInfo,
2562
- statusText: `Failover failed after ${failoverAttempts.length} attempts`,
2669
+ statusText: this.isCallerCancellation(errorInfo) ? 'Cancelled' : `Failover failed after ${failoverAttempts.length} attempts`,
2563
2670
  timeElapsed: endTime.getTime() - startTime.getTime(),
2564
2671
  data: null
2565
2672
  };
@@ -2738,6 +2845,10 @@ export class AIPromptRunner {
2738
2845
  }
2739
2846
  catch (error) {
2740
2847
  const errorInfo = ErrorAnalyzer.analyzeError(error, driverClass);
2848
+ // A caller cancellation is not a model failure. Whoever handles it logs it once, at info level.
2849
+ if (this.isCallerCancellation(this.carriedErrorInfo(error) ?? errorInfo)) {
2850
+ throw error;
2851
+ }
2741
2852
  this.logError(error, {
2742
2853
  category: 'ModelExecution',
2743
2854
  model: model,
@@ -2855,18 +2966,26 @@ export class AIPromptRunner {
2855
2966
  // Neither a caller token nor a prompt timeout — execute unbounded (legacy behavior).
2856
2967
  return await llm.ChatCompletion(chatParams);
2857
2968
  }
2858
- return await Promise.race([
2859
- llm.ChatCompletion(chatParams),
2860
- new Promise((_, reject) => {
2861
- const fail = () => reject(this.buildAbortError(signal, bound));
2862
- if (signal.aborted) {
2863
- fail();
2864
- }
2865
- else {
2866
- signal.addEventListener('abort', fail, { once: true });
2867
- }
2868
- }),
2869
- ]);
2969
+ let fail;
2970
+ const aborted = new Promise((_, reject) => {
2971
+ fail = () => reject(this.buildAbortError(signal, bound));
2972
+ if (signal.aborted) {
2973
+ fail();
2974
+ }
2975
+ else {
2976
+ signal.addEventListener('abort', fail, { once: true });
2977
+ }
2978
+ });
2979
+ try {
2980
+ return await Promise.race([llm.ChatCompletion(chatParams), aborted]);
2981
+ }
2982
+ finally {
2983
+ // With no prompt timeout the signal is the caller's own token, which outlives this call: a
2984
+ // listener left on it would pile up across every prompt the caller runs.
2985
+ if (fail) {
2986
+ signal.removeEventListener('abort', fail);
2987
+ }
2988
+ }
2870
2989
  }
2871
2990
  /**
2872
2991
  * Builds the rejection error for an aborted model call — a typed {@link AIPromptTimeoutError} when
@@ -2877,7 +2996,7 @@ export class AIPromptRunner {
2877
2996
  const reason = signal.reason;
2878
2997
  return reason instanceof AIPromptTimeoutError ? reason : new Error('Chat completion timed out');
2879
2998
  }
2880
- return new Error('Chat completion was cancelled');
2999
+ return this.buildCancellationError();
2881
3000
  }
2882
3001
  /**
2883
3002
  * Walks every message in chatParams and rewrites media content blocks
@@ -3340,6 +3459,10 @@ export class AIPromptRunner {
3340
3459
  }
3341
3460
  }
3342
3461
  catch (error) {
3462
+ // A cancellation ends the retries; the caller logs it and records the run as cancelled.
3463
+ if (this.isCancellation(error, params)) {
3464
+ throw error;
3465
+ }
3343
3466
  lastError = error;
3344
3467
  this.logError(error, {
3345
3468
  category: 'ExecutionRetry',
@@ -3904,7 +4027,35 @@ export class AIPromptRunner {
3904
4027
  return parsedResult;
3905
4028
  }
3906
4029
  /**
3907
- * Attempts to repair malformed JSON using a two-step process.
4030
+ * Resolves the parse error that actually describes the model's output.
4031
+ *
4032
+ * The error reaching the repair path comes from `JSON.parse(CleanJSON(rawOutput))`, so it may
4033
+ * describe one of CleanJSON's intermediate transforms rather than the response itself. That
4034
+ * distinction is not cosmetic: a repair pass needs the failure offset in the *original* bytes,
4035
+ * and the AI repair prompt is actively misled by an error describing text it was never shown.
4036
+ *
4037
+ * Observed in production: an unescaped quote at offset 23011 was reported as
4038
+ * `Unexpected token 'm', "mermaid\ns"...` because CleanJSON had extracted a mermaid fence out of
4039
+ * a string value before failing. Every downstream consumer — the repair model, the validation
4040
+ * record, the logs — inherited that misdiagnosis.
4041
+ *
4042
+ * @param rawOutput - The model's unmodified output
4043
+ * @param originalError - The error caught upstream, used as a fallback
4044
+ * @returns The message that best describes what is wrong with `rawOutput`
4045
+ */
4046
+ resolveTrueParseError(rawOutput, originalError) {
4047
+ try {
4048
+ JSON.parse(rawOutput);
4049
+ }
4050
+ catch (directError) {
4051
+ return directError instanceof Error ? directError.message : String(directError);
4052
+ }
4053
+ // rawOutput parses cleanly, so the failure came from a later stage; the caller's error stands.
4054
+ return originalError.message;
4055
+ }
4056
+ /**
4057
+ * Attempts to repair malformed JSON using a multi-step process: JSON5, then deterministic
4058
+ * lexical repair, then an AI repair prompt.
3908
4059
  *
3909
4060
  * @param rawOutput - The malformed JSON string
3910
4061
  * @param originalError - The original parsing error
@@ -3955,8 +4106,31 @@ export class AIPromptRunner {
3955
4106
  return json5Result;
3956
4107
  }
3957
4108
  catch (json5Error) {
3958
- // Step 2: Use AI to repair the JSON
3959
- this.logStatus(' 🤖 JSON5 failed, attempting AI-based JSON repair...', true, params);
4109
+ // The error handed to us may describe a CleanJSON transform rather than the model's actual
4110
+ // output — CleanJSON rewrites the text through several passes before failing, and the error
4111
+ // that escapes describes whatever it was holding at the end. Repairing, and telling a model
4112
+ // what to repair, both require the real syntax error against the real bytes.
4113
+ const trueError = this.resolveTrueParseError(rawOutput, originalError);
4114
+ // Step 2: Deterministic lexical repair. The dominant failure by far is an unescaped quote or
4115
+ // raw control character inside a string value — models embed mermaid diagrams, HTML mockups
4116
+ // and code samples in markdown fields and miss an escape. JSON5 cannot help (an unescaped
4117
+ // quote closes a string in JSON5 too), but the defect is mechanical, so fixing it needs no
4118
+ // model call. Runs before the AI stage: it is microseconds against an LLM round-trip on a
4119
+ // payload that may be tens of KB, and it cannot invent content the way a model can.
4120
+ const lexicalRepair = RepairJSONEscaping(rawOutput);
4121
+ if (lexicalRepair.repaired) {
4122
+ this.logStatus(` ✅ Lexical repair fixed ${lexicalRepair.repairedOffsets.length} unescaped character(s)`, true, params);
4123
+ currentPromptRun._jsonRepairInfo = {
4124
+ repaired: true,
4125
+ method: 'LexicalEscaping',
4126
+ originalError: trueError,
4127
+ rawOutputPrefix: rawOutput.substring(0, 200),
4128
+ repairedOffsets: lexicalRepair.repairedOffsets
4129
+ };
4130
+ return lexicalRepair.value;
4131
+ }
4132
+ // Step 3: Use AI to repair the JSON
4133
+ this.logStatus(' 🤖 JSON5 and lexical repair failed, attempting AI-based JSON repair...', true, params);
3960
4134
  try {
3961
4135
  // Find the "Repair JSON" prompt in the "MJ: System" category
3962
4136
  const repairPrompt = AIEngine.Instance.Prompts.find(p => p.Name.trim().toLowerCase() === 'repair json' && p.Category.trim().toLowerCase() === 'mj: system');
@@ -3969,7 +4143,7 @@ export class AIPromptRunner {
3969
4143
  contextUser: params.contextUser,
3970
4144
  prompt: repairPrompt,
3971
4145
  data: {
3972
- ERROR_MESSAGE: originalError.message,
4146
+ ERROR_MESSAGE: trueError,
3973
4147
  MALFORMED_JSON: rawOutput
3974
4148
  },
3975
4149
  skipValidation: true // don't want to validate as this would cause recursive infinity scenario if the JSON is invalid. Just one shot, fix or no fix
@@ -3988,7 +4162,7 @@ export class AIPromptRunner {
3988
4162
  currentPromptRun._jsonRepairInfo = {
3989
4163
  repaired: true,
3990
4164
  method: 'AIRepair',
3991
- originalError: originalError.message,
4165
+ originalError: trueError,
3992
4166
  rawOutputPrefix: rawOutput.substring(0, 200),
3993
4167
  repairPromptRunId: repairResult.promptRun?.ID
3994
4168
  };
@@ -3999,14 +4173,15 @@ export class AIPromptRunner {
3999
4173
  this.logError(aiRepairError, {
4000
4174
  category: 'JSONRepairFailed',
4001
4175
  metadata: {
4002
- originalError: originalError.message,
4176
+ originalError: trueError,
4003
4177
  json5Error: json5Error.message,
4178
+ lexicalRepairReason: lexicalRepair.reason,
4004
4179
  aiError: aiRepairError.message,
4005
4180
  rawOutput: rawOutput.substring(0, 500)
4006
4181
  },
4007
4182
  maxErrorLength: params.maxErrorLength
4008
4183
  });
4009
- throw new Error(`JSON repair failed after both JSON5 and AI attempts: ${originalError.message}`);
4184
+ throw new Error(`JSON repair failed after JSON5, lexical and AI attempts: ${trueError}`);
4010
4185
  }
4011
4186
  }
4012
4187
  }
@@ -4302,6 +4477,16 @@ export class AIPromptRunner {
4302
4477
  promptRun.Success = modelResult.success && (parsedResult.validationResult?.Success !== false);
4303
4478
  // Set final Status based on success
4304
4479
  promptRun.Status = promptRun.Success ? 'Completed' : 'Failed';
4480
+ // A call the caller cancelled is recorded as cancelled, not as a failed model call.
4481
+ if (!modelResult.success && this.isCallerCancellation(modelResult.errorInfo)) {
4482
+ promptRun.Status = 'Cancelled';
4483
+ promptRun.Cancelled = true;
4484
+ promptRun.CancellationReason = 'user_requested';
4485
+ }
4486
+ // The failover fields were set while the INSERT may still have been in flight, and its reload
4487
+ // would have undone them: set them again here, after the reload.
4488
+ this._pendingFailoverFields.get(promptRun)?.(promptRun);
4489
+ this._pendingFailoverFields.delete(promptRun);
4305
4490
  // Set ErrorDetails if failed
4306
4491
  if (!promptRun.Success) {
4307
4492
  if (!modelResult.success && modelResult.errorMessage) {